# -*- coding: cp1254 -*-
from header_common import *
from header_operations import *
from module_constants import *
from header_parties import *
from header_skills import *
from header_mission_templates import *
from header_items import *
from header_triggers import *
from header_terrain_types import *
from header_troops import *
from header_item_modifiers import *
from module_items import *
from module_troops import *
from setting_sango import *
#from header_subsystem_exec import *


####################################################################################################################
# scripts is a list of script records.
# Each script record contns the following two fields:
# 1) Script id: The prefix "script_" will be inserted when referencing scripts.
# 2) Operation block: This must be a valid operation block. See header_operations.py for reference.
####################################################################################################################
scripts_defined=1
scripts = [

  #game_start:
  # This script is called when a new game is started
  # INPUT: none
  ("game_start",
   [
      (call_script, "script_update_party_creation_random_limits"),       
# Reseting player party icon
      (assign, "$g_player_party_icon", -1),
# Setting food bonuses
      (item_set_slot, "itm_smoked_fish", slot_item_food_bonus, 3),
      (item_set_slot, "itm_dried_meat", slot_item_food_bonus, 4),
      (item_set_slot, "itm_apples", slot_item_food_bonus, 2),
      (item_set_slot, "itm_honey", slot_item_food_bonus, 5),
      (item_set_slot, "itm_cabbages", slot_item_food_bonus, 1),
      (item_set_slot, "itm_butter", slot_item_food_bonus, 5),
      (item_set_slot, "itm_meat", slot_item_food_bonus, 4),
      (item_set_slot, "itm_paddy", slot_item_food_bonus, 2),
	  (item_set_slot, "itm_fish", slot_item_food_bonus, 3),      
	  
      (item_set_slot, "itm_wine", slot_item_food_bonus, 4),
      (item_set_slot, "itm_baijiu", slot_item_food_bonus, 4),
      (item_set_slot, "itm_ale", slot_item_food_bonus, 3),
      
# Setting the random town sequence:
      (store_sub, ":num_towns", towns_end, towns_begin),
      (assign, ":num_iterations", ":num_towns"),
      (try_for_range, ":cur_town_no", 0, ":num_towns"),
        (troop_set_slot, "trp_random_town_sequence", ":cur_town_no", -1),
      (try_end),
      (assign, ":cur_town_no", 0),
      (try_for_range, ":unused", 0, ":num_iterations"),
        (store_random_in_range, ":random_no", 0, ":num_towns"),
        (assign, ":is_unique", 1),
        (try_for_range, ":cur_town_no_2", 0, ":num_towns"),
          (troop_slot_eq, "trp_random_town_sequence", ":cur_town_no_2", ":random_no"),
          (assign, ":is_unique", 0),
        (try_end),
        (try_begin),
          (eq, ":is_unique", 1),
          (troop_set_slot, "trp_random_town_sequence", ":cur_town_no", ":random_no"),
          (val_add, ":cur_town_no", 1),
        (else_try),
          (val_add, ":num_iterations", 1),
        (try_end),
      (try_end),
# Cultures:
      (faction_set_slot, "fac_culture_1",  slot_faction_tier_1_troop, "trp_wei_youth"),
      (faction_set_slot, "fac_culture_1",  slot_faction_tier_2_troop, "trp_wei_solider"),
      (faction_set_slot, "fac_culture_1",  slot_faction_tier_3_troop, "trp_wei_footman"),
      (faction_set_slot, "fac_culture_1",  slot_faction_tier_4_troop, "trp_wei_elite_footman"),
      (faction_set_slot, "fac_culture_1",  slot_faction_tier_5_troop, "trp_wei_heavy_cavalry"),


      (faction_set_slot, "fac_culture_2", slot_faction_tier_1_troop, "trp_shu_youth"),
      (faction_set_slot, "fac_culture_2", slot_faction_tier_2_troop, "trp_shu_solider"),
      (faction_set_slot, "fac_culture_2", slot_faction_tier_3_troop, "trp_shu_infantry"),
      (faction_set_slot, "fac_culture_2", slot_faction_tier_4_troop, "trp_elite_shu_infantry"),
      (faction_set_slot, "fac_culture_2", slot_faction_tier_5_troop, "trp_shu_armed_horseman_elite"),

      (faction_set_slot, "fac_culture_3", slot_faction_tier_1_troop, "trp_wu_youth"),
      (faction_set_slot, "fac_culture_3", slot_faction_tier_2_troop, "trp_wu_solider"),
      (faction_set_slot, "fac_culture_3", slot_faction_tier_3_troop, "trp_feather_army"),
      (faction_set_slot, "fac_culture_3", slot_faction_tier_4_troop, "trp_feather_army_elite"),
      (faction_set_slot, "fac_culture_3", slot_faction_tier_5_troop, "trp_wu_elite_rider"),

#      (faction_set_slot, "fac_culture_4", slot_faction_tier_1_troop, "trp_nord_recruit"),
#      (faction_set_slot, "fac_culture_4", slot_faction_tier_2_troop, "trp_nord_footman"),
#      (faction_set_slot, "fac_culture_4", slot_faction_tier_3_troop, "trp_nord_trained_footman"),
#      (faction_set_slot, "fac_culture_4", slot_faction_tier_4_troop, "trp_nord_warrior"),
#      (faction_set_slot, "fac_culture_4", slot_faction_tier_5_troop, "trp_nord_veteran"),

#      (faction_set_slot, "fac_culture_5", slot_faction_tier_1_troop, "trp_rhodok_tribesman"),
#      (faction_set_slot, "fac_culture_5", slot_faction_tier_2_troop, "trp_rhodok_spearman"),
#      (faction_set_slot, "fac_culture_5", slot_faction_tier_3_troop, "trp_rhodok_trained_spearman"),
#      (faction_set_slot, "fac_culture_5", slot_faction_tier_4_troop, "trp_rhodok_veteran_spearman"),
#      (faction_set_slot, "fac_culture_5", slot_faction_tier_5_troop, "trp_rhodok_sergeant"),
      
# Factions:
      (faction_set_slot, "fac_kingdom_caowei",  slot_faction_culture, "fac_culture_1"),
      (faction_set_slot, "fac_kingdom_caowei",  slot_faction_leader, "trp_caocao"),

      (faction_set_slot, "fac_kingdom_shuhan",  slot_faction_culture, "fac_culture_2"),
      (faction_set_slot, "fac_kingdom_shuhan",  slot_faction_leader, "trp_liubei"),

      (faction_set_slot, "fac_kingdom_wu",  slot_faction_culture, "fac_culture_3"),
      (faction_set_slot, "fac_kingdom_wu",  slot_faction_leader, "trp_sunquan"),

#      (faction_set_slot, "fac_kingdom_4",  slot_faction_culture, "fac_culture_4"),
#      (faction_set_slot, "fac_kingdom_4",  slot_faction_leader, "trp_kingdom_4_lord"),

#      (faction_set_slot, "fac_kingdom_5",  slot_faction_culture, "fac_culture_5"),
#      (faction_set_slot, "fac_kingdom_5",  slot_faction_leader, "trp_kingdom_5_lord"),

      (call_script, "script_diplomacy_start_war_between_kingdoms", "fac_kingdom_caowei", "fac_kingdom_shuhan"),
	  (call_script, "script_diplomacy_start_war_between_kingdoms", "fac_kingdom_wu", "fac_kingdom_shuhan"),
	  (call_script, "script_diplomacy_start_war_between_kingdoms", "fac_kingdom_wu", "fac_kingdom_caowei"),
#      (call_script, "script_diplomacy_start_war_between_kingdoms", "fac_kingdom_caowei", "fac_kingdom_5"),
#      (call_script, "script_diplomacy_start_war_between_kingdoms", "fac_kingdom_4", "fac_kingdom_shuhan"),
#      (call_script, "script_diplomacy_start_war_between_kingdoms", "fac_kingdom_4", "fac_kingdom_caowei"),
#      (call_script, "script_diplomacy_start_war_between_kingdoms", "fac_kingdom_wu", "fac_kingdom_shuhan"),
#      (call_script, "script_diplomacy_start_war_between_kingdoms", "fac_kingdom_wu", "fac_kingdom_5"),

      (try_for_range, ":faction_no", kingdoms_begin, kingdoms_end),
        (faction_get_slot, ":culture", ":faction_no", slot_faction_culture),
      
        (faction_get_slot, ":troop", ":culture",  slot_faction_tier_1_troop),
        (faction_set_slot, ":faction_no",  slot_faction_tier_1_troop, ":troop"),
        (faction_get_slot, ":troop", ":culture",  slot_faction_tier_2_troop),
        (faction_set_slot, ":faction_no",  slot_faction_tier_2_troop, ":troop"),
        (faction_get_slot, ":troop", ":culture",  slot_faction_tier_3_troop),
        (faction_set_slot, ":faction_no",  slot_faction_tier_3_troop, ":troop"),
        (faction_get_slot, ":troop", ":culture",  slot_faction_tier_4_troop),
        (faction_set_slot, ":faction_no",  slot_faction_tier_4_troop, ":troop"),
        (faction_get_slot, ":troop", ":culture",  slot_faction_tier_5_troop),
        (faction_set_slot, ":faction_no",  slot_faction_tier_5_troop, ":troop"),
      
        (try_begin),
          (faction_slot_eq, ":faction_no", slot_faction_culture, "fac_culture_1"),
      
          (faction_set_slot, ":faction_no",  slot_faction_deserter_troop, "trp_mercenary"),
          (faction_set_slot, ":faction_no",  slot_faction_guard_troop, "trp_wei_elite_footman"),
          (faction_set_slot, ":faction_no",  slot_faction_messenger_troop, "trp_wei_light_cavalry"),
          (faction_set_slot, ":faction_no",  slot_faction_prison_guard_troop, "trp_wei_heavy_cavalry"),
          (faction_set_slot, ":faction_no",  slot_faction_castle_guard_troop, "trp_armored_guarder"),
          (faction_set_slot, ":faction_no",  slot_faction_reinforcements_a, "pt_kingdom_1_reinforcements_a"),
          (faction_set_slot, ":faction_no",  slot_faction_reinforcements_b, "pt_kingdom_1_reinforcements_b"),
          (faction_set_slot, ":faction_no",  slot_faction_reinforcements_c, "pt_kingdom_1_reinforcements_c"),
        (else_try),
          (faction_slot_eq, ":faction_no", slot_faction_culture, "fac_culture_2"),
      
          (faction_set_slot, ":faction_no", slot_faction_deserter_troop, "trp_mercenary"),
          (faction_set_slot, ":faction_no", slot_faction_guard_troop, "trp_elite_shu_infantry"),
          (faction_set_slot, ":faction_no", slot_faction_messenger_troop, "trp_shu_horseman"),
          (faction_set_slot, ":faction_no", slot_faction_prison_guard_troop, "trp_shu_elite_horseman"),
          (faction_set_slot, ":faction_no", slot_faction_castle_guard_troop, "trp_shu_unstopped_horseman"),
          (faction_set_slot, ":faction_no",  slot_faction_reinforcements_a, "pt_kingdom_2_reinforcements_a"),
          (faction_set_slot, ":faction_no",  slot_faction_reinforcements_b, "pt_kingdom_2_reinforcements_b"),
          (faction_set_slot, ":faction_no",  slot_faction_reinforcements_c, "pt_kingdom_2_reinforcements_c"),
        (else_try),
          (faction_slot_eq, ":faction_no", slot_faction_culture, "fac_culture_3"),
      
          (faction_set_slot, ":faction_no", slot_faction_deserter_troop, "trp_mercenary"),
          (faction_set_slot, ":faction_no", slot_faction_guard_troop, "trp_feather_army"),
          (faction_set_slot, ":faction_no", slot_faction_messenger_troop, "trp_wu_rider"),
          (faction_set_slot, ":faction_no", slot_faction_prison_guard_troop, "trp_wu_trouble_dealing_army"),
          (faction_set_slot, ":faction_no", slot_faction_castle_guard_troop, "trp_feather_army"),
          (faction_set_slot, ":faction_no",  slot_faction_reinforcements_a, "pt_kingdom_3_reinforcements_a"),
          (faction_set_slot, ":faction_no",  slot_faction_reinforcements_b, "pt_kingdom_3_reinforcements_b"),
          (faction_set_slot, ":faction_no",  slot_faction_reinforcements_c, "pt_kingdom_3_reinforcements_c"),
#        (else_try),
#          (faction_slot_eq, ":faction_no", slot_faction_culture, "fac_culture_4"),
      
#          (faction_set_slot, ":faction_no", slot_faction_deserter_troop, "trp_nord_deserter"),
#          (faction_set_slot, ":faction_no", slot_faction_guard_troop, "trp_nord_warrior"),
#          (faction_set_slot, ":faction_no", slot_faction_messenger_troop, "trp_nord_messenger"),
#          (faction_set_slot, ":faction_no", slot_faction_prison_guard_troop, "trp_nord_prison_guard"),
#          (faction_set_slot, ":faction_no", slot_faction_castle_guard_troop, "trp_nord_castle_guard"),
#          (faction_set_slot, ":faction_no",  slot_faction_reinforcements_a, "pt_kingdom_4_reinforcements_a"),
#          (faction_set_slot, ":faction_no",  slot_faction_reinforcements_b, "pt_kingdom_4_reinforcements_b"),
#          (faction_set_slot, ":faction_no",  slot_faction_reinforcements_c, "pt_kingdom_4_reinforcements_c"),
#        (else_try),
#          (faction_slot_eq, ":faction_no", slot_faction_culture, "fac_culture_5"),
      
#          (faction_set_slot, ":faction_no", slot_faction_deserter_troop, "trp_rhodok_deserter"),
#          (faction_set_slot, ":faction_no", slot_faction_guard_troop, "trp_rhodok_veteran_spearman"),
#          (faction_set_slot, ":faction_no", slot_faction_messenger_troop, "trp_rhodok_messenger"),
#          (faction_set_slot, ":faction_no", slot_faction_prison_guard_troop, "trp_rhodok_prison_guard"),
#          (faction_set_slot, ":faction_no", slot_faction_castle_guard_troop, "trp_rhodok_castle_guard"),
#          (faction_set_slot, ":faction_no",  slot_faction_reinforcements_a, "pt_kingdom_5_reinforcements_a"),
#          (faction_set_slot, ":faction_no",  slot_faction_reinforcements_b, "pt_kingdom_5_reinforcements_b"),
#          (faction_set_slot, ":faction_no",  slot_faction_reinforcements_c, "pt_kingdom_5_reinforcements_c"),
        (try_end),
      (try_end),



      
# Towns:
      (try_for_range, ":item_no", trade_goods_begin, trade_goods_end),
        (store_sub, ":offset", ":item_no", trade_goods_begin),
        (val_add, ":offset", slot_town_trade_good_prices_begin),
        (try_for_range, ":center_no", centers_begin, centers_end),
          (party_set_slot, ":center_no", ":offset", average_price_factor),
        (try_end),
        (party_set_slot, "p_zendar", ":offset", average_price_factor),
        (party_set_slot, "p_salt_mine", ":offset", average_price_factor),
        (party_set_slot, "p_four_ways_inn", ":offset", average_price_factor),
      (try_end),

      (try_for_range, ":town_no", towns_begin, towns_end),
        (call_script, "script_center_set_trade_good_production", ":town_no", "itm_smoked_fish", -15),
        (call_script, "script_center_set_trade_good_production", ":town_no", "itm_dried_meat", -25),
        (call_script, "script_center_set_trade_good_production", ":town_no", "itm_honey", -15),
        (call_script, "script_center_set_trade_good_production", ":town_no", "itm_cabbages", -20),
        (call_script, "script_center_set_trade_good_production", ":town_no", "itm_butter", -20),
        (call_script, "script_center_set_trade_good_production", ":town_no", "itm_wine", -20),
        (call_script, "script_center_set_trade_good_production", ":town_no", "itm_flour", -20),
        (call_script, "script_center_set_trade_good_production", ":town_no", "itm_ale", -10),
        (call_script, "script_center_set_trade_good_production", ":town_no", "itm_apples", -20),
        (call_script, "script_center_set_trade_good_production", ":town_no", "itm_grain", -40),

##        (call_script, "script_center_set_trade_good_production", "p_town_1", "itm_iron", -20),
##        (call_script, "script_center_set_trade_good_production", "p_town_2", "itm_wool", -30),
##        (call_script, "script_center_set_trade_good_production", "p_town_4", "itm_furs", -30),
##        (call_script, "script_center_set_trade_good_production", "p_town_4", "itm_oil", -30),
##        (call_script, "script_center_set_trade_good_production", "p_town_5", "itm_velvet", -10),
##        (call_script, "script_center_set_trade_good_production", "p_town_10", "itm_spice", -15),
##        (call_script, "script_center_set_trade_good_production", "p_town_14", "itm_linen", -10),
      (try_end),
	  (call_script,"script_sango_init_city"),
      
##      (party_set_slot,"p_town_1", slot_town_arena_melee_1_num_teams,   2),
##      (party_set_slot,"p_town_1", slot_town_arena_melee_1_team_size,   1),
##      (party_set_slot,"p_town_1", slot_town_arena_melee_2_num_teams,   4),
##      (party_set_slot,"p_town_1", slot_town_arena_melee_2_team_size,   1),
##      (party_set_slot,"p_town_1", slot_town_arena_melee_3_num_teams,   4),
##      (party_set_slot,"p_town_1", slot_town_arena_melee_3_team_size,   1),
##      (call_script, "script_center_set_trade_good_production", "p_town_1", "itm_linen", 40),
##      (call_script, "script_center_set_trade_good_production", "p_town_1", "itm_iron", -30),
##
##      (party_set_slot,"p_town_2", slot_town_arena_melee_1_num_teams,   4),
##      (party_set_slot,"p_town_2", slot_town_arena_melee_1_team_size,   4),
##      (party_set_slot,"p_town_2", slot_town_arena_melee_2_num_teams,   4),
##      (party_set_slot,"p_town_2", slot_town_arena_melee_2_team_size,   6),
##      (party_set_slot,"p_town_2", slot_town_arena_melee_3_num_teams,   4),
##      (party_set_slot,"p_town_2", slot_town_arena_melee_3_team_size,   8),
##      (call_script, "script_center_set_trade_good_production", "p_town_2", "itm_smoked_fish", 50),
##      (call_script, "script_center_set_trade_good_production", "p_town_2", "itm_wool", -30),
##      
##      (party_set_slot,"p_town_3", slot_town_arena_melee_1_num_teams,   2),
##      (party_set_slot,"p_town_3", slot_town_arena_melee_1_team_size,   8),
##      (party_set_slot,"p_town_3", slot_town_arena_melee_2_num_teams,   2),
##      (party_set_slot,"p_town_3", slot_town_arena_melee_2_team_size,   8),
##      (party_set_slot,"p_town_3", slot_town_arena_melee_3_num_teams,   2),
##      (party_set_slot,"p_town_3", slot_town_arena_melee_3_team_size,   8),
##      (call_script, "script_center_set_trade_good_production", "p_town_3", "itm_wine", 30),
##      (call_script, "script_center_set_trade_good_production", "p_town_3", "itm_dried_meat", -40),
##
##      (party_set_slot,"p_town_4", slot_town_arena_melee_1_num_teams,   2),
##      (party_set_slot,"p_town_4", slot_town_arena_melee_1_team_size,   8),
##      (party_set_slot,"p_town_4", slot_town_arena_melee_2_num_teams,   3),
##      (party_set_slot,"p_town_4", slot_town_arena_melee_2_team_size,   8),
##      (party_set_slot,"p_town_4", slot_town_arena_melee_3_num_teams,   2),
##      (party_set_slot,"p_town_4", slot_town_arena_melee_3_team_size,   5),
##      (call_script, "script_center_set_trade_good_production", "p_town_4", "itm_oil", 40),
##      (call_script, "script_center_set_trade_good_production", "p_town_4", "itm_furs", -40),
##      
##      (party_set_slot,"p_town_5", slot_town_arena_melee_1_num_teams,   2),
##      (party_set_slot,"p_town_5", slot_town_arena_melee_1_team_size,   3),
##      (party_set_slot,"p_town_5", slot_town_arena_melee_2_num_teams,   2),
##      (party_set_slot,"p_town_5", slot_town_arena_melee_2_team_size,   5),
##      (party_set_slot,"p_town_5", slot_town_arena_melee_3_num_teams,   2),
##      (party_set_slot,"p_town_5", slot_town_arena_melee_3_team_size,   8),
##      (call_script, "script_center_set_trade_good_production", "p_town_5", "itm_velvet", 40),
##      (call_script, "script_center_set_trade_good_production", "p_town_5", "itm_pottery", -40),
##
##      (party_set_slot,"p_town_6", slot_town_arena_melee_1_num_teams,   2),
##      (party_set_slot,"p_town_6", slot_town_arena_melee_1_team_size,   4),
##      (party_set_slot,"p_town_6", slot_town_arena_melee_2_num_teams,   3),
##      (party_set_slot,"p_town_6", slot_town_arena_melee_2_team_size,   4),
##      (party_set_slot,"p_town_6", slot_town_arena_melee_3_num_teams,   3),
##      (party_set_slot,"p_town_6", slot_town_arena_melee_3_team_size,   6),
##      (call_script, "script_center_set_trade_good_production", "p_town_6", "itm_ale", 40),
##      (call_script, "script_center_set_trade_good_production", "p_town_6", "itm_spice", -40),
##
##      (party_set_slot,"p_town_7", slot_town_arena_melee_1_num_teams,   4),
##      (party_set_slot,"p_town_7", slot_town_arena_melee_1_team_size,   4),
##      (party_set_slot,"p_town_7", slot_town_arena_melee_2_num_teams,   4),
##      (party_set_slot,"p_town_7", slot_town_arena_melee_2_team_size,   6),
##      (party_set_slot,"p_town_7", slot_town_arena_melee_3_num_teams,   4),
##      (party_set_slot,"p_town_7", slot_town_arena_melee_3_team_size,   8),
##      (call_script, "script_center_set_trade_good_production", "p_town_7", "itm_grain", 40),
##      (call_script, "script_center_set_trade_good_production", "p_town_7", "itm_smoked_fish", -40),
##
##      (party_set_slot,"p_town_8", slot_town_arena_melee_1_num_teams,   3),
##      (party_set_slot,"p_town_8", slot_town_arena_melee_1_team_size,   1),
##      (party_set_slot,"p_town_8", slot_town_arena_melee_2_num_teams,   3),
##      (party_set_slot,"p_town_8", slot_town_arena_melee_2_team_size,   3),
##      (party_set_slot,"p_town_8", slot_town_arena_melee_3_num_teams,   3),
##      (party_set_slot,"p_town_8", slot_town_arena_melee_3_team_size,   7),
##      (call_script, "script_center_set_trade_good_production", "p_town_8", "itm_wool", 40),
##      (call_script, "script_center_set_trade_good_production", "p_town_8", "itm_velvet", -40),
##
##      (party_set_slot,"p_town_9", slot_town_arena_melee_1_num_teams,   2),
##      (party_set_slot,"p_town_9", slot_town_arena_melee_1_team_size,   2),
##      (party_set_slot,"p_town_9", slot_town_arena_melee_2_num_teams,   2),
##      (party_set_slot,"p_town_9", slot_town_arena_melee_2_team_size,   5),
##      (party_set_slot,"p_town_9", slot_town_arena_melee_3_num_teams,   2),
##      (party_set_slot,"p_town_9", slot_town_arena_melee_3_team_size,   8),
##      (call_script, "script_center_set_trade_good_production", "p_town_9", "itm_furs", 40),
##      (call_script, "script_center_set_trade_good_production", "p_town_9", "itm_ale", -40),
##
##      (party_set_slot,"p_town_10", slot_town_arena_melee_1_num_teams,   2),
##      (party_set_slot,"p_town_10", slot_town_arena_melee_1_team_size,   3),
##      (party_set_slot,"p_town_10", slot_town_arena_melee_2_num_teams,   2),
##      (party_set_slot,"p_town_10", slot_town_arena_melee_2_team_size,   5),
##      (party_set_slot,"p_town_10", slot_town_arena_melee_3_num_teams,   2),
##      (party_set_slot,"p_town_10", slot_town_arena_melee_3_team_size,   8),
##      (call_script, "script_center_set_trade_good_production", "p_town_10", "itm_spice", 20),
##      (call_script, "script_center_set_trade_good_production", "p_town_10", "itm_grain", -40),
##      (call_script, "script_center_set_trade_good_production", "p_town_10", "itm_tools", -40),
##
##      (party_set_slot,"p_town_11", slot_town_arena_melee_1_num_teams,   2),
##      (party_set_slot,"p_town_11", slot_town_arena_melee_1_team_size,   8),
##      (party_set_slot,"p_town_11", slot_town_arena_melee_2_num_teams,   3),
##      (party_set_slot,"p_town_11", slot_town_arena_melee_2_team_size,   4),
##      (party_set_slot,"p_town_11", slot_town_arena_melee_3_num_teams,   3),
##      (party_set_slot,"p_town_11", slot_town_arena_melee_3_team_size,   6),
##      (call_script, "script_center_set_trade_good_production", "p_town_11", "itm_iron", 50),
##      (call_script, "script_center_set_trade_good_production", "p_town_11", "itm_dried_meat", -50),
##
##      (party_set_slot,"p_town_12", slot_town_arena_melee_1_num_teams,   3),
##      (party_set_slot,"p_town_12", slot_town_arena_melee_1_team_size,   8),
##      (party_set_slot,"p_town_12", slot_town_arena_melee_2_num_teams,   4),
##      (party_set_slot,"p_town_12", slot_town_arena_melee_2_team_size,   6),
##      (party_set_slot,"p_town_12", slot_town_arena_melee_3_num_teams,   4),
##      (party_set_slot,"p_town_12", slot_town_arena_melee_3_team_size,   5),
##      (call_script, "script_center_set_trade_good_production", "p_town_12", "itm_smoked_fish", 50),
##      (call_script, "script_center_set_trade_good_production", "p_town_12", "itm_wine", -60),
##
##      (party_set_slot,"p_town_13", slot_town_arena_melee_1_num_teams,   2),
##      (party_set_slot,"p_town_13", slot_town_arena_melee_1_team_size,   8),
##      (party_set_slot,"p_town_13", slot_town_arena_melee_2_num_teams,   4),
##      (party_set_slot,"p_town_13", slot_town_arena_melee_2_team_size,   5),
##      (party_set_slot,"p_town_13", slot_town_arena_melee_3_num_teams,   4),
##      (party_set_slot,"p_town_13", slot_town_arena_melee_3_team_size,   7),
##      (call_script, "script_center_set_trade_good_production", "p_town_13", "itm_dried_meat", 50),
##      (call_script, "script_center_set_trade_good_production", "p_town_13", "itm_oil", -40),
##
##      (party_set_slot,"p_town_14", slot_town_arena_melee_1_num_teams,   2),
##      (party_set_slot,"p_town_14", slot_town_arena_melee_1_team_size,   4),
##      (party_set_slot,"p_town_14", slot_town_arena_melee_2_num_teams,   2),
##      (party_set_slot,"p_town_14", slot_town_arena_melee_2_team_size,   5),
##      (party_set_slot,"p_town_14", slot_town_arena_melee_3_num_teams,   2),
##      (party_set_slot,"p_town_14", slot_town_arena_melee_3_team_size,   6),
##      (call_script, "script_center_set_trade_good_production", "p_town_14", "itm_pottery", 50),
##      (call_script, "script_center_set_trade_good_production", "p_town_14", "itm_linen", -40),

# Towns (loop)
#      (try_for_range, ":town_no", towns_begin, towns_end),
#        (store_sub, ":offset", ":town_no", towns_begin),
#        (party_set_slot,":town_no", slot_party_type, spt_town),
##        (store_add, ":cur_object_no", "trp_town_1_seneschal", ":offset"),
##        (party_set_slot,":town_no", slot_town_seneschal, ":cur_object_no"),
#        (store_add, ":cur_object_no", "scn_town_1_center", ":offset"),
#        (party_set_slot,":town_no", slot_town_center, ":cur_object_no"),
#        (store_add, ":cur_object_no", "scn_town_1_castle", ":offset"),
#        (party_set_slot,":town_no", slot_town_castle, ":cur_object_no"),
#        (store_add, ":cur_object_no", "scn_town_1_prison", ":offset"),
#        (party_set_slot,":town_no", slot_town_prison, ":cur_object_no"),
#        (store_add, ":cur_object_no", "scn_town_1_tavern", ":offset"),
#        (party_set_slot,":town_no", slot_town_tavern, ":cur_object_no"),
#        (store_add, ":cur_object_no", "scn_town_1_store", ":offset"),
#        (party_set_slot,":town_no", slot_town_store, ":cur_object_no"),
#        (store_add, ":cur_object_no", "scn_town_1_arena", ":offset"),
#        (party_set_slot,":town_no", slot_town_arena, ":cur_object_no"),
#        (store_add, ":cur_object_no", "scn_town_1_alley", ":offset"),
#        (party_set_slot,":town_no", slot_town_alley, ":cur_object_no"),
#        (store_add, ":cur_object_no", "trp_town_1_tavernkeeper", ":offset"),
#        (party_set_slot,":town_no", slot_town_tavernkeeper, ":cur_object_no"),
#        (store_add, ":cur_object_no", "trp_town_1_weaponsmith", ":offset"),
#        (party_set_slot,":town_no", slot_town_weaponsmith, ":cur_object_no"),
#        (store_add, ":cur_object_no", "trp_town_1_armorer", ":offset"),
#        (party_set_slot,":town_no", slot_town_armorer, ":cur_object_no"),
#        (store_add, ":cur_object_no", "trp_town_1_merchant", ":offset"),
#        (party_set_slot,":town_no", slot_town_merchant, ":cur_object_no"),
#        (store_add, ":cur_object_no", "trp_town_1_horse_merchant", ":offset"),
#        (party_set_slot,":town_no", slot_town_horse_merchant, ":cur_object_no"),
#        (store_add, ":cur_object_no", "p_town_1_mercs", ":offset"),
#        (party_set_slot,":town_no", slot_town_mercs, ":cur_object_no"),
#        (store_add, ":cur_object_no", "scn_town_1_center", ":offset"),
#        (party_set_slot,":town_no", slot_town_center, ":cur_object_no"),
#        (party_set_slot,":town_no", slot_town_arena_template, "mt_arena_melee_fight"),
#        (party_set_slot,":town_no", slot_town_reinforcement_party_template, "pt_center_reinforcements"),
#      (try_end),

#      (party_set_slot,"p_town_1", slot_town_arena_template, "mt_arena_melee_fight_no_ranged"),
      
## Castles
#      (try_for_range, ":castle_no", castles_begin, castles_end),
#        (store_sub, ":offset", ":castle_no", castles_begin),
#        (val_mul, ":offset", 2),

#        (store_add, ":senechal_troop_no", "trp_castle_1_seneschal", ":offset"),
#        (party_set_slot,":castle_no", slot_town_seneschal, ":senechal_troop_no"),
#        (store_add, ":exterior_scene_no", "scn_castle_1_exterior", ":offset"),
#        (party_set_slot,":castle_no", slot_castle_exterior, ":exterior_scene_no"),
#        (store_add, ":interior_scene_no", "scn_castle_1_interior", ":offset"),
#        (party_set_slot,":castle_no", slot_town_castle, ":interior_scene_no"),
#        (party_set_slot,":castle_no", slot_town_reinforcement_party_template, "pt_center_reinforcements"),
#        (party_set_slot,":castle_no", slot_party_type, spt_castle),
#        (party_set_slot,":castle_no", slot_center_is_besieged_by, -1),
#      (try_end),

## Set which castles need to be attacked with siege towers.
#      (party_set_slot,"p_castle_1", slot_center_siege_with_belfry,   0),
#      (party_set_slot,"p_castle_2", slot_center_siege_with_belfry,   1),
#      (party_set_slot,"p_castle_3", slot_center_siege_with_belfry,   0),
#      (party_set_slot,"p_castle_4", slot_center_siege_with_belfry,   0),
#      (party_set_slot,"p_castle_5", slot_center_siege_with_belfry,   0),
#      (party_set_slot,"p_castle_6", slot_center_siege_with_belfry,   0),
#      (party_set_slot,"p_castle_7", slot_center_siege_with_belfry,   1),
#      (party_set_slot,"p_castle_8", slot_center_siege_with_belfry,   1),
#      (party_set_slot,"p_castle_9", slot_center_siege_with_belfry,   1),
#      (party_set_slot,"p_castle_10", slot_center_siege_with_belfry,   0),
#      (party_set_slot,"p_castle_11", slot_center_siege_with_belfry,   1),


# Towns

# Villages
       #TODO: add smoked fish to coastal villages.
      (call_script, "script_center_set_trade_good_production", "p_village_1", "itm_smoked_fish", 60),
      (try_for_range, ":village_no", villages_begin, villages_end),
        (store_random_in_range, ":rand", 0, 9),
        (val_mul, ":rand", ":rand"),
        (call_script, "script_center_set_trade_good_production", ":village_no", "itm_dried_meat", ":rand"),
        (store_random_in_range, ":rand", 0, 9),
        (val_mul, ":rand", ":rand"),
        (call_script, "script_center_set_trade_good_production", ":village_no", "itm_apples", ":rand"),
        (store_random_in_range, ":rand", 0, 9),
        (val_mul, ":rand", ":rand"),
        (call_script, "script_center_set_trade_good_production", ":village_no", "itm_honey", ":rand"),
        (store_random_in_range, ":rand", 0, 9),
        (val_mul, ":rand", ":rand"),
        (call_script, "script_center_set_trade_good_production", ":village_no", "itm_cabbages", ":rand"),
        (store_random_in_range, ":rand", 0, 9),
        (val_mul, ":rand", ":rand"),
        (call_script, "script_center_set_trade_good_production", ":village_no", "itm_butter", ":rand"),
        (store_random_in_range, ":rand", 0, 9),
        (val_mul, ":rand", ":rand"),
        (call_script, "script_center_set_trade_good_production", ":village_no", "itm_wine", ":rand"),
        (store_random_in_range, ":rand", 0, 9),
        (val_mul, ":rand", ":rand"),
        (call_script, "script_center_set_trade_good_production", ":village_no", "itm_flour", ":rand"),
        (store_random_in_range, ":rand", 0, 9),
        (val_mul, ":rand", ":rand"),
        (call_script, "script_center_set_trade_good_production", ":village_no", "itm_ale", ":rand"),
        (store_random_in_range, ":rand", 0, 9),
        (val_mul, ":rand", ":rand"),
        (call_script, "script_center_set_trade_good_production", ":village_no", "itm_apples", ":rand"),
        (store_random_in_range, ":rand", 0, 9),
        (val_mul, ":rand", ":rand"),
        (call_script, "script_center_set_trade_good_production", ":village_no", "itm_grain", ":rand"),
        (store_random_in_range, ":rand", 0, 9),
        (val_mul, ":rand", ":rand"),
        (call_script, "script_center_set_trade_good_production", ":village_no", "itm_oil", ":rand"),
      (try_end),
      
      (try_for_range, ":village_no", villages_begin, villages_end),
        (store_sub, ":offset", ":village_no", villages_begin),

        (store_add, ":exterior_scene_no", "scn_village_1", ":offset"),
        (party_set_slot,":village_no", slot_castle_exterior, ":exterior_scene_no"),
      
        (store_add, ":store_troop_no", "trp_village_1_store", ":offset"),
        (party_set_slot,":village_no", slot_town_merchant, ":store_troop_no"),
        
        (party_set_slot,":village_no", slot_party_type, spt_village),
        (party_set_slot,":village_no", slot_village_raided_by, -1),

        (call_script, "script_refresh_village_merchant_inventory", ":village_no"),
        (call_script, "script_refresh_village_merchant_inventory", ":village_no"),
      
        (call_script, "script_refresh_village_defenders", ":village_no"),
        (call_script, "script_refresh_village_defenders", ":village_no"),
        (call_script, "script_refresh_village_defenders", ":village_no"),
        (call_script, "script_refresh_village_defenders", ":village_no"),
      (try_end),

      #TODO: These villages have no scenes yet and are linked to existing village scenes
      (party_set_slot,"p_village_10", slot_castle_exterior, "scn_village_7"),

      (party_set_slot,"p_village_24", slot_castle_exterior, "scn_village_4"),
      (party_set_slot,"p_village_26", slot_castle_exterior, "scn_village_6"),
      (party_set_slot,"p_village_27", slot_castle_exterior, "scn_village_3"),
      (party_set_slot,"p_village_29", slot_castle_exterior, "scn_village_9"),
      (party_set_slot,"p_village_30", slot_castle_exterior, "scn_village_5"),
      (party_set_slot,"p_village_31", slot_castle_exterior, "scn_village_1"),
      (party_set_slot,"p_village_32", slot_castle_exterior, "scn_village_2"),
      (party_set_slot,"p_village_33", slot_castle_exterior, "scn_village_3"),
      (party_set_slot,"p_village_34", slot_castle_exterior, "scn_village_4"),
      (party_set_slot,"p_village_35", slot_castle_exterior, "scn_village_5"),
      (party_set_slot,"p_village_36", slot_castle_exterior, "scn_village_6"),
      (party_set_slot,"p_village_38", slot_castle_exterior, "scn_village_8"),
      (party_set_slot,"p_village_39", slot_castle_exterior, "scn_village_9"),


      (try_for_range, ":center_no", centers_begin, centers_end),
        (party_set_slot, ":center_no", slot_center_last_spotted_enemy, -1),
        (party_set_slot, ":center_no", slot_center_is_besieged_by, -1),
        (party_set_slot, ":center_no", slot_center_last_taken_by_troop, -1),
      (try_end),
      
# Troops:

# Assign banners and renown.
# We assume there are enough banners for all kingdom heroes.
      (try_for_range, ":kingdom_hero", kingdom_heroes_begin, kingdom_heroes_end),
        (store_sub, ":hero_offset", ":kingdom_hero", kingdom_heroes_begin),
#        (lt, ":hero_offset", num_banners),
        (store_add, ":banner_id", "spr_banner_a", ":hero_offset"),
        (troop_set_slot,":kingdom_hero",  slot_troop_banner_scene_prop, ":banner_id"),
        (store_troop_faction, ":kingdom_hero_faction", ":kingdom_hero"),
        (try_begin),
          (faction_slot_eq, ":kingdom_hero_faction", slot_faction_leader, ":kingdom_hero"),
          (store_random_in_range, ":random_renown", 200, 400),
        (else_try),
          (store_random_in_range, ":random_renown", 50, 200),
        (try_end),
        (troop_set_slot, ":kingdom_hero", slot_troop_renown, ":random_renown"),
      (try_end),

#Correcting banners according to the player banner
      (troop_get_slot, ":selected_banner_spr", "trp_player", slot_troop_banner_scene_prop),
      (assign, ":end_cond", kingdom_heroes_end),
      (try_for_range, ":cur_troop", kingdom_heroes_begin, ":end_cond"),
        (troop_slot_eq, ":cur_troop", slot_troop_banner_scene_prop, ":selected_banner_spr"),
        (troop_set_slot, ":cur_troop", slot_troop_banner_scene_prop, "spr_banner_cu"),
        (assign, ":end_cond", 0),
      (try_end),

	  (call_script,"script_set_lord_init"),
#re-edit
##      (call_script, "script_give_center_to_lord", "p_town_1",  "trp_kingdom_4_lord"),
##      (call_script, "script_give_center_to_lord", "p_town_2",  "trp_knight_4_1"),
##      (call_script, "script_give_center_to_lord", "p_town_3",  "trp_knight_5_1"),
##      (call_script, "script_give_center_to_lord", "p_town_4",  "trp_knight_1_1"),
##      (call_script, "script_give_center_to_lord", "p_town_5",  "trp_kingdom_5_lord"),
##      (call_script, "script_give_center_to_lord", "p_town_6",  "trp_kingdom_1_lord"),
##      (call_script, "script_give_center_to_lord", "p_town_7",  "trp_knight_1_2"),
##      
##      (call_script, "script_give_center_to_lord", "p_town_8",  "trp_kingdom_2_lord"),
##      (call_script, "script_give_center_to_lord", "p_town_9",  "trp_knight_2_1"),
##      (call_script, "script_give_center_to_lord", "p_town_10", "trp_kingdom_3_lord"),
##      (call_script, "script_give_center_to_lord", "p_town_11", "trp_knight_3_1"),
##      (call_script, "script_give_center_to_lord", "p_town_12", "trp_knight_4_2"),
##      (call_script, "script_give_center_to_lord", "p_town_13", "trp_knight_2_2"),
##      (call_script, "script_give_center_to_lord", "p_town_14", "trp_knight_3_2"),
##
##
##
##      (call_script, "script_give_center_to_faction_aux", "p_castle_1", "fac_kingdom_5"),
##      (call_script, "script_give_center_to_faction_aux", "p_castle_2", "fac_kingdom_wu"),
##      (call_script, "script_give_center_to_faction_aux", "p_castle_3", "fac_kingdom_shuhan"),
##      (call_script, "script_give_center_to_faction_aux", "p_castle_4", "fac_kingdom_caowei"),
##      (call_script, "script_give_center_to_faction_aux", "p_castle_5", "fac_kingdom_4"),
##      (call_script, "script_give_center_to_faction_aux", "p_castle_6", "fac_kingdom_shuhan"),
##      (call_script, "script_give_center_to_faction_aux", "p_castle_7", "fac_kingdom_wu"),
##      (call_script, "script_give_center_to_faction_aux", "p_castle_8", "fac_kingdom_shuhan"),
##      (call_script, "script_give_center_to_faction_aux", "p_castle_9", "fac_kingdom_5"),
##      (call_script, "script_give_center_to_faction_aux", "p_castle_10", "fac_kingdom_caowei"),
##      (call_script, "script_give_center_to_faction_aux", "p_castle_11", "fac_kingdom_4"),
      
##      (call_script, "script_give_center_to_lord", "p_castle_1",  "trp_knight_5_2"),
##      (call_script, "script_give_center_to_lord", "p_castle_2",  "trp_knight_3_3"),
##      (call_script, "script_give_center_to_lord", "p_castle_3",  "trp_knight_2_3"),
##      (call_script, "script_give_center_to_lord", "p_castle_4",  "trp_knight_1_3"),
##      (call_script, "script_give_center_to_lord", "p_castle_5",  "trp_knight_4_3"),
##      (call_script, "script_give_center_to_lord", "p_castle_6",  "trp_knight_2_4"),
##      (call_script, "script_give_center_to_lord", "p_castle_7",  "trp_knight_3_4"),
##      (call_script, "script_give_center_to_lord", "p_castle_8",  "trp_knight_2_4"),
##      (call_script, "script_give_center_to_lord", "p_castle_9",  "trp_knight_5_3"),
##      (call_script, "script_give_center_to_lord", "p_castle_10", "trp_knight_1_4"),
##      (call_script, "script_give_center_to_lord", "p_castle_11", "trp_knight_4_4"),


  # fill_village_bound_centers
    #pass 1: Give one village to each castle and town
      (try_for_range, ":cur_center", walled_centers_begin, walled_centers_end),
        (assign, ":min_dist", 999999),
        (assign, ":min_dist_village", -1),
        (try_for_range, ":cur_village", villages_begin, villages_end),
          (store_distance_to_party_from_party, ":cur_dist", ":cur_village", ":cur_center"),
          (lt, ":cur_dist", ":min_dist"),
          (assign, ":min_dist", ":cur_dist"),
          (assign, ":min_dist_village", ":cur_village"),
        (try_end),
        (party_set_slot, ":min_dist_village", slot_village_bound_center, ":cur_center"),
        (store_faction_of_party, ":town_faction", ":cur_center"),
        (call_script, "script_give_center_to_faction_aux", ":min_dist_village", ":town_faction"),
      (try_end),
      
    #pass 2: Give other villages to closest town.
      (try_for_range, ":cur_village", villages_begin, villages_end),
        (neg|party_slot_ge, ":cur_village", slot_village_bound_center, 1), #skip villages which are already bound.
        (assign, ":min_dist", 999999),
        (assign, ":min_dist_town", -1),
        (try_for_range, ":cur_town", towns_begin, towns_end),
          (store_distance_to_party_from_party, ":cur_dist", ":cur_village", ":cur_town"),
          (lt, ":cur_dist", ":min_dist"),
          (assign, ":min_dist", ":cur_dist"),
          (assign, ":min_dist_town", ":cur_town"),
        (try_end),
        (party_set_slot, ":cur_village", slot_village_bound_center, ":min_dist_town"),
        (store_faction_of_party, ":town_faction", ":min_dist_town"),
        (call_script, "script_give_center_to_faction_aux", ":cur_village", ":town_faction"),
      (try_end),

      (try_for_range, ":center_no", centers_begin, centers_end),
        (store_faction_of_party, ":original_faction", ":center_no"),
        (faction_get_slot, ":culture", ":original_faction", slot_faction_culture),
        (party_set_slot, ":center_no", slot_center_culture,  ":culture"),
      (try_end),
      
      (call_script, "script_update_village_market_towns"),
      
#Assign only family structures of lords who doesn't have a father. Other troops will get the family tree automatically
#      (troop_set_slot,"trp_kingdom_1_lord",  slot_troop_spouse, "trp_kingdom_1_lord_wife"),
#      (troop_set_slot,"trp_kingdom_2_lord",  slot_troop_spouse, "trp_kingdom_2_lord_wife"),
#      (troop_set_slot,"trp_kingdom_3_lord",  slot_troop_spouse, "trp_kingdom_3_lord_wife"),
#      (troop_set_slot,"trp_kingdom_4_lord",  slot_troop_spouse, "trp_kingdom_4_lord_wife"),
#      (troop_set_slot,"trp_kingdom_5_lord",  slot_troop_spouse, "trp_kingdom_5_lord_wife"),
#
#      (troop_set_slot,"trp_kingdom_1_lord",  slot_troop_daughter, "trp_kingdom_1_lord_daughter"),
#      (troop_set_slot,"trp_kingdom_2_lord",  slot_troop_daughter, "trp_kingdom_2_lord_daughter"),
#      (troop_set_slot,"trp_kingdom_3_lord",  slot_troop_daughter, "trp_kingdom_3_lord_daughter"),
#      (troop_set_slot,"trp_kingdom_4_lord",  slot_troop_daughter, "trp_kingdom_4_lord_daughter"),
#      (troop_set_slot,"trp_kingdom_5_lord",  slot_troop_daughter, "trp_kingdom_5_lord_daughter"),

##      (troop_set_slot,"trp_kingdom_2_lord_a", slot_troop_spouse, "trp_kingdom_2_lady_a"),
##      (troop_set_slot,"trp_kingdom_2_lord_a", slot_troop_son, "trp_kingdom_2_lord_b"),
##      (troop_set_slot,"trp_kingdom_2_lord_a", slot_troop_sibling, "trp_kingdom_2_lady_c"),
##      (troop_set_slot,"trp_kingdom_2_lord_a", slot_troop_daughter, "trp_kingdom_2_lady_e"),
##      
##      (troop_set_slot,"trp_kingdom_2_lord_b", slot_troop_daughter, "trp_kingdom_2_lady_b"),
##      (troop_set_slot,"trp_kingdom_2_lord_c", slot_troop_spouse, "trp_kingdom_2_lady_c"),
##      (troop_set_slot,"trp_kingdom_2_lord_d", slot_troop_daughter, "trp_kingdom_2_lady_d"),
##      (troop_set_slot,"trp_kingdom_2_lord_e", slot_troop_spouse, "trp_kingdom_2_lady_e"),
##      (troop_set_slot,"trp_kingdom_2_lord_f", slot_troop_daughter, "trp_kingdom_2_lady_f"),
##      (troop_set_slot,"trp_kingdom_2_lord_g", slot_troop_spouse, "trp_kingdom_2_lady_g"),
##      (troop_set_slot,"trp_kingdom_2_lord_h", slot_troop_daughter, "trp_kingdom_2_lady_h"),
##      (troop_set_slot,"trp_kingdom_2_lord_i", slot_troop_spouse, "trp_kingdom_2_lady_i"),
##      (troop_set_slot,"trp_kingdom_2_lord_j", slot_troop_daughter, "trp_kingdom_2_lady_j"),

##      (try_for_range, ":troop_id", merchants_begin, merchants_end),
##        (troop_set_slot, ":troop_id", slot_troop_occupation, slto_merchant),
##      (try_end),

      (try_for_range, ":troop_id", kingdom_heroes_begin, kingdom_heroes_end),
		(troop_set_slot, ":troop_id", slot_troop_leaded_party, 0),
        (try_begin),
          (store_troop_faction, ":faction_id", ":troop_id"),
          (is_between, ":faction_id", kingdoms_begin, kingdoms_end),
          (troop_set_slot, ":troop_id", slot_troop_occupation, slto_kingdom_hero),
        (try_end),
        (assign, ":initial_wealth", 6000),
        (try_begin),
          (store_troop_faction, ":faction", ":troop_id"),
          (faction_slot_eq, ":faction", slot_faction_leader, ":troop_id"),
          (assign, ":initial_wealth", 20000),
        (try_end),
        (troop_set_slot, ":troop_id", slot_troop_wealth, ":initial_wealth"),
      (try_end),

      (try_for_range, ":center_no", walled_centers_begin, walled_centers_end),
        (assign, ":garrison_strength", 8), #add town garrisons
        (try_for_range, ":unused", 0, ":garrison_strength"),
          (call_script, "script_cf_reinforce_party", ":center_no"),
        (try_end),

        #Fill town food stores upto half the limit
        (call_script, "script_center_get_food_store_limit", ":center_no"),
        (assign, ":food_store_limit", reg0),
        (val_div, ":food_store_limit", 2),
        (party_set_slot, ":center_no", slot_party_food_store, ":food_store_limit"),

        #create lord parties
        (party_get_slot, ":center_lord", ":center_no", slot_town_lord),##key
		(assign,reg60,":center_no"),
		(assign,reg61,":center_lord"),
		(display_message,"@{reg60} lord {reg61}"),
        (ge, ":center_lord", 1),
        (troop_slot_eq, ":center_lord", slot_troop_leaded_party, 0),
        (call_script, "script_create_kingdom_hero_party", ":center_lord", ":center_no"),
        (assign, ":lords_party", "$pout_party"),
        (party_attach_to_party, ":lords_party", ":center_no"),
        (store_random_in_range, ":xp", 4000, 10000),
        (call_script, "script_upgrade_hero_party", ":lords_party", ":xp"),
        (party_set_slot, ":center_no", slot_town_player_odds, 1000),
      (try_end),

      (call_script, "script_complete_family_relations"),
      (call_script, "script_complete_family_relations"),

#      (try_for_range, ":troop_id", kingdom_ladies_begin, kingdom_ladies_end),
#        (troop_set_slot, ":troop_id", slot_troop_occupation, slto_kingdom_lady),
#        (troop_get_slot, ":cur_family", ":troop_id", slot_troop_father),
#        (try_begin),
#          (eq, ":cur_family", 0),
#          (troop_get_slot, ":cur_family", ":troop_id", slot_troop_spouse),
#        (try_end),
#        (try_begin),
#          (gt, ":cur_family", 0),
#          (call_script, "script_get_troop_attached_party", ":cur_family"),
#          (assign, ":cur_center", reg0),
#          (gt, ":cur_center", 0),
#          (troop_set_slot, ":troop_id", slot_troop_cur_center, ":cur_center"),
#        (else_try),
#          (store_troop_faction, ":faction_no", ":troop_id"),
#          (call_script, "script_cf_select_random_center_with_faction", ":faction_no"),
#          (assign, ":cur_center", reg0),
#          (troop_set_slot, ":troop_id", slot_troop_cur_center, ":cur_center"),
#        (try_end),
#      (try_end),

#      (try_for_range, ":troop_id", heroes_begin, heroes_end),
#        (troop_slot_eq, ":troop_id", slot_troop_occupation, slto_kingdom_lady),
#        (troop_get_slot, ":cur_father", ":troop_id", slot_troop_father),
#        (gt, ":cur_father", 0),# Lovers for daughters only
#        (store_random_in_range, ":random_no", 0, 100),
#        (le, ":random_no", 80),
#        (call_script, "script_cf_get_random_kingdom_hero_as_lover", ":troop_id"),#Can fail
#        (assign, ":cur_lover", reg0),
#        (troop_set_slot, ":troop_id", slot_troop_lover, ":cur_lover"),
#        (troop_set_slot, ":cur_lover", slot_troop_lover, ":troop_id"),
#      (try_end),

      (try_for_range, ":troop_id", heroes_begin, heroes_end),
        (troop_get_slot, ":in_relation_1", ":troop_id", slot_troop_spouse),
        (troop_get_slot, ":in_relation_2", ":troop_id", slot_troop_sibling),
        (troop_get_slot, ":in_relation_3", ":troop_id", slot_troop_daughter),
        (troop_get_slot, ":in_relation_4", ":troop_id", slot_troop_son),
        (troop_get_slot, ":in_relation_5", ":troop_id", slot_troop_father),
        (troop_get_slot, ":in_relation_6", ":troop_id", slot_troop_mother),
        (troop_get_slot, ":in_relation_7", ":troop_id", slot_troop_lover),
#        (troop_get_slot, ":troop_rank", ":troop_id", slot_troop_kingdom_rank),
        (store_troop_faction, ":troop_faction", ":troop_id"),

        (assign, ":troop_enemy_count", 0),
        (try_for_range, ":i_enemy_slot", slot_troop_enemies_begin, slot_troop_enemies_end),
          (troop_slot_ge, ":troop_id", ":i_enemy_slot", 1),
          (val_add, ":troop_enemy_count", 1),
        (try_end),

        (try_for_range, ":i_enemy_slot", slot_troop_enemies_begin, slot_troop_enemies_end),
          (troop_set_slot, ":troop_id", ":i_enemy_slot", -1),
        (try_end),
      
        (store_random_in_range, ":random_enemy_count", 0, 4),
        (val_add, ":random_enemy_count", ":troop_enemy_count"),
        (val_min, ":random_enemy_count", 5),
        (try_for_range, ":unused", ":troop_enemy_count", ":random_enemy_count"),
          (assign, ":possible_enemy_count", 0),
          (try_for_range, ":enemy_troop_id", heroes_begin, heroes_end),
            (neq, ":enemy_troop_id", ":troop_id"),
            (neq, ":enemy_troop_id", ":in_relation_1"),
            (neq, ":enemy_troop_id", ":in_relation_2"),
            (neq, ":enemy_troop_id", ":in_relation_3"),
            (neq, ":enemy_troop_id", ":in_relation_4"),
            (neq, ":enemy_troop_id", ":in_relation_5"),
            (neq, ":enemy_troop_id", ":in_relation_6"),
            (neq, ":enemy_troop_id", ":in_relation_7"),
            (store_troop_faction, ":enemy_troop_faction", ":enemy_troop_id"),
            (eq, ":enemy_troop_faction", ":troop_faction"),
#            (troop_get_slot, ":enemy_troop_rank", ":enemy_troop_id", slot_troop_kingdom_rank),
#            (lt, ":enemy_troop_rank", 4),
#            (lt, ":troop_rank", 4),
            (assign, ":marked_as_enemy", 0),
            (try_for_range, ":i_enemy_slot_mark", slot_troop_enemies_begin, slot_troop_enemies_end),
              (troop_slot_eq, ":troop_id", ":i_enemy_slot_mark", ":enemy_troop_id"),
              (assign, ":marked_as_enemy", 1),
            (try_end),
            (eq, ":marked_as_enemy", 0),
            (val_add, ":possible_enemy_count", 1),
          (try_end),
          (store_random_in_range, ":random_enemy", 0, ":possible_enemy_count"),
          (assign, ":possible_enemy_count", 0),
          (assign, ":result", -1),
          (try_for_range, ":enemy_troop_id", heroes_begin, heroes_end),
            (eq, ":result", -1),
            (neq, ":enemy_troop_id", ":troop_id"),
            (neq, ":enemy_troop_id", ":in_relation_1"),
            (neq, ":enemy_troop_id", ":in_relation_2"),
            (neq, ":enemy_troop_id", ":in_relation_3"),
            (neq, ":enemy_troop_id", ":in_relation_4"),
            (neq, ":enemy_troop_id", ":in_relation_5"),
            (neq, ":enemy_troop_id", ":in_relation_6"),
            (neq, ":enemy_troop_id", ":in_relation_7"),
            (store_troop_faction, ":enemy_troop_faction", ":enemy_troop_id"),
            (eq, ":enemy_troop_faction", ":troop_faction"),
#            (troop_get_slot, ":enemy_troop_rank", ":enemy_troop_id", slot_troop_kingdom_rank),
#            (lt, ":enemy_troop_rank", 4),
#            (lt, ":troop_rank", 4),
            (assign, ":marked_as_enemy", 0),
            (try_for_range, ":i_enemy_slot_mark", slot_troop_enemies_begin, slot_troop_enemies_end),
              (troop_slot_eq, ":troop_id", ":i_enemy_slot_mark", ":enemy_troop_id"),
              (assign, ":marked_as_enemy", 1),
            (try_end),
            (eq, ":marked_as_enemy", 0),
            (val_add, ":possible_enemy_count", 1),
            (gt, ":possible_enemy_count", ":random_enemy"),
            (assign, ":result", ":enemy_troop_id"),
          (try_end),

          (gt, ":result", 0),
          (assign, ":enemy_troop_enemy_count", 0),
          (try_for_range, ":i_enemy_slot", slot_troop_enemies_begin, slot_troop_enemies_end),
            (troop_slot_ge, ":result", ":i_enemy_slot", 1),
            (val_add, ":enemy_troop_enemy_count", 1),
          (try_end),

          (lt, ":enemy_troop_enemy_count", 5),

          (assign, ":troop_enemy_count", 0),
          (try_for_range, ":i_enemy_slot", slot_troop_enemies_begin, slot_troop_enemies_end),
            (troop_slot_ge, ":troop_id", ":i_enemy_slot", 1),
            (val_add, ":troop_enemy_count", 1),
          (try_end),

          (store_add, ":cur_slot", slot_troop_enemies_begin, ":troop_enemy_count"),
          (troop_set_slot, ":troop_id", ":cur_slot", ":result"),
          (store_add, ":cur_slot", slot_troop_enemies_begin, ":enemy_troop_enemy_count"),
          (troop_set_slot, ":result", ":cur_slot", ":troop_id"),
        (try_end),
      (try_end),

#      (call_script, "script_average_trade_good_productions"),

      (try_for_range, ":unused", 0, 7),
        (call_script, "script_spawn_bandits"),
      (try_end),
      (call_script, "script_update_trade_good_prices"),
      (call_script, "script_update_trade_good_prices"),
      (call_script, "script_update_trade_good_prices"),
      (call_script, "script_update_trade_good_prices"),
      (call_script, "script_update_trade_good_prices"),
      
      (call_script, "script_assign_lords_to_empty_centers"),

      (call_script, "script_get_player_party_morale_values"),
      (party_set_morale, "p_main_party", reg0),

      (call_script, "script_update_mercenary_units_of_towns"),
      (call_script, "script_update_companion_candidates_in_taverns"),
      (call_script, "script_update_ransom_brokers"),
      (call_script, "script_update_tavern_travelers"),
      (call_script, "script_update_tavern_minstels"),
      (try_for_range, ":village_no", villages_begin, villages_end),
        (call_script, "script_update_volunteer_troops_in_village", ":village_no"),
      (try_end),
      (try_for_range, ":cur_kingdom", kingdoms_begin, kingdoms_end),
        (call_script, "script_update_faction_notes", ":cur_kingdom"),
      (try_end),
      (try_for_range, ":cur_troop", kingdom_heroes_begin, kingdom_heroes_end),
        (call_script, "script_update_troop_notes", ":cur_troop"),
      (try_end),
      (call_script, "script_update_troop_notes", "trp_player"),
    ]),    


  # script_game_event_party_encounter:
  # This script is called from the game engine whenever player party encounters another party or a battle on the world map
  # INPUT:
  # param1: encountered_party
  # param2: second encountered_party (if this was a battle
  ("game_event_party_encounter",
   [
       (store_script_param_1, "$g_encountered_party"),
       (store_script_param_2, "$g_encountered_party_2"),# encountered_party2 is set when we come across a battle or siege, otherwise it's a negative value
#       (store_encountered_party, "$g_encountered_party"),
#       (store_encountered_party2,"$g_encountered_party_2"), # encountered_party2 is set when we come across a battle or siege, otherwise it's a minus value
       (store_faction_of_party, "$g_encountered_party_faction","$g_encountered_party"),
       (store_relation, "$g_encountered_party_relation", "$g_encountered_party_faction", "fac_player_faction"),
       (party_get_slot, "$g_encountered_party_type", "$g_encountered_party", slot_party_type),
       (party_get_template_id,"$g_encountered_party_template","$g_encountered_party"),
       (try_begin),
         (gt, "$g_encountered_party_2", 0),
#         (store_faction_of_party, "$g_encountered_party_2_faction","$g_encountered_party_2"),
#         (store_relation, "$g_encountered_party_2_relation", "$g_encountered_party_2_faction", "fac_player_faction"),
#         (party_get_template_id,"$g_encountered_party_2_template","$g_encountered_party_2"),
       (else_try),
#         (assign, "$g_encountered_party_2_faction",-1),
#         (assign, "$g_encountered_party_2_relation", 0),
#         (assign,"$g_encountered_party_2_template", -1),
       (try_end),
       (assign, "$g_last_rest_center", -1),
       (assign, "$talk_context", 0),
       (assign,"$g_player_surrenders",0),
       (assign,"$g_enemy_surrenders",0),
       (assign, "$g_leave_encounter",0),
       (assign, "$g_engaged_enemy", 0),
       (assign,"$waiting_for_arena_fight_result", 0),
       (assign,"$arena_bet_amount",0),
#       (assign,"$g_player_raiding_village",0),
       (rest_for_hours, 0), #stop waiting
#       (assign, "$g_permitted_to_center",0),
       (assign, "$new_encounter", 1), #check this in the menu.
       (try_begin),
         (lt, "$g_encountered_party_2",0), #Normal encounter. Not battle or siege.
         (try_begin),
           (party_slot_eq, "$g_encountered_party", slot_party_type, spt_town),
           (jump_to_menu, "mnu_castle_outside"),
         (else_try),
           (party_slot_eq, "$g_encountered_party", slot_party_type, spt_castle),
           (jump_to_menu, "mnu_castle_outside"),
         (else_try),
           (party_slot_eq, "$g_encountered_party", slot_party_type, spt_ship),
           (jump_to_menu, "mnu_ship_reembark"),
         (else_try),
           (party_slot_eq, "$g_encountered_party", slot_party_type, spt_village),
           (jump_to_menu, "mnu_village"),
         (else_try),
           (eq, "$g_encountered_party", "p_zendar"),
           (jump_to_menu, "mnu_zendar"),
         (else_try),
           (eq, "$g_encountered_party", "p_salt_mine"),
           (jump_to_menu, "mnu_salt_mine"),
         (else_try),
           (eq, "$g_encountered_party", "p_four_ways_inn"),
           (jump_to_menu, "mnu_four_ways_inn"),
#         (else_try),
#           (eq, "$g_encountered_party", "p_test_scene"),
#           (jump_to_menu, "mnu_test_scene"),
         (else_try),
           (eq, "$g_encountered_party", "p_dhorak_keep"),
           (jump_to_menu, "mnu_dhorak_keep"),
         (else_try),
           (eq, "$g_encountered_party", "p_training_ground"),
           (jump_to_menu, "mnu_training_ground"),
         (else_try),
           (eq, "$g_encountered_party", "p_camp_bandits"),
           (jump_to_menu, "mnu_camp"),
         (else_try),
           (jump_to_menu, "mnu_simple_encounter"),
         (try_end),
       (else_try), #Battle or siege
         (try_begin),
           (this_or_next|party_slot_eq, "$g_encountered_party", slot_party_type, spt_town),
           (party_slot_eq, "$g_encountered_party", slot_party_type, spt_castle),
           (try_begin),
             (eq, "$auto_enter_town", "$g_encountered_party"),
             (jump_to_menu, "mnu_town"),
           (else_try),
             (eq, "$auto_besiege_town", "$g_encountered_party"),
             (jump_to_menu, "mnu_besiegers_camp_with_allies"),
           (else_try),
             (jump_to_menu, "mnu_join_siege_outside"),
           (try_end),
         (else_try),
           (jump_to_menu, "mnu_pre_join"),
         (try_end),
       (try_end),
       (assign,"$auto_enter_town",0),
       (assign,"$auto_besiege_town",0),
      ]),

  #script_game_event_simulate_battle:
  # This script is called whenever the game simulates the battle between two parties on the map.
  # INPUT:
  # param1: Defender Party
  # param2: Attacker Party
  ("game_event_simulate_battle",
    [
       (store_script_param_1, ":root_defender_party"),
       (store_script_param_2, ":root_attacker_party"),

       (try_begin),
         (this_or_next|party_slot_eq, ":root_defender_party", slot_party_retreat_flag, 1),
         (party_slot_eq, ":root_attacker_party", slot_party_retreat_flag, 1),
         (set_trigger_result, 1), #End battle!
       (try_end),
       (party_set_slot, ":root_attacker_party", slot_party_retreat_flag, 0),

       (assign, ":cancel_attack", 0),

       (try_begin),
         (neg|is_currently_night), #Don't fight at night???
         (party_collect_attachments_to_party, ":root_defender_party", "p_collective_ally"),
         (party_collect_attachments_to_party, ":root_attacker_party", "p_collective_enemy"),

         (call_script, "script_party_count_fit_regulars", "p_collective_ally"),
         (assign, ":defender_strength", reg0),
         (call_script, "script_party_count_fit_regulars", "p_collective_enemy"),
         (assign, ":attacker_strength", reg0),

         (val_min, ":defender_strength", 30),
         (val_min, ":attacker_strength", 30),


         (try_begin),
           #For sieges increase attacker casualties and reduce defender casualties.
           (this_or_next|party_slot_eq, ":root_defender_party", slot_party_type, spt_castle),
           (party_slot_eq, ":root_defender_party", slot_party_type, spt_town),
           (val_mul, ":defender_strength", 2),
           (val_div, ":attacker_strength", 2),
         (try_end),

         (inflict_casualties_to_party_group, ":root_attacker_party", ":defender_strength", "p_temp_casualties"),
         (party_collect_attachments_to_party, ":root_attacker_party", "p_collective_enemy"),
#         (call_script, "script_party_count_fit_regulars", "p_collective_enemy"),
         (call_script, "script_party_calculate_regular_strength", "p_collective_enemy"),
         (assign, ":new_attacker_strength", reg0),

         (try_begin),
           (gt, ":new_attacker_strength", 0),
           (inflict_casualties_to_party_group, ":root_defender_party", ":attacker_strength", "p_temp_casualties"),
         (try_end),
         (party_collect_attachments_to_party, ":root_defender_party", "p_collective_ally"),
#         (call_script, "script_party_count_fit_regulars", "p_collective_ally"),
         (call_script, "script_party_calculate_regular_strength", "p_collective_ally"),
         (assign, ":new_defender_strength", reg0),

         (try_begin),
           (party_slot_eq, ":root_defender_party", slot_party_type, spt_town),
           (party_slot_eq, ":root_attacker_party", slot_party_type, spt_castle),
           (store_mul, ":attacker_advantage", ":new_attacker_strength", 1),
           (store_mul, ":defender_advantage", ":new_defender_strength", 4),
         (else_try),
           (store_mul, ":attacker_advantage", ":new_attacker_strength", 2),
           (store_mul, ":defender_advantage", ":new_defender_strength", 3),
         (try_end),

         (try_begin),
           (lt, ":attacker_advantage",":defender_advantage"),
           (assign, ":cancel_attack", 1),
         (try_end),
       

         (try_begin),
           (this_or_next|eq, ":new_attacker_strength", 0),
           (eq, ":new_defender_strength", 0),
           # Battle concluded! determine winner

           (try_begin),
             (eq, ":new_attacker_strength", 0),
             (assign, ":root_winner_party",   ":root_defender_party"),
             (assign, ":root_defeated_party", ":root_attacker_party"),
             (assign, ":collective_casualties",    "p_collective_enemy"),
           (else_try),
             (assign, ":root_winner_party", ":root_attacker_party"),
             (assign, ":root_defeated_party",  ":root_defender_party"),
             (assign, ":collective_casualties",  "p_collective_ally"),
           (try_end),

           (call_script, "script_get_nonempty_party_in_group", ":root_winner_party"),
           (assign, ":nonempty_winner_party", reg0),
           (ge, ":nonempty_winner_party", 0),

           (store_faction_of_party, ":faction_receiving_prisoners", ":nonempty_winner_party"),
           (store_faction_of_party, ":defeated_faction", ":root_defeated_party"),

           (party_get_num_companion_stacks, ":num_stacks", ":collective_casualties"),
           (try_for_range, ":troop_iterator", 0, ":num_stacks"),
             (party_stack_get_troop_id, ":cur_troop_id", ":collective_casualties", ":troop_iterator"),
             (troop_is_hero, ":cur_troop_id"),
             (troop_set_slot, ":cur_troop_id", slot_troop_is_prisoner, 0),
             (troop_set_slot, ":cur_troop_id", slot_troop_leaded_party, -1),
             (store_random_in_range, ":rand", 0, 100),
             (try_begin),
               (ge, ":rand", hero_escape_after_defeat_chance),
               (party_add_prisoners, ":nonempty_winner_party", ":cur_troop_id", 1),
               (gt, reg0, 0),
               (troop_set_slot, ":cur_troop_id", slot_troop_is_prisoner, 1),
               (display_log_message,"str_hero_taken_prisoner"),
             (else_try),
               (str_store_troop_name, s1, ":cur_troop_id"),
               (str_store_faction_name, s2, ":faction_receiving_prisoners"),
               (str_store_faction_name, s3, ":defeated_faction"),
               (display_log_message,"@{s1} of {s3} was defeated in battle but managed to escape."),
             (try_end),
           (try_end),
           (party_get_num_prisoner_stacks, ":num_stacks", ":collective_casualties"),
           (try_for_range, ":troop_iterator", 0, ":num_stacks"),
             (party_prisoner_stack_get_troop_id, ":cur_troop_id", ":collective_casualties", ":troop_iterator"),
             (troop_is_hero, ":cur_troop_id"),
             (troop_set_slot, ":cur_troop_id", slot_troop_is_prisoner, 0),
             (str_store_troop_name, s1, ":cur_troop_id"),
             (str_store_faction_name, s2, ":faction_receiving_prisoners"),
             (str_store_faction_name, s3, ":defeated_faction"),
             (display_log_message,"str_hero_freed"),
           (try_end),

           (party_clear, "p_temp_party"),
           (assign, "$g_move_heroes", 0), #heroes are already processed above. Skip them here.
           (call_script, "script_party_add_party_prisoners", "p_temp_party", ":collective_casualties"),
           (call_script, "script_party_prisoners_add_party_companions", "p_temp_party", ":collective_casualties"),
           (distribute_party_among_party_group, "p_temp_party", ":root_winner_party"),
           (call_script, "script_clear_party_group", ":root_defeated_party"),
           (set_trigger_result, 1), #End battle!


         #Center captured
           (try_begin),
             (party_get_slot, ":cur_party_type", ":root_defeated_party", slot_party_type),
             (this_or_next|eq, ":cur_party_type", spt_town),
             (eq, ":cur_party_type", spt_castle),

             (store_faction_of_party, ":winner_faction", ":root_winner_party"),
             (store_faction_of_party, ":defeated_faction", ":root_defeated_party"),

             (str_store_party_name, s1, ":root_defeated_party"),
             (str_store_faction_name, s2, ":winner_faction"),
             (str_store_faction_name, s3, ":defeated_faction"),
             (display_log_message, "str_center_captured"),

             (try_begin),
               (party_get_num_companion_stacks, ":num_stacks", ":root_winner_party"),
               (gt, ":num_stacks", 0),
               (party_stack_get_troop_id, ":leader_troop_no", ":root_winner_party", 0),
               (is_between, ":leader_troop_no", kingdom_heroes_begin, kingdom_heroes_end),
               (party_set_slot, ":root_defeated_party", slot_center_last_taken_by_troop, ":leader_troop_no"),
             (else_try),
               (party_set_slot, ":root_defeated_party", slot_center_last_taken_by_troop, -1),
             (try_end),

             (call_script, "script_give_center_to_faction", ":root_defeated_party", ":winner_faction"),
             (party_set_slot, ":root_winner_party", slot_party_ai_state, spai_undefined),
             (party_set_ai_behavior, ":root_winner_party", ai_bhvr_travel_to_party),
             (party_set_flags, ":root_winner_party", pf_default_behavior, 0),
           (try_end),
         (try_end),

        #ADD XP
         (try_begin),
           (party_slot_eq, ":root_attacker_party", slot_party_type, spt_kingdom_hero_party),
           (store_random_in_range, ":random_num",0, 100),
           (lt, ":random_num", 25),
           (gt, ":new_attacker_strength", 0),
           (call_script, "script_upgrade_hero_party", ":root_attacker_party", 1000),
         (try_end),
         (try_begin),
           (party_slot_eq, ":root_defender_party", slot_party_type, spt_kingdom_hero_party),
           (store_random_in_range, ":random_num",0, 100),
           (lt, ":random_num", 25),
           (gt, ":new_defender_strength", 0),
           (call_script, "script_upgrade_hero_party", ":root_defender_party", 1000),
         (try_end),

         (store_random_in_range, ":random_num",0, 100),
         (try_begin),
           (this_or_next|lt, ":random_num", 20),
           (eq, ":cancel_attack", 1),
           (set_trigger_result, 1), #End battle!
         (try_end),
       (try_end),
  ]),
  
  #script_game_get_item_buy_price_factor:
  # This script is called from the game engine for calculating the buying price of any item.
  # INPUT:
  # param1: item_kind_id
  # OUTPUT:
  # trigger_result and reg0 = price_factor
  ("game_get_item_buy_price_factor",
    [
      (store_script_param_1, ":item_kind_id"),
      (assign, ":price_factor", 100),

      (call_script, "script_get_trade_penalty", ":item_kind_id"),
      (assign, ":trade_penalty", reg0),

      (try_begin),
        (is_between, ":item_kind_id", trade_goods_begin, trade_goods_end),
        (store_sub, ":item_slot_no", ":item_kind_id", trade_goods_begin),
        (val_add, ":item_slot_no", slot_town_trade_good_prices_begin),
        (party_get_slot, ":price_factor", "$g_encountered_party", ":item_slot_no"),
        (val_mul, ":price_factor", 100), #normalize price factor to range 0..100
        (val_div, ":price_factor", average_price_factor),
      (try_end),
      
      (store_add, ":penalty_factor", 100, ":trade_penalty"),
      
      (val_mul, ":price_factor", ":penalty_factor"),
      (val_div, ":price_factor", 100),

      (assign, reg0, ":price_factor"),
      (set_trigger_result, reg0),
  ]),
  
  #script_game_get_item_sell_price_factor:
  # This script is called from the game engine for calculating the selling price of any item.
  # INPUT:
  # param1: item_kind_id
  # OUTPUT:
  # trigger_result and reg0 = price_factor
  ("game_get_item_sell_price_factor",
    [
      (store_script_param_1, ":item_kind_id"),
      (assign, ":price_factor", 100),

      (call_script, "script_get_trade_penalty", ":item_kind_id"),
      (assign, ":trade_penalty", reg0),

      (try_begin),
        (is_between, ":item_kind_id", trade_goods_begin, trade_goods_end),
        (store_sub, ":item_slot_no", ":item_kind_id", trade_goods_begin),
        (val_add, ":item_slot_no", slot_town_trade_good_prices_begin),
        (party_get_slot, ":price_factor", "$g_encountered_party", ":item_slot_no"),
        (val_mul, ":price_factor", 100),#normalize price factor to range 0..100
        (val_div, ":price_factor", average_price_factor),
      (else_try),
        #increase trade penalty while selling
        (val_mul, ":trade_penalty", 3),
        (val_div, ":trade_penalty", 2),
      (try_end),
      
      
      (store_add, ":penalty_divisor", 100, ":trade_penalty"),
      
      (val_mul, ":price_factor", 100),
      (val_div, ":price_factor", ":penalty_divisor"),
      
      (assign, reg0, ":price_factor"),
      (set_trigger_result, reg0),
  ]),
  
  # script_get_trade_penalty
  # 
  # Input:
  # param1: troop_id,
  # Output: reg0
  
  ("get_trade_penalty",
    [
      (store_script_param_1, ":item_kind_id"),
      (assign, ":penalty",0),
      
      (party_get_skill_level, ":trade_skill", "p_main_party", skl_trade),
      (try_begin),
        (is_between, ":item_kind_id", trade_goods_begin, trade_goods_end),
        (assign, ":penalty",17),
        (store_mul, ":skill_bonus", ":trade_skill", 1),
        (val_sub, ":penalty", ":skill_bonus"),
      (else_try),
        (assign, ":penalty",100),
        (store_mul, ":skill_bonus", ":trade_skill", 5),
        (val_sub, ":penalty", ":skill_bonus"),
      (try_end),

       # Apply penalty if player is hostile to merchants faction
      (assign, ":merchants_relation_multiplier", 1000),
      (store_relation, ":merchants_reln", "fac_merchants", "fac_player_faction"),
      (try_begin),
        (lt, ":merchants_reln", 0),
        (store_sub, ":merchants_reln_dif", 10, ":merchants_reln"),
        (store_mul, ":merchants_relation_penalty", ":merchants_reln_dif", 20),
        (val_add, ":merchants_relation_multiplier", ":merchants_relation_penalty"),
      (try_end),

       # Apply penalty if player is on bad terms with the merchant
      (troop_get_slot, ":troop_reln", "$g_talk_troop", slot_troop_player_relation),
      (try_begin),
        (lt, ":troop_reln", 0),
        (store_sub, ":troop_reln_dif", 0, ":troop_reln"),
        (store_mul, ":troop_relation_penalty", ":troop_reln_dif", 20),
        (val_add, ":merchants_relation_multiplier", ":troop_relation_penalty"),
      (try_end),
      
      (val_mul, ":penalty",  ":merchants_relation_multiplier"),
      (val_div, ":penalty", 1000),
      (assign, reg0, ":penalty"),
  ]),
  
  #script_game_event_buy_item:
  # This script is called from the game engine when player buys an item.
  # INPUT:
  # param1: item_kind_id
  ("game_event_buy_item",
    [
      (store_script_param_1, ":item_kind_id"),
      (store_script_param_2, ":reclaim_mode"),
      (try_begin),
        (is_between, ":item_kind_id", trade_goods_begin, trade_goods_end),
        (store_sub, ":item_slot_no", ":item_kind_id", trade_goods_begin),
        (val_add, ":item_slot_no", slot_town_trade_good_prices_begin),
        (party_get_slot, ":multiplier", "$g_encountered_party", ":item_slot_no"),
        (try_begin),
          (eq, ":reclaim_mode", 0),
          (val_add, ":multiplier", 10),
        (else_try),
          (val_add, ":multiplier", 15),
        (try_end),
        (val_min, ":multiplier", maximum_price_factor),
        (party_set_slot, "$g_encountered_party", ":item_slot_no", ":multiplier"),
      (try_end),
  ]),
  
  #script_game_event_sell_item:
  # This script is called from the game engine when player sells an item.
  # INPUT:
  # param1: item_kind_id
  ("game_event_sell_item",
    [
      (store_script_param_1, ":item_kind_id"),
      (store_script_param_2, ":return_mode"),
      (try_begin),
        (is_between, ":item_kind_id", trade_goods_begin, trade_goods_end),
        (store_sub, ":item_slot_no", ":item_kind_id", trade_goods_begin),
        (val_add, ":item_slot_no", slot_town_trade_good_prices_begin),
        (party_get_slot, ":multiplier", "$g_encountered_party", ":item_slot_no"),
        (try_begin),
          (eq, ":return_mode", 0),
          (val_sub, ":multiplier", 15),
        (else_try),
          (val_sub, ":multiplier", 10),
        (try_end),
        (val_max, ":multiplier", minimum_price_factor),
        (party_set_slot, "$g_encountered_party", ":item_slot_no", ":multiplier"),
      (try_end),
  ]),
  
  
  # script_game_get_troop_wage
  # This script is called from the game engine for calculating troop wages.
  # Input:
  # param1: troop_id, param2: party-id
  # Output: reg0: weekly wage
  
  ("game_get_troop_wage",
    [
      (store_script_param_1, ":troop_id"),
      (store_script_param_2, ":unused"), #party id
      
      (assign,":wage", 0),
      (try_begin),
        (troop_is_hero, ":troop_id"),
      (else_try),
        (store_character_level, ":troop_level", ":troop_id"),
        (assign, ":wage", ":troop_level"),
        (val_add, ":wage", 5),
        (val_mul, ":wage", ":wage"),
        (val_div, ":wage", 30),
      (try_end),
      (assign, reg0, ":wage"),
      (set_trigger_result, reg0),
  ]),
  
  # script_game_get_join_cost
  # This script is called from the game engine for calculating troop join cost.
  # Input:
  # param1: troop_id,
  # Output: reg0: weekly wage
  
  ("game_get_join_cost",
    [
      (store_script_param_1, ":troop_id"),
      
      (assign,":join_cost", 0),
      (try_begin),
        (troop_is_hero, ":troop_id"),
      (else_try),
        (store_character_level, ":troop_level", ":troop_id"),
        (assign, ":join_cost", ":troop_level"),
        (val_add, ":join_cost", 5),
        (val_mul, ":join_cost", ":join_cost"),
        (val_add, ":join_cost", 40),
        (val_div, ":join_cost", 5),
      (try_end),
      (assign, reg0, ":join_cost"),
      (set_trigger_result, reg0),
  ]),
  
  # script_game_get_prisoner_price
  # This script is called from the game engine for calculating prisoner price
  # Input:
  # param1: troop_id,
  # Output: reg0
  
  ("game_get_prisoner_price",
    [
      (store_script_param_1, ":troop_id"),
      (assign, reg0, 20),
      (try_begin),
        (is_between, "$g_talk_troop", ransom_brokers_begin, ransom_brokers_end),
        (store_character_level, ":troop_level", ":troop_id"),
        (assign, ":ransom_amount", ":troop_level"),
        (val_add, ":ransom_amount", 10), 
        (val_mul, ":ransom_amount", ":ransom_amount"),
        (val_div, ":ransom_amount", 6),
      (try_end),
      (set_trigger_result, reg0),
  ]),


  # script_game_check_prisoner_can_be_sold
  # This script is called from the game engine for checking if a given troop can be sold.
  # Input: 
  # param1: troop_id,
  # Output: reg0: 1= can be sold; 0= can not be sold.
  
  ("game_check_prisoner_can_be_sold",
    [
      (store_script_param_1, ":troop_id"),
      (assign, reg0, 0),
      (try_begin),
        (neg|troop_is_hero, ":troop_id"),
        (assign, reg0, 1),
      (try_end),
      (set_trigger_result, reg0),
  ]),

  #script_game_event_inspect_party:
  # This script is called from the game engine when player party inspects another party.
  # INPUT:
  # param1: Party-id
  ("game_event_inspect_party",
    [
  ]),

  #script_game_get_statistics_line:
  # This script is called from the game engine when statistics page is opened.
  # INPUT:
  # param1: line_no
  ("game_get_statistics_line",
    [
      (store_script_param_1, ":line_no"),
      (try_begin),
        (eq, ":line_no", 0),
        (get_player_agent_kill_count, reg1),
        (str_store_string, s1, "str_number_of_troops_killed_reg1"),
        (set_result_string, s1),
      (else_try),
        (eq, ":line_no", 1),
        (get_player_agent_kill_count, reg1, 1),
        (str_store_string, s1, "str_number_of_troops_wounded_reg1"),
        (set_result_string, s1),
      (else_try),
        (eq, ":line_no", 2),
        (get_player_agent_own_troop_kill_count, reg1),
        (str_store_string, s1, "str_number_of_own_troops_killed_reg1"),
        (set_result_string, s1),
      (else_try),
        (eq, ":line_no", 3),
        (get_player_agent_own_troop_kill_count, reg1, 1),
        (str_store_string, s1, "str_number_of_own_troops_wounded_reg1"),
        (set_result_string, s1),
      (try_end),
  ]),

  #script_game_get_date_text:
  # This script is called from the game engine when the date needs to be displayed.
  # INPUT: arg1 = number of days passed since the beginning of the game
  # OUTPUT: result string = date
  ("game_get_date_text",
    [
      (store_script_param_1, ":num_days"),
      (store_add, ":cur_day", ":num_days", 23),
      (assign, ":cur_month", 3),
      (assign, ":cur_year", 1257),
      (assign, ":try_range", 99999),
      (try_for_range, ":unused", 0, ":try_range"),
        (try_begin),
          (this_or_next|eq, ":cur_month", 1),
          (this_or_next|eq, ":cur_month", 3),
          (this_or_next|eq, ":cur_month", 5),
          (this_or_next|eq, ":cur_month", 7),
          (this_or_next|eq, ":cur_month", 8),
          (this_or_next|eq, ":cur_month", 10),
          (eq, ":cur_month", 12),
          (assign, ":month_day_limit", 31),
        (else_try),
          (this_or_next|eq, ":cur_month", 4),
          (this_or_next|eq, ":cur_month", 6),
          (this_or_next|eq, ":cur_month", 9),
          (eq, ":cur_month", 11),
          (assign, ":month_day_limit", 30),
        (else_try),
          (try_begin),
            (store_div, ":cur_year_div_4", ":cur_year", 4),
            (val_mul, ":cur_year_div_4", 4),
            (eq, ":cur_year_div_4", ":cur_year"),
            (assign, ":month_day_limit", 29),
          (else_try),
            (assign, ":month_day_limit", 28),      
          (try_end),
        (try_end),
        (try_begin),
          (gt, ":cur_day", ":month_day_limit"),
          (val_sub, ":cur_day", ":month_day_limit"),
          (val_add, ":cur_month", 1),
          (try_begin),
            (gt, ":cur_month", 12),
            (val_sub, ":cur_month", 12),
            (val_add, ":cur_year", 1),
          (try_end),
        (else_try),
          (assign, ":try_range", 0),
        (try_end),
      (try_end),
      (assign, reg1, ":cur_day"),
      (assign, reg2, ":cur_year"),
      (try_begin),
        (eq, ":cur_month", 1),
        (str_store_string, s1, "str_january_reg1_reg2"),
      (else_try),
        (eq, ":cur_month", 2),
        (str_store_string, s1, "str_february_reg1_reg2"),
      (else_try),
        (eq, ":cur_month", 3),
        (str_store_string, s1, "str_march_reg1_reg2"),
      (else_try),
        (eq, ":cur_month", 4),
        (str_store_string, s1, "str_april_reg1_reg2"),
      (else_try),
        (eq, ":cur_month", 5),
        (str_store_string, s1, "str_may_reg1_reg2"),
      (else_try),
        (eq, ":cur_month", 6),
        (str_store_string, s1, "str_june_reg1_reg2"),
      (else_try),
        (eq, ":cur_month", 7),
        (str_store_string, s1, "str_july_reg1_reg2"),
      (else_try),
        (eq, ":cur_month", 8),
        (str_store_string, s1, "str_august_reg1_reg2"),
      (else_try),
        (eq, ":cur_month", 9),
        (str_store_string, s1, "str_september_reg1_reg2"),
      (else_try),
        (eq, ":cur_month", 10),
        (str_store_string, s1, "str_october_reg1_reg2"),
      (else_try),
        (eq, ":cur_month", 11),
        (str_store_string, s1, "str_november_reg1_reg2"),
      (else_try),
        (eq, ":cur_month", 12),
        (str_store_string, s1, "str_december_reg1_reg2"),
      (try_end),
      (set_result_string, s1),
    ]),  
  
  #script_game_get_money_text:
  # This script is called from the game engine when an amount of money needs to be displayed.
  # INPUT: arg1 = amount in units
  # OUTPUT: result string = money in text
  ("game_get_money_text",
    [
      (store_script_param_1, ":amount"),
      (try_begin),
        (eq, ":amount", 1),
        (str_store_string, s1, "str_1_denar"),
      (else_try),
        (assign, reg1, ":amount"),
        (str_store_string, s1, "str_reg1_denars"),
      (try_end),
      (set_result_string, s1),
  ]),

  #script_game_get_party_companion_limit:
  # This script is called from the game engine when the companion limit is needed for a party.
  # INPUT: arg1 = none
  # OUTPUT: reg0 = companion_limit
  ("game_get_party_companion_limit",
    [
      (assign, ":troop_no", "trp_player"),

      (assign, ":limit", 10),
      (store_skill_level, ":skill", "skl_leadership", ":troop_no"),
      (store_attribute_level, ":charisma", ":troop_no", ca_charisma),
      (val_mul, ":skill", 3),
      (val_add, ":limit", ":skill"),
      (val_add, ":limit", ":charisma"),

      (troop_get_slot, ":troop_renown", ":troop_no", slot_troop_renown),
      (store_div, ":renown_bonus", ":troop_renown", 25),
      (val_add, ":limit", ":renown_bonus"),
##SG qi xi
      (try_begin),
        (ge,"$use_qixi",1),
        (try_begin),
          (eq,"$five",2),
          (val_sub, ":limit", 5),
        (else_try),
          (eq,"$ten",2),
          (val_sub, ":limit", 10),
        (else_try),
          (eq,"$twenty",2),
          (val_sub, ":limit", 20),
        (try_end),
      (try_end),
##SG qi xi
      (assign, reg0, ":limit"),
      (set_trigger_result, reg0),
  ]),

  # script_party_get_ideal_size @used for NPC parties.
  # Input: arg1 = party_no
  # Output: reg0: ideal size 
  ("party_get_ideal_size",
    [
      (store_script_param_1, ":party_no"),
      (assign, ":limit", 30),
      (try_begin),
        (party_slot_eq, ":party_no", slot_party_type, spt_kingdom_hero_party),
        (party_stack_get_troop_id, ":party_leader", ":party_no", 0),
        (store_faction_of_party, ":faction_id", ":party_no"),
        (assign, ":limit", 10),

        (store_skill_level, ":skill", "skl_leadership", ":party_leader"),
        (store_attribute_level, ":charisma", ":party_leader", ca_charisma),
        (val_mul, ":skill", 3),
        (val_add, ":limit", ":skill"),
        (val_add, ":limit", ":charisma"),

        (troop_get_slot, ":troop_renown", ":party_leader", slot_troop_renown),
        (store_div, ":renown_bonus", ":troop_renown", 25),
        (val_add, ":limit", ":renown_bonus"),

        (try_begin),
          (faction_slot_eq, ":faction_id", slot_faction_leader, ":party_leader"),
          (val_add, ":limit", 50),
        (try_end),
      (try_end),
      (assign, reg0, ":limit"),
  ]),


  #script_game_get_party_prisoner_limit:
  # This script is called from the game engine when the prisoner limit is needed for a party.
  # INPUT: arg1 = party_no
  # OUTPUT: reg0 = prisoner_limit
  ("game_get_party_prisoner_limit",
    [
#      (store_script_param_1, ":party_no"),
      (assign, ":troop_no", "trp_player"),

      (assign, ":limit", 0),
      (store_skill_level, ":skill", "skl_prisoner_management", ":troop_no"),
      (store_mul, ":limit", ":skill", 5),
      (assign, reg0, ":limit"),
      (set_trigger_result, reg0),
  ]),

  #script_game_get_item_extra_text:
  # This script is called from the game engine when an item's properties are displayed.
  # INPUT: arg1 = item_no, arg2 = extra_text_id (this can be between 0-7 (7 included))
  # OUTPUT: result_string = item extra text, trigger_result = text color (0 for default)
  ("game_get_item_extra_text",
    [
      (store_script_param, ":item_no", 1),
      (store_script_param, ":extra_text_id", 2),
      (try_begin),
        (is_between, ":item_no", morale_boosters_begin, morale_boosters_end),
        (try_begin),
          (eq, ":extra_text_id", 0),
          (item_get_slot, ":food_bonus", ":item_no", slot_item_food_bonus),
          (assign, reg1, ":food_bonus"),
          (set_result_string, "@+{reg1} to party morale"),
          (set_trigger_result, 0x4444FF),
        (try_end),
      (try_end),
  ]),

  #script_game_on_disembark:
  # This script is called from the game engine when the player reaches the shore with a ship.
  # INPUT: pos0 = disembark position
  # OUTPUT: none
  ("game_on_disembark",
   [(jump_to_menu, "mnu_disembark"),
  ]),


  #script_game_context_menu_get_buttons:
  # This script is called from the game engine when the player clicks the right mouse button over a party on the map.
  # INPUT: arg1 = party_no
  # OUTPUT: none, fills the menu buttons
  ("game_context_menu_get_buttons",
   [(store_script_param, ":party_no", 1),
    (try_begin),
      (neq, ":party_no", "p_main_party"),
      (context_menu_add_item, "@Move here", cmenu_move),
    (try_end),
    (try_begin),
      (is_between, ":party_no", centers_begin, centers_end),
      (context_menu_add_item, "@View notes", 1),
    (else_try),
      (party_get_num_companion_stacks, ":num_stacks", ":party_no"),
      (gt, ":num_stacks", 0),
      (party_stack_get_troop_id, ":troop_no", ":party_no", 0),
      (is_between, ":troop_no", kingdom_heroes_begin, kingdom_heroes_end),
      (context_menu_add_item, "@View notes", 2),
    (try_end),
  ]),

  #script_game_event_context_menu_button_clicked:
  # This script is called from the game engine when the player clicks on a button at the right mouse menu.
  # INPUT: arg1 = party_no, arg2 = button_value
  # OUTPUT: none
  ("game_event_context_menu_button_clicked",
   [(store_script_param, ":party_no", 1),
    (store_script_param, ":button_value", 2),
    (try_begin),
      (eq, ":button_value", 1),
      (change_screen_notes, 3, ":party_no"),
    (else_try),
      (eq, ":button_value", 2),
      (party_stack_get_troop_id, ":troop_no", ":party_no", 0),
      (change_screen_notes, 1, ":troop_no"),
    (try_end),
  ]),
  

  # npc_get_troop_wage
  # This script is called from module system to calculate troop wages for npc parties.
  # Input:
  # param1: troop_id
  # Output: reg0: weekly wage
  
  ("npc_get_troop_wage",
    [
   
      (store_script_param_1, ":troop_id"),
      (store_script_param_2, ":unused"), #party id
      
      (assign,":wage", 0),
      (try_begin),
        (troop_is_hero, ":troop_id"),
      (else_try),
        (store_character_level, ":troop_level", ":troop_id"),
        (assign, ":wage", ":troop_level"),
        (val_add, ":wage", 5),
        (val_mul, ":wage", ":wage"),
        (val_div, ":wage", 30),
      (try_end),
      (assign,reg0,":wage"),
      (assign,reg59,":wage"), # Use a backup reg
      (str_store_troop_name,s59,":troop_id"),
  ]),

  #script_setup_talk_info
  # INPUT:
  # param1: item_id
  # param2: production_rate (should be between -100 (for net consumption) and 100 (for net production)
  ("setup_talk_info",
    [
      (talk_info_set_relation_bar, "$g_talk_troop_relation"),
      (str_store_troop_name, s61, "$g_talk_troop"),
      (str_store_string, s61, "@ {s1}"),
      (assign, reg1, "$g_talk_troop_relation"),
      (str_store_string, s62, "str_relation_reg1"),
      (talk_info_set_line, 0, s61),
      (talk_info_set_line, 1, s62),
      (call_script, "script_describe_relation_to_s63", "$g_talk_troop_relation"),
      (talk_info_set_line, 3, s63),
  ]),

  #script_update_party_creation_random_limits
  # INPUT: none
  ("update_party_creation_random_limits",
    [
      (store_character_level, ":player_level", "trp_player"),
      (store_mul, ":upper_limit", ":player_level", 4),
      (store_div, ":upper_limit", ":player_level", 2),
      (val_add, ":upper_limit", 35),
      (val_min, ":upper_limit", 100),
      (set_party_creation_random_limits, 0, ":upper_limit"),
      (assign, reg0, ":upper_limit"),
  ]),


  #script_center_set_trade_good_production
  # INPUT:
  # param1: center_no
  # param2: item_id
  # param3: production_rate (should be between -100 (for net consumption) and 100 (for net production)
  ("center_set_trade_good_production",
    [
      (store_script_param, ":center_no", 1),
      (store_script_param, ":item_no", 2),
      (store_script_param, ":production_rate", 3),
      (val_sub, ":item_no", trade_goods_begin),
      (val_add, ":item_no", slot_town_trade_good_productions_begin),
      (party_set_slot, ":center_no", ":item_no", ":production_rate"),
  ]),
  
##  #script_average_trade_good_productions
##  # INPUT: none
##  ("average_trade_good_productions",
##    [
##      (store_sub, ":slot_to_temp_slot", slot_town_trade_good_temp_productions_begin, slot_town_trade_good_productions_begin),
##      (store_sub, ":item_to_slot", slot_town_trade_good_productions_begin, trade_goods_begin),
##      (store_sub, ":item_to_price_slot", slot_town_trade_good_prices_begin, trade_goods_begin),
##      (try_for_range, ":center_no", centers_begin, centers_end),
##        (this_or_next|is_between, ":center_no", towns_begin, towns_end),
##        (is_between, ":center_no", villages_begin, villages_end),
##        (try_for_range, ":cur_good", trade_goods_begin, trade_goods_end),
##          (store_add, ":cur_good_slot", ":cur_good", ":item_to_slot"),
##          (party_get_slot, ":old_production", ":center_no", ":cur_good_slot"),
##          (assign, ":new_production", ":old_production"),
##          (assign, ":abs_old_production", ":old_production"),
##          (try_begin),
##            (lt, ":abs_old_production", 0),
##            (val_mul, ":abs_old_production", -1),
##          (try_end),
##          (try_for_range, ":other_center", centers_begin, centers_end),
##            (this_or_next|is_between, ":center_no", towns_begin, towns_end),
##            (is_between, ":center_no", villages_begin, villages_end),
##            (neq, ":other_center", ":center_no"),
##            (store_distance_to_party_from_party, ":cur_distance", ":center_no", ":other_center"),
##            (lt, ":cur_distance", 50),
##            (party_get_slot, ":other_center_production", ":other_center", ":cur_good_slot"),
##            #change production rate only if other town's production rate's absolute value is greater than ours.
##            (assign, ":abs_other_production", ":other_center_production"),
##            (val_abs, ":abs_other_production"),
##            (try_begin),
##              (ge, ":abs_other_production", ":abs_old_production"),
##              (store_sub, ":net_difference", ":other_center_production", ":old_production"),
##              (store_sub, ":cur_effectiveness", 50, ":cur_distance"),
##              (val_mul, ":net_difference", ":cur_effectiveness"),
##              (val_div, ":net_difference", 250),
##              (val_add, ":new_production", ":net_difference"),
##            (try_end),
##          (try_end),
##          (store_add, ":cur_good_temp_slot", ":cur_good_slot", ":slot_to_temp_slot"),
##          (party_set_slot, ":center_no", ":cur_good_temp_slot", ":new_production"),
##        (try_end),
##      (try_end),
##      (try_for_range, ":center_no", centers_begin, centers_end),
##        (this_or_next|is_between, ":center_no", towns_begin, towns_end),
##        (is_between, ":center_no", villages_begin, villages_end),
##        #        (assign, reg40, ":center_no"),
##        #        (assign, reg41, 54321),
##        #        (display_message, "str_debug_string_1"),
##        (try_for_range, ":cur_good", trade_goods_begin, trade_goods_end),
##          (store_add, ":cur_good_slot", ":cur_good", ":item_to_slot"),
##          (store_add, ":cur_good_temp_slot", ":cur_good_slot", ":slot_to_temp_slot"),
##          (party_get_slot, ":new_production", ":center_no", ":cur_good_temp_slot"),
##          (party_set_slot, ":center_no", ":cur_good_slot", ":new_production"),
##          #          (assign, reg40, ":cur_good"),
##          #          (assign, reg41, ":new_production"),
##          #          (display_message, "str_debug_string_1"),
##          (store_add, ":cur_good_price_slot", ":cur_good", ":item_to_price_slot"),
##          (party_set_slot, ":center_no", ":cur_good_price_slot", average_price_factor),
##        (try_end),
##      (try_end),
##  ]),
##  
  
  #script_update_trade_good_prices
  # INPUT: none
  ("update_trade_good_prices",
    [
      (try_for_range, ":center_no", centers_begin, centers_end),
        (this_or_next|is_between, ":center_no", towns_begin, towns_end),
        (is_between, ":center_no", villages_begin, villages_end),
        (call_script, "script_update_trade_good_price_for_party", ":center_no"),
      (try_end),
      (call_script, "script_update_trade_good_price_for_party", "p_zendar"),
      (call_script, "script_update_trade_good_price_for_party", "p_salt_mine"),
      (call_script, "script_update_trade_good_price_for_party", "p_four_ways_inn"),
  ]),

  #script_update_trade_good_price_for_party
  # INPUT: arg1 = party_no
  ("update_trade_good_price_for_party",
    [
      (store_script_param, ":center_no", 1),
      (try_for_range, ":cur_good", trade_goods_begin, trade_goods_end),
        (store_sub, ":cur_good_slot", ":cur_good", trade_goods_begin),
        (val_add, ":cur_good_slot", slot_town_trade_good_productions_begin),
        (store_sub, ":cur_good_price_slot", ":cur_good", trade_goods_begin),
        (val_add, ":cur_good_price_slot", slot_town_trade_good_prices_begin),
        (party_get_slot, ":production", ":center_no", ":cur_good_slot"),
        (party_get_slot, ":cur_price", ":center_no", ":cur_good_price_slot"),
        (try_begin),
          (lt, ":production", 0), #demand is greater than supply
          (store_mul, ":change_factor", ":production", -3), #price will be increased by his factor
        (else_try),
          (store_mul, ":change_factor", ":production", 2), #price will be decreased by this factor
        (try_end),
        (val_mul, ":change_factor", 2),
        (store_random_in_range, ":random_change", 0, ":change_factor"),
        (try_begin),
          (lt, ":production", 0), #demand is greater than supply
          (val_add, ":cur_price", ":random_change"),
        (else_try),
          (val_sub, ":cur_price", ":random_change"),
        (try_end),
        #Move price towards average by 2%...
        (store_sub, ":price_difference", ":cur_price", average_price_factor),
        (val_mul, ":price_difference", 98),
        (val_div, ":price_difference", 100),
        (store_add, ":new_price", average_price_factor, ":price_difference"),
        (val_clamp, ":new_price", minimum_price_factor, maximum_price_factor),
        (party_set_slot, ":center_no", ":cur_good_price_slot", ":new_price"),
      (try_end),
  ]),  
  
  #script_do_merchant_town_trade
  # INPUT: arg1 = party_no (of the merchant), arg2 = center_no
  ("do_merchant_town_trade",
    [
      (store_script_param_1, ":party_no"),
      (store_script_param_2, ":center_no"),
      (call_script, "script_do_party_center_trade", ":party_no", ":center_no", 20), #change prices by 20%
      
      (assign, ":total_change", reg0),
      #Adding the earnings to the wealth (maximum changed price is the earning)
      (val_div, ":total_change", 2),
      (str_store_party_name, s1, ":party_no"),
      (str_store_party_name, s2, ":center_no"),
      (assign, reg1, ":total_change"),
      (try_begin),
        (eq, "$cheat_mode", 1),
        (display_message, "@Merchant {s1} traded with {s2} and earned {reg1} denars."),
      (try_end),

      #Adding tax revenue to the center
      (party_get_slot, ":accumulated_tariffs", ":center_no", slot_center_accumulated_tariffs),
      (val_div, ":total_change", 3), #33% of the merchant's revenue.
      (val_add, ":accumulated_tariffs", ":total_change"),
      (party_set_slot, ":center_no", slot_center_accumulated_tariffs, ":accumulated_tariffs"),
      
##      #Giving a constant wage to the party
##      (party_get_num_companions, ":party_size", ":party_no"),
##      (store_mul, ":party_wage", ":party_size", 5),
##      (val_sub, ":cur_wealth", ":party_wage"),
##      #Hiring new troops if wealth is above a limit
##      (try_begin),
##        (gt, ":cur_wealth", 2500),
##        (val_mul, ":party_wage", 30),
##        (gt, ":cur_wealth", ":party_wage"),
##        (party_add_template, ":party_no", "pt_merchant_party_reinforcement"),
##        (party_get_num_companions, ":party_new_size", ":party_no"),
##        (val_sub, ":party_new_size", ":party_size"),
##        (val_mul, ":party_new_size", 10),
##        (val_sub, ":cur_wealth", ":party_new_size"),
##      (try_end),
##      (val_max, ":cur_wealth", 2000),
##      (troop_set_slot, ":troop_no", slot_troop_wealth, ":cur_wealth"),
  ]),
  
  #script_party_calculate_regular_strength:
  # INPUT:
  # param1: Party-id
  ("party_calculate_regular_strength",
    [
      (store_script_param_1, ":party"), #Party_id
      
      (assign, reg(0),0),
      (party_get_num_companion_stacks, ":num_stacks",":party"),
      (try_for_range, ":i_stack", 0, ":num_stacks"),
        (party_stack_get_troop_id, ":stack_troop",":party",":i_stack"),
        (neg|troop_is_hero, ":stack_troop"),
        (store_character_level, ":stack_strength", ":stack_troop"),
        (val_add, ":stack_strength", 12),
        (val_mul, ":stack_strength", ":stack_strength"),
        (val_div, ":stack_strength", 100),
        (party_stack_get_size, ":stack_size",":party",":i_stack"),
        (party_stack_get_num_wounded, ":num_wounded",":party",":i_stack"),
        (val_sub, ":stack_size", ":num_wounded"),
        (val_mul, ":stack_strength", ":stack_size"),
        (val_add,reg(0), ":stack_strength"),
      (try_end),
  ]),
  
  
  
  
  #script_party_calculate_strength:
  # INPUT: arg1 = party_id
  # OUTPUT: reg0 = strength
  
  ("party_calculate_strength",
    [
      (store_script_param_1, ":party"), #Party_id
      
      (assign, reg(0),0),
      (party_get_num_companion_stacks, ":num_stacks",":party"),
      (try_for_range, ":i_stack", 0, ":num_stacks"),
        (party_stack_get_troop_id,     ":stack_troop",":party",":i_stack"),
        (store_character_level, ":stack_strength", ":stack_troop"),
        (val_add, ":stack_strength", 12),
        (val_mul, ":stack_strength", ":stack_strength"),
        (val_div, ":stack_strength", 100),
        (try_begin),
          (neg|troop_is_hero, ":stack_troop"),
          (party_stack_get_size, ":stack_size",":party",":i_stack"),
          (party_stack_get_num_wounded, ":num_wounded",":party",":i_stack"),
          (val_sub, ":stack_size", ":num_wounded"),
          (val_mul, ":stack_strength", ":stack_size"),
        (else_try),
          (store_troop_health, ":troop_health",":stack_troop"), #hero...
          (le, ":troop_health", 20),
          (assign,":stack_strength",0),
        (try_end),
        (val_add,reg(0), ":stack_strength"),
      (try_end),
  ]),
  
  #script_party_calculate_loot:
  # INPUT:
  # param1: Party-id
  # Returns num looted items in reg(0)
  
  ("party_calculate_loot",
    [
      (store_script_param_1, ":enemy_party"), #Enemy Party_id
      
      (assign,":item_id",0),
      (call_script, "script_calculate_main_party_shares"),
      (assign, ":num_player_party_shares", reg0),
      #      (assign, ":num_ally_shares", reg1),
      #      (store_add, ":num_shares",  ":num_player_party_shares", ":num_ally_shares"),
      
      #Calculate player loot probability
      #      (assign, ":loot_proboability", 100),
      #      (val_mul, ":loot_proboability", 10),
      #      (val_div, ":loot_proboability", ":num_shares"),
      
      (assign, ":loot_proboability", 10),
      (val_mul, ":loot_proboability", "$g_strength_contribution_of_player"),
      (val_div, ":loot_proboability", ":num_player_party_shares"),

      (try_for_range, ":i_loot", 0, num_party_loot_slots),
        (store_add, ":cur_loot_slot", ":i_loot", slot_party_looted_item_1),
        (party_get_slot, ":item_no", "$g_enemy_party", ":cur_loot_slot"),
        (gt, ":item_no", 0),
        (party_set_slot, "$g_enemy_party", ":cur_loot_slot", 0),
        (val_sub, ":cur_loot_slot", slot_party_looted_item_1),
        (val_add, ":cur_loot_slot", slot_party_looted_item_1_modifier),
        (party_get_slot, ":item_modifier", "$g_enemy_party", ":cur_loot_slot"),
        (troop_add_item, "trp_temp_troop", ":item_no", ":item_modifier"),
      (try_end),
      (party_set_slot, "$g_enemy_party", slot_party_next_looted_item_slot, 0),
      
      #Now loot the defeated party
      (party_get_num_companion_stacks, ":num_stacks",":enemy_party"),
      (try_for_range, ":i_stack", 0, ":num_stacks"),
        (party_stack_get_troop_id,     ":stack_troop",":enemy_party",":i_stack"),
        (neg|troop_is_hero, ":stack_troop"),
        (party_stack_get_size, ":stack_size",":enemy_party",":i_stack"),
        (try_for_range, ":unused", 0, ":stack_size"),
          (troop_loot_troop,"trp_temp_troop",":stack_troop",":loot_proboability"),
        (try_end),
      (try_end),
      (assign, ":num_looted_items",0),
      (troop_get_inventory_capacity, ":inv_cap", "trp_temp_troop"),
      (try_for_range, ":i_slot", 0, ":inv_cap"),
        (troop_get_inventory_slot, ":item_id", "trp_temp_troop", ":i_slot"),
        (ge, ":item_id", 0),
        (val_add, ":num_looted_items",1),
      (try_end),
      
      (try_begin),
        (party_slot_eq, "$g_enemy_party", slot_party_type, spt_kingdom_caravan),
        (assign, ":plunder_amount", 10),
        (val_mul, ":plunder_amount", "$g_strength_contribution_of_player"),
        (val_div, ":plunder_amount", 40),
        #       (val_div, ":plunder_amount", ":num_player_party_shares"),
        (val_clamp, ":plunder_amount", 1, 50),
        (store_sub, ":item_to_price_slot", slot_town_trade_good_prices_begin, trade_goods_begin),
        (reset_item_probabilities,100),
        (try_for_range, ":cur_goods", trade_goods_begin, trade_goods_end),
          (store_add, ":cur_price_slot", ":cur_goods", ":item_to_price_slot"),
          (party_get_slot, ":cur_price", "$g_enemy_party", ":cur_price_slot"),
          (assign, ":cur_probability", 100),
          (val_mul, ":cur_probability", average_price_factor),
          (val_div, ":cur_probability", ":cur_price"),
          (val_mul, ":cur_probability", average_price_factor),
          (val_div, ":cur_probability", ":cur_price"),
          (val_mul, ":cur_probability", average_price_factor),
          (val_div, ":cur_probability", ":cur_price"),
          (set_item_probability_in_merchandise,":cur_goods",":cur_probability"),
        (try_end),
        (troop_add_merchandise,"trp_temp_troop",itp_type_goods,":plunder_amount"),
        (val_add, ":num_looted_items", ":plunder_amount"),
      (try_end),
      (assign, reg0, ":num_looted_items"),
  ]),
  
  #script_calculate_main_party_shares:
  # INPUT:
  # Returns number of player party shares in reg0
  
  ("calculate_main_party_shares",
    [
      (assign, ":num_player_party_shares",5),
      # Add shares for player's party
      (party_get_num_companion_stacks, ":num_stacks","p_main_party"),
      (try_for_range, ":i_stack", 1, ":num_stacks"),
        (party_stack_get_troop_id,     ":stack_troop","p_main_party",":i_stack"),
        (try_begin),
          (neg|troop_is_hero, ":stack_troop"),
          (party_stack_get_size, ":stack_size","p_main_party",":i_stack"),
          (val_add, ":num_player_party_shares", ":stack_size"),
        (else_try),
          (val_add, ":num_player_party_shares", 5),
        (try_end),
      (try_end),
      
      (assign, reg0, ":num_player_party_shares"),
  ]),
  
  #script_party_give_xp_and_gold:
  # INPUT:
  # param1: destroyed Party-id
  # calculates and gives player paty's share of gold and xp.
  
  ("party_give_xp_and_gold",
    [
      (store_script_param_1, ":enemy_party"), #Party_id
      
      (call_script, "script_calculate_main_party_shares"),
      (assign, ":num_player_party_shares", reg0),
      
      #      (assign, ":num_ally_shares", reg1),
      #     (store_add, ":num_total_shares",  ":num_player_party_shares", ":num_ally_shares"),
      
      (assign, ":total_gain", 0),
      (party_get_num_companion_stacks, ":num_stacks",":enemy_party"),
      (try_for_range, ":i_stack", 0, ":num_stacks"),
        (party_stack_get_troop_id,     ":stack_troop",":enemy_party",":i_stack"),
        (neg|troop_is_hero, ":stack_troop"),
        (party_stack_get_size, ":stack_size",":enemy_party",":i_stack"),
        (store_character_level, ":level", ":stack_troop"),
        (store_add, ":gain", ":level", 10),
        (val_mul, ":gain", ":gain"),
        (val_div, ":gain", 10),
        (store_mul, ":stack_gain", ":gain", ":stack_size"),
        (val_add, ":total_gain", ":stack_gain"),
      (try_end),
      
      (val_mul, ":total_gain", "$g_strength_contribution_of_player"),
      (val_div, ":total_gain", 100),

      (val_min, ":total_gain", 40000), #eliminate negative results
      
      
      #      (store_mul, ":player_party_xp_gain", ":total_gain", ":num_player_party_shares"),
      #      (val_div, ":player_party_xp_gain", ":num_total_shares"),
      
      (assign, ":player_party_xp_gain", ":total_gain"),
      
      (store_random_in_range, ":r", 50, 100),
      (val_mul, ":player_party_xp_gain", ":r"),
      (val_div, ":player_party_xp_gain", 100),
      
      (party_add_xp, "p_main_party", ":player_party_xp_gain"),
      
      (store_mul, ":player_gold_gain", ":total_gain", 5),
      (val_min, ":player_gold_gain", 60000), #eliminate negative results
      (store_random_in_range, ":r", 50, 100),
      (val_mul, ":player_gold_gain", ":r"),
      (val_div, ":player_gold_gain", 100),
      (val_div, ":player_gold_gain", ":num_player_party_shares"),
      
      #add gold now
      (party_get_num_companion_stacks, ":num_stacks","p_main_party"),
      (try_for_range, ":i_stack", 0, ":num_stacks"),
        (party_stack_get_troop_id,     ":stack_troop","p_main_party",":i_stack"),
        (try_begin),
          (troop_is_hero, ":stack_troop"),
          (troop_add_gold, ":stack_troop", ":player_gold_gain"),
        (try_end),
      (try_end),

      #Add morale
      (assign, ":morale_gain", ":total_gain"),
      (val_div, ":morale_gain", ":num_player_party_shares"),
      (call_script, "script_change_player_party_morale", ":morale_gain"),
  ]),
  
  
  #script_setup_troop_meeting:
  # INPUT:
  # param1: troop_id with which meeting will be made.
  # param2: troop_dna (optional)
  
  ("setup_troop_meeting",
    [
      (store_script_param_1, ":meeting_troop"),
      (store_script_param_2, ":troop_dna"),
      (modify_visitors_at_site,"scn_conversation_scene"),(reset_visitors),
      (set_visitor,0,"trp_player"),
      #       (party_stack_get_troop_dna,":troop_dna",":meeting_party",0),
      (set_visitor,17,":meeting_troop",":troop_dna"),
      (set_jump_mission,"mt_conversation_encounter"),
      (jump_to_scene,"scn_conversation_scene"),
      (change_screen_map_conversation, ":meeting_troop"),
  ]),
  
  #script_setup_party_meeting:
  # INPUT:
  # param1: Party-id with which meeting will be made.
  
  ("setup_party_meeting",
    [
      (store_script_param_1, ":meeting_party"),
      (modify_visitors_at_site,"scn_conversation_scene"),(reset_visitors),
      (set_visitor,0,"trp_player"),
      (party_stack_get_troop_id, ":meeting_troop",":meeting_party",0),
      (party_stack_get_troop_dna,":troop_dna",":meeting_party",0),
      (set_visitor,17,":meeting_troop",":troop_dna"),
      (set_jump_mission,"mt_conversation_encounter"),
      (jump_to_scene,"scn_conversation_scene"),
      (change_screen_map_conversation, ":meeting_troop"),
  ]),
  
  #script_party_remove_all_companions:
  # INPUT:
  # param1: Party-id from which  companions will be removed.
  # "$g_move_heroes" : controls if heroes will also be removed.
  
  ("party_remove_all_companions",
    [
      (store_script_param_1, ":party"), #Source Party_id
      (party_get_num_companion_stacks, ":num_companion_stacks",":party"),
      (try_for_range_backwards, ":stack_no", 0, ":num_companion_stacks"),
        (party_stack_get_troop_id,   ":stack_troop",":party",":stack_no"),
        (this_or_next|neg|troop_is_hero, ":stack_troop"),
        (eq, "$g_move_heroes", 1),
        (party_stack_get_size,  ":stack_size",":party",":stack_no"),
        (party_remove_members, ":party", ":stack_troop",  ":stack_size"),
      (try_end),
  ]),
  
  #script_party_remove_all_prisoners:
  # INPUT:
  # param1: Party-id from which  prisoners will be removed.
  # "$g_move_heroes" : controls if heroes will also be removed.
  
  ("party_remove_all_prisoners",
    [
      (store_script_param_1, ":party"), #Source Party_id
      (party_get_num_prisoner_stacks, ":num_prisoner_stacks",":party"),
      (try_for_range_backwards, ":stack_no", 0, ":num_prisoner_stacks"),
        (party_prisoner_stack_get_troop_id,   ":stack_troop",":party",":stack_no"),
        (this_or_next|neg|troop_is_hero, ":stack_troop"),
        (eq, "$g_move_heroes", 1),
        (party_prisoner_stack_get_size, ":stack_size",":party",":stack_no"),
        (party_remove_prisoners, ":party", ":stack_troop", ":stack_size"),
      (try_end),
  ]),
  
  #script_party_add_party_companions:
  # INPUT:
  # param1: Party-id to add the second part
  # param2: Party-id which will be added to the first one.
  # "$g_move_heroes" : controls if heroes will also be added.
  
  ("party_add_party_companions",
    [
      (store_script_param_1, ":target_party"), #Target Party_id
      (store_script_param_2, ":source_party"), #Source Party_id
      (party_get_num_companion_stacks, ":num_stacks",":source_party"),
      (try_for_range, ":stack_no", 0, ":num_stacks"),
        (party_stack_get_troop_id,     ":stack_troop",":source_party",":stack_no"),
        (this_or_next|neg|troop_is_hero, ":stack_troop"),
        (eq, "$g_move_heroes", 1),
        (party_stack_get_size,         ":stack_size",":source_party",":stack_no"),
        (party_add_members, ":target_party", ":stack_troop", ":stack_size"),
        (party_stack_get_num_wounded, ":num_wounded", ":source_party", ":stack_no"),
        (party_wound_members, ":target_party", ":stack_troop", ":num_wounded"),
      (try_end),
  ]),
  
  #script_party_add_party_prisoners:
  # INPUT:
  # param1: Party-id to add the second party
  # param2: Party-id which will be added to the first one.
  # "$g_move_heroes" : controls if heroes will also be added.
  
  ("party_add_party_prisoners",
    [
      (store_script_param_1, ":target_party"), #Target Party_id
      (store_script_param_2, ":source_party"), #Source Party_id
      (party_get_num_prisoner_stacks, ":num_stacks",":source_party"),
      (try_for_range, ":stack_no", 0, ":num_stacks"),
        (party_prisoner_stack_get_troop_id,     ":stack_troop",":source_party",":stack_no"),
        (this_or_next|neg|troop_is_hero, ":stack_troop"),
        (eq, "$g_move_heroes", 1),
        (party_prisoner_stack_get_size,         ":stack_size",":source_party",":stack_no"),
        (party_add_members, ":target_party", ":stack_troop", ":stack_size"),
      (try_end),
  ]),
  
  #script_party_prisoners_add_party_companions:
  # INPUT:
  # param1: Party-id to add the second part
  # param2: Party-id which will be added to the first one.
  # "$g_move_heroes" : controls if heroes will also be added.
  
  ("party_prisoners_add_party_companions",
    [
      (store_script_param_1, ":target_party"), #Target Party_id
      (store_script_param_2, ":source_party"), #Source Party_id
      (party_get_num_companion_stacks, ":num_stacks",":source_party"),
      (try_for_range, ":stack_no", 0, ":num_stacks"),
        (party_stack_get_troop_id,     ":stack_troop",":source_party",":stack_no"),
        (this_or_next|neg|troop_is_hero, ":stack_troop"),
        (eq, "$g_move_heroes", 1),
        (party_stack_get_size, ":stack_size",":source_party",":stack_no"),
        (party_add_prisoners, ":target_party", ":stack_troop", ":stack_size"),
      (try_end),
  ]),
  
  #script_party_prisoners_add_party_prisoners:
  # INPUT:
  # param1: Party-id to add the second part
  # param2: Party-id which will be added to the first one.
  # "$g_move_heroes" : controls if heroes will also be added.
  
  ("party_prisoners_add_party_prisoners",
    [
      (store_script_param_1, ":target_party"), #Target Party_id
      (store_script_param_2, ":source_party"), #Source Party_id
      (party_get_num_prisoner_stacks, ":num_stacks",":source_party"),
      (try_for_range, ":stack_no", 0, ":num_stacks"),
        (party_prisoner_stack_get_troop_id,     ":stack_troop",":source_party",":stack_no"),
        (this_or_next|neg|troop_is_hero, ":stack_troop"),
        (eq, "$g_move_heroes", 1),
        (party_prisoner_stack_get_size,         ":stack_size",":source_party",":stack_no"),
        (party_add_prisoners, ":target_party", ":stack_troop", ":stack_size"),
      (try_end),
  ]),
  
  # script_party_add_party:
  # INPUT:
  # param1: Party-id to add the second part
  # param2: Party-id which will be added to the first one.
  # "$g_move_heroes" : controls if heroes will also be added.
  
  ("party_add_party",
    [
      (store_script_param_1, ":target_party"), #Target Party_id
      (store_script_param_2, ":source_party"), #Source Party_id
      (call_script, "script_party_add_party_companions",          ":target_party", ":source_party"),
      (call_script, "script_party_prisoners_add_party_prisoners", ":target_party", ":source_party"),
  ]),
  
  
  #script_party_copy:
  # INPUT:
  # param1: Party-id to copy the second party
  # param2: Party-id which will be copied to the first one.
  
  ("party_copy",
    [
      (assign, "$g_move_heroes", 1),
      (store_script_param_1, ":target_party"), #Target Party_id
      (store_script_param_2, ":source_party"), #Source Party_id
      (party_clear, ":target_party"),
      (call_script, "script_party_add_party", ":target_party", ":source_party"),
  ]),
  
  
  #script_clear_party_group:
  # INPUT:
  # param1: Party-id of the root of the group.
  # This script will clear the root party and all parties attached to it recursively.
  
  ("clear_party_group",
    [
      (store_script_param_1, ":root_party"),
      (party_clear, ":root_party"),
      (party_get_num_attached_parties, ":num_attached_parties", ":root_party"),
      (try_for_range, ":attached_party_rank", 0, ":num_attached_parties"),
        (party_get_attached_party_with_rank, ":attached_party", ":root_party", ":attached_party_rank"),
        (call_script, "script_clear_party_group", ":attached_party"),
      (try_end),
  ]),
  
  #script_get_nonempty_party_in_group:
  # INPUT:
  # param1: Party-id of the root of the group.
  # OUTPUT: reg0: nonempy party-id
  
  ("get_nonempty_party_in_group",
    [
      
      (store_script_param_1, ":party_no"),
      (party_get_num_companions, ":num_companions", ":party_no"),
      (try_begin),
        (gt, ":num_companions", 0),
        (assign, reg0, ":party_no"),
      (else_try),
        (assign, reg0, -1),
        
        (party_get_num_attached_parties, ":num_attached_parties", ":party_no"),
        (try_for_range, ":attached_party_rank", 0, ":num_attached_parties"),
          (lt, reg0, 0),
          (party_get_attached_party_with_rank, ":attached_party", ":party_no", ":attached_party_rank"),
          (call_script, "script_get_nonempty_party_in_group", ":attached_party"),
        (try_end),
      (try_end),
  ]),
  
  #script_collect_prisoners_from_empty_parties:
  # INPUT:
  # param1: Party-id of the root of the group.
  # param2: Party to collect prisoners in.
  # make sure collection party is cleared before calling this.
  
  ("collect_prisoners_from_empty_parties",
    [
      (store_script_param_1, ":party_no"),
      (store_script_param_2, ":collection_party"),
      
      (party_get_num_companions, ":num_companions", ":party_no"),
      (try_begin),
        (eq, ":num_companions", 0), #party is empty (has no companions). Collect its prisoners.
        (party_get_num_prisoner_stacks, ":num_stacks",":party_no"),
        (try_for_range, ":stack_no", 0, ":num_stacks"),
          (party_prisoner_stack_get_troop_id,     ":stack_troop",":party_no",":stack_no"),
          (troop_is_hero, ":stack_troop"),
          (party_add_members, ":collection_party", ":stack_troop", 1),
        (try_end),
      (try_end),
      (party_get_num_attached_parties, ":num_attached_parties", ":party_no"),
      (try_for_range, ":attached_party_rank", 0, ":num_attached_parties"),
        (party_get_attached_party_with_rank, ":attached_party", ":party_no", ":attached_party_rank"),
        (call_script, "script_collect_prisoners_from_empty_parties", ":attached_party", ":collection_party"),
      (try_end),
  ]),
  
  
  
  #script_print_casualties_to_s0:
  # INPUT:
  # param1: Party_id, param2: 0 = use new line, 1 = use comma
  
  #OUTPUT:
  # string register 0.
  
  ("print_casualties_to_s0",
    [(store_script_param, ":party_no", 1),
     (store_script_param, ":use_comma", 2),
     (str_clear, s0),
     (assign, ":total_reported", 0),
     (assign, ":total_wounded", 0),
     (assign, ":total_killed", 0),
     (party_get_num_companion_stacks, ":num_stacks",":party_no"),
     (try_for_range, ":i_stack", 0, ":num_stacks"),
       (party_stack_get_troop_id, ":stack_troop",":party_no",":i_stack"),
       (party_stack_get_size, ":stack_size",":party_no",":i_stack"),
       (party_stack_get_num_wounded, ":num_wounded",":party_no",":i_stack"),
       (store_sub, ":num_killed", ":stack_size", ":num_wounded"),
       (val_add, ":total_killed", ":num_killed"),
       (val_add, ":total_wounded", ":num_wounded"),
       (try_begin),
         (this_or_next|gt, ":num_killed", 0),
         (gt, ":num_wounded", 0),
         (store_add, reg3, ":num_killed", ":num_wounded"),
         (str_store_troop_name_by_count, s1, ":stack_troop", reg3),
         (try_begin),
           (troop_is_hero, ":stack_troop"),
           (assign, reg3, 0),
         (try_end),
         (try_begin),
           (gt, ":num_killed", 0),
           (gt, ":num_wounded", 0),
           (assign, reg4, ":num_killed"),
           (assign, reg5, ":num_wounded"),
           (str_store_string, s2, "@{reg4} killed, {reg5} wounded"),
         (else_try),
           (gt, ":num_killed", 0),
           (str_store_string, s2, "@killed"),
         (else_try),
           (str_store_string, s2, "@wounded"),
         (try_end),
         (try_begin),
           (eq, ":use_comma", 1),
           (try_begin),
             (eq, ":total_reported", 0),
             (str_store_string, s0, "@{reg3?{reg3}:} {s1} ({s2})"),
           (else_try),
             (str_store_string, s0, "@{s0}, {reg3?{reg3}:} {s1} ({s2})"),
           (try_end),
         (else_try),
           (str_store_string, s0, "@{s0}^{reg3?{reg3}:} {s1} ({s2})"),
         (try_end),
         (val_add, ":total_reported", 1),
       (try_end),
     (try_end),

     (try_begin),
       (this_or_next|gt, ":total_killed", 0),
       (gt, ":total_wounded", 0),
       (store_add, reg3, ":total_killed", ":total_wounded"),
       (try_begin),
         (gt, ":total_killed", 0),
         (gt, ":total_wounded", 0),
         (assign, reg4, ":total_killed"),
         (assign, reg5, ":total_wounded"),
         (str_store_string, s2, "@{reg4} killed, {reg5} wounded"),
       (else_try),
         (gt, ":total_killed", 0),
         (str_store_string, s2, "@killed"),
       (else_try),
         (str_store_string, s2, "@wounded"),
       (try_end),
       (str_store_string, s0, "@{s0}^TOTAL: {reg3} ({s2})"),
     (else_try),
       (try_begin),
         (eq, ":use_comma", 1),
         (str_store_string, s0, "@None"),
       (else_try),
         (str_store_string, s0, "@^None"),
       (try_end),
     (try_end),
  ]),
  
  
  #script_print_party_to_s0:
  # INPUT:
  # param1: Party-id
  
  #OUTPUT:
  # string register 0.
  
  ##  ("print_party_to_s0",
  ##    [
  ##      (store_script_param_1, ":party"), #Party_id
  ##      (party_get_num_companion_stacks, ":num_stacks",":party"),
  ##      (str_store_string, s50, "str_none"),
  ##      (try_for_range, ":i_stack", 0, ":num_stacks"),
  ##        (party_stack_get_troop_id,     ":stack_troop",":party",":i_stack"),
  ##        (party_stack_get_size,         ":stack_size",":party",":i_stack"),
  ##        (str_store_troop_name_by_count, s61, ":stack_troop", ":stack_size"),
  ##        (try_begin),
  ##          (troop_is_hero, ":stack_troop"),
  ##          (str_store_string_reg, s51, s61),
  ##        (else_try),
  ##          (assign, reg60, ":stack_size"),
  ##          (str_store_string, s63, "str_reg60_s61"),
  ##        (try_end),
  ##        (try_begin),
  ##          (eq, ":i_stack", 0),
  ##          (str_store_string_reg, s50, s51),
  ##        (else_try),
  ##          (str_store_string, s50, "str_s50_comma_s51"),
  ##        (try_end),
  ##      (try_end),
  ##      (str_store_string_reg, s0, s50),
  ##  ]),
  

  
  #script_party_count_fit_regulars:
  # Returns the number of unwounded regular companions in a party
  # INPUT:
  # param1: Party-id
  
  ("party_count_fit_regulars",
    [
      (store_script_param_1, ":party"), #Party_id
      (party_get_num_companion_stacks, ":num_stacks",":party"),
      (assign, reg0, 0),
      (try_for_range, ":i_stack", 0, ":num_stacks"),
        (party_stack_get_troop_id,     ":stack_troop",":party",":i_stack"),
        (neg|troop_is_hero, ":stack_troop"),
        (party_stack_get_size,         ":stack_size",":party",":i_stack"),
        (party_stack_get_num_wounded, ":num_wounded",":party",":i_stack"),
        (val_sub, ":stack_size", ":num_wounded"),
        (val_add, reg0, ":stack_size"),
      (try_end),
  ]),
  
  
  #script_party_count_fit_for_battle:
  # Returns the number of unwounded regular companions in a party
  # INPUT:
  # param1: Party-id
  # OUTPUT: reg0 = result
  ("party_count_fit_for_battle",
    [
      (store_script_param_1, ":party"), #Party_id
      (party_get_num_companion_stacks, ":num_stacks",":party"),
      (assign, reg0, 0),
      (try_for_range, ":i_stack", 0, ":num_stacks"),
        (party_stack_get_troop_id,     ":stack_troop",":party",":i_stack"),
        (assign, ":num_fit",0),
        (try_begin),
          (troop_is_hero, ":stack_troop"),
#          (store_troop_health, ":troop_hp", ":stack_troop"),
          (try_begin),
            (neg|troop_is_wounded, ":stack_troop"),
#            (ge,  ":troop_hp", 20),
            (assign, ":num_fit",1),
          (try_end),
        (else_try),
          (party_stack_get_size,         ":num_fit",":party",":i_stack"),
          (party_stack_get_num_wounded, ":num_wounded",":party",":i_stack"),
          (val_sub, ":num_fit", ":num_wounded"),
        (try_end),
        (val_add, reg0, ":num_fit"),
      (try_end),
  ]),
  
  #script_party_count_prisoners:
  # Returns the number of prisoners in a party
  # INPUT:
  # param1: Party-id
  
  ("party_count_prisoners",
    [
      (store_script_param_1, ":party"), #Party_id
      (party_get_num_prisoner_stacks, ":num_stacks",":party"),
      (assign, reg0, 0),
      (try_for_range, ":i_stack", 0, ":num_stacks"),
        (party_prisoner_stack_get_size,         ":stack_size",":party",":i_stack"),
        (val_add, reg0, ":stack_size"),
      (try_end),
  ]),
  
  ##  ("get_fit_stack_with_rank",
  ##    [
  ##      (store_script_param_1, ":party"), #Party_id
  ##      (store_script_param_2, ":rank"), #Rank
  ##      (party_get_num_companion_stacks, ":num_stacks",":party"),
  ##      (assign, reg0, -1),
  ##      (assign, ":num_total", 0),
  ##      (try_for_range, ":i_stack", 0, ":num_stacks"),
  ##        (eq, reg(0), -1), #continue only if we haven't found the result yet.
  ##        (party_stack_get_troop_id,     ":stack_troop",":party",":i_stack"),
  ##        (assign, ":num_fit",0),
  ##        (try_begin),
  ##          (troop_is_hero, ":stack_troop"),
  ##          (store_troop_health, ":troop_hp", ":stack_troop"),
  ##          (try_begin),
  ##            (ge,  ":troop_hp", 20),
  ##            (assign, ":num_fit",1),
  ##          (try_end),
  ##        (else_try),
  ##          (party_stack_get_size,         ":num_fit",":party",":i_stack"),
  ##          (party_stack_get_num_wounded, ":num_wounded",":party",":i_stack"),
  ##          (val_sub, ":num_fit", ":num_wounded"),
  ##        (try_end),
  ##        (val_add, ":num_total", ":num_fit"),
  ##        (try_begin),
  ##          (lt, ":rank", ":num_total"),
  ##          (assign, reg(0), ":i_stack"),
  ##        (try_end),
  ##      (try_end),
  ##  ]),
  
  #script_get_stack_with_rank:
  # Returns the stack no, containing unwounded regular companions with rank rank.
  # INPUT:
  # param1: Party-id
  # param2: rank
  
  ("get_stack_with_rank",
    [
      (store_script_param_1, ":party"), #Party_id
      (store_script_param_2, ":rank"), #Rank
      (party_get_num_companion_stacks, ":num_stacks",":party"),
      (assign, reg(0), -1),
      (assign, ":num_total", 0),
      (try_for_range, ":i_stack", 0, ":num_stacks"),
        (eq, reg(0), -1), #continue only if we haven't found the result yet.
        (party_stack_get_troop_id,     ":stack_troop",":party",":i_stack"),
        (neg|troop_is_hero, ":stack_troop"),
        (party_stack_get_size,         ":stack_size",":party",":i_stack"),
        (party_stack_get_num_wounded,  ":num_wounded",":party",":i_stack"),
        (val_sub, ":stack_size", ":num_wounded"),
        (val_add, ":num_total", ":stack_size"),
        (try_begin),
          (lt, ":rank", ":num_total"),
          (assign, reg(0), ":i_stack"),
        (try_end),
      (try_end),
  ]),
  
  #script_inflict_casualties_to_party:
  # INPUT:
  # param1: Party-id
  # param2: number of rounds
  
  #OUTPUT:
  # This script doesn't return a value but populates the parties p_temp_wounded and p_temp_killed with the wounded and killed.
  #Example:
  #  (script_inflict_casualties_to_party, "_p_main_party" ,50),
  #  Simulate 50 rounds of casualties to main_party.
  
  ("inflict_casualties_to_party",
    [
      (party_clear, "p_temp_casualties"),
      (store_script_param_1, ":party"), #Party_id
      (call_script, "script_party_count_fit_regulars", ":party"),
      (assign, ":num_fit", reg(0)), #reg(47) = number of fit regulars.
      (store_script_param_2, ":num_attack_rounds"), #number of attacks
      (try_for_range, ":unused", 0, ":num_attack_rounds"),
        (gt, ":num_fit", 0),
        (store_random_in_range, ":attacked_troop_rank", 0 , ":num_fit"), #attack troop with rank reg(46)
        (assign, reg1, ":attacked_troop_rank"),
        (call_script, "script_get_stack_with_rank", ":party", ":attacked_troop_rank"),
        (assign, ":attacked_stack", reg(0)), #reg(53) = stack no to attack.
        #        (display_message,"str_debug_reg0"),
        (party_stack_get_troop_id,     ":attacked_troop",":party",":attacked_stack"),
        (store_character_level, ":troop_toughness", ":attacked_troop"),
        (val_add, ":troop_toughness", 5),  #troop-toughness = level + 5
        (assign, ":casualty_chance", 10000),
        (val_div, ":casualty_chance", ":troop_toughness"), #dying chance
        (try_begin),
          (store_random_in_range, ":rand_num", 0 ,10000),
          (lt, ":rand_num", ":casualty_chance"), #check chance to be a casualty
          (store_random_in_range, ":rand_num2", 0, 2), #check if this troop will be wounded or killed
          (try_begin),
            (troop_is_hero,":attacked_troop"), #currently troop can't be a hero, but no harm in keeping this.
            (store_troop_health, ":troop_hp",":attacked_troop"),
            (val_sub, ":troop_hp", 45),
            (val_max, ":troop_hp", 1),
            (troop_set_health, ":attacked_troop", ":troop_hp"),
          (else_try),
            (lt, ":rand_num2", 1), #wounded
            (party_add_members, "p_temp_casualties", ":attacked_troop", 1),
            (party_wound_members, "p_temp_casualties", ":attacked_troop", 1),
            (party_wound_members, ":party", ":attacked_troop", 1),
          (else_try), #killed
            (party_add_members, "p_temp_casualties", ":attacked_troop", 1),
            (party_remove_members, ":party", ":attacked_troop", 1),
          (try_end),
          (val_sub, ":num_fit", 1), #adjust number of fit regulars.
        (try_end),
      (try_end),
  ]),
  
  
  #script_move_members_with_ratio:
  # INPUT:
  # param1: Source Party-id
  # param2: Target Party-id
  # pin_number = ratio of members to move, multiplied by 1000
  
  #OUTPUT:
  # This script doesn't return a value but moves some of the members of source party to target party according to the given ratio.
  ("move_members_with_ratio",
    [
      (store_script_param_1, ":source_party"), #Source Party_id
      (store_script_param_2, ":target_party"), #Target Party_id
      (party_get_num_prisoner_stacks, ":num_stacks",":source_party"),
      (try_for_range_backwards, ":stack_no", 0, ":num_stacks"),
        (party_prisoner_stack_get_troop_id,     ":stack_troop",":source_party",":stack_no"),
        (party_prisoner_stack_get_size,    ":stack_size",":source_party",":stack_no"),
        (store_mul, ":number_to_move",":stack_size","$pin_number"),
        (val_div, ":number_to_move", 1000),
        (party_remove_prisoners, ":source_party", ":stack_troop", ":number_to_move"),
        (assign, ":number_moved", reg0),
        (party_add_prisoners, ":target_party", ":stack_troop", ":number_moved"),
      (try_end),
      (party_get_num_companion_stacks, ":num_stacks",":source_party"),
      (try_for_range_backwards, ":stack_no", 0, ":num_stacks"),
        (party_stack_get_troop_id,     ":stack_troop",":source_party",":stack_no"),
        (party_stack_get_size,    ":stack_size",":source_party",":stack_no"),
        (store_mul, ":number_to_move",":stack_size","$pin_number"),
        (val_div, ":number_to_move", 1000),
        (party_remove_members, ":source_party", ":stack_troop", ":number_to_move"),
        (assign, ":number_moved", reg0),
        (party_add_members, ":target_party", ":stack_troop", ":number_moved"),
      (try_end),
  ]),
  
  
  # script_count_parties_of_faction_and_party_type:
  # counts number of active parties with a template and faction.
  # Input: arg1 = faction_no, arg2 = party_type
  # Output: reg0 = count
  
  ("count_parties_of_faction_and_party_type",
    [
      (store_script_param_1, ":faction_no"),
      (store_script_param_2, ":party_type"),
      (assign, reg0, 0),
      (try_for_parties, ":party_no"),
        (party_is_active, ":party_no"),
        (party_get_slot, ":cur_party_type", ":party_no", slot_party_type),
        (store_faction_of_party, ":cur_faction", ":party_no"),
        (eq, ":cur_party_type", ":party_type"),
        (eq, ":cur_faction", ":faction_no"),
        (val_add, reg0, 1),
      (try_end),
  ]),
  
# script_faction_calculate_strength
# Input: arg1 = faction_no
# Output: reg0 = strength
  ("faction_recalculate_strength",
   [
      (store_script_param_1, ":faction_no"),
      (assign, ":num_armies", 0),
      (assign, ":num_castles", 0),
      (assign, ":num_towns", 0),
      (try_for_range, ":troop_no", kingdom_heroes_begin, kingdom_heroes_end),
        (store_troop_faction, ":hero_faction_no", ":troop_no"),
        (eq, ":hero_faction_no", ":faction_no"),
        (troop_get_slot, ":hero_party", ":troop_no", slot_troop_leaded_party),
        (ge, ":hero_party", 0),
        (call_script, "script_party_count_fit_regulars", ":hero_party"),
        (assign, ":party_size", reg0),
        (call_script, "script_party_get_ideal_size", "$pout_party"),
        (assign, ":ideal_size", reg0),
        (val_mul, ":ideal_size", 60),
        (val_div, ":ideal_size", 100),
        (gt, ":party_size", ":ideal_size"),
        (val_add, ":num_armies", 1),
      (try_end),

      (try_for_range, ":center_no", centers_begin, centers_end),
        (store_faction_of_party, ":center_faction", ":center_no"),
        (eq, ":center_faction", ":faction_no"),
        (try_begin),
          (party_slot_eq, ":center_no", slot_party_type, spt_castle),
          (val_add, ":num_castles", 1),
        (else_try),
          (party_slot_eq, ":center_no", slot_party_type, spt_town),
          (val_add, ":num_towns", 1),
        (try_end),
      (try_end),

      (faction_set_slot, ":faction_no", slot_faction_num_armies, ":num_armies"),
      (faction_set_slot, ":faction_no", slot_faction_num_castles, ":num_castles"),
      (faction_set_slot, ":faction_no", slot_faction_num_towns, ":num_towns"),

    ]),  
  
  #script_select_random_town:
  # This script selects a random town in range [towns_begin, towns_end)
  # INPUTS:
  # none
  
  #OUTPUT:
  # reg0: id of the selected random town
##  ("select_random_town",
##    [
##      (assign, ":num_towns", towns_end),
##      (val_sub,":num_towns", towns_begin),
##      (store_random, ":random_town", ":num_towns"),
##      (val_add,":random_town", towns_begin),
##      (assign, reg0, ":random_town"),
##  ]),
  
#  ("select_random_spawn_point",
#    [
#      (assign, reg(20), spawn_points_end),
#      (val_sub,reg(20), spawn_points_begin),
#      (store_random, reg(21), reg(20)),
#      (val_add,reg(21), spawn_points_begin),
#      (assign, "$pout_town", reg(21)),
# ]),
  
##  #script_cf_select_random_town_with_faction:
##  # This script selects a random town in range [towns_begin, towns_end)
##  # such that faction of the town is equal to given_faction
##  # INPUT:
##  # arg1 = faction_no
##  
##  #OUTPUT:
##  # This script may return false if there is no matching town.
##  # reg0 = town_no
##  ("cf_select_random_town_with_faction",
##    [
##      (store_script_param_1, ":faction_no"),
##      (assign, ":result", -1),
##      # First count num matching spawn points
##      (assign, ":no_towns", 0),
##      (try_for_range,":cur_town", towns_begin, towns_end),
##        (store_faction_of_party, ":cur_faction", ":cur_town"),
##        (eq, ":cur_faction", ":faction_no"),
##        (val_add, ":no_towns", 1),
##      (try_end),
##      (gt, ":no_towns", 0), #Fail if there are no towns
##      (store_random_in_range, ":random_town", 0, ":no_towns"),
##      (assign, ":no_towns", 0),
##      (try_for_range,":cur_town", towns_begin, towns_end),
##        (eq, ":result", -1),
##        (store_faction_of_party, ":cur_faction", ":cur_town"),
##        (eq, ":cur_faction", ":faction_no"),
##        (val_add, ":no_towns", 1),
##        (gt, ":no_towns", ":random_town"),
##        (assign, ":result", ":cur_town"),
##      (try_end),
##      (assign, reg0, ":result"),
##  ]),
  
  
  #script_cf_select_random_center_with_faction:
  # This script selects a random center in range [centers_begin, centers_end)
  # such that faction of the town is equal to given_faction
  # INPUT:
  # arg1 = faction_no
  
  #OUTPUT:
  # This script may return false if there is no matching town.
  # reg0 = town_no (Can fail)
  ("cf_select_random_center_with_faction",
    [
      (store_script_param_1, ":faction_no"),
      (assign, ":result", -1),
      # First count num matching spawn points
      (assign, ":no_centers", 0),
      (try_for_range,":cur_center", walled_centers_begin, walled_centers_end),
        (store_faction_of_party, ":cur_faction", ":cur_center"),
        (eq, ":cur_faction", ":faction_no"),
        (val_add, ":no_centers", 1),
      (try_end),
      (gt, ":no_centers", 0), #Fail if there are no centers
      (store_random_in_range, ":random_center", 0, ":no_centers"),
      (assign, ":no_centers", 0),
      (try_for_range,":cur_center", walled_centers_begin, walled_centers_end),
        (eq, ":result", -1),
        (store_faction_of_party, ":cur_faction", ":cur_center"),
        (eq, ":cur_faction", ":faction_no"),
        (val_add, ":no_centers", 1),
        (gt, ":no_centers", ":random_center"),
        (assign, ":result", ":cur_center"),
      (try_end),
      (assign, reg0, ":result"),
  ]),
  
  #script_cf_select_random_town_at_peace_with_faction:
  # This script selects a random town in range [towns_begin, towns_end)
  # such that faction of the town is friendly to given_faction
  # INPUT:
  # arg1 = faction_no
  
  #OUTPUT:
  # This script may return false if there is no matching town.
  # reg0 = town_no
  ("cf_select_random_town_at_peace_with_faction",
    [
      (store_script_param_1, ":faction_no"),
      (assign, ":result", -1),
      # First count num matching towns
      (assign, ":no_towns", 0),
      (try_for_range,":cur_town", towns_begin, towns_end),
        (store_faction_of_party, ":cur_faction", ":cur_town"),
        (store_relation,":reln", ":cur_faction", ":faction_no"),
        (ge, ":reln", 0),
        (val_add, ":no_towns", 1),
      (try_end),
      (gt, ":no_towns", 0), #Fail if there are no towns
      (store_random_in_range, ":random_town", 0, ":no_towns"),
      (assign, ":no_towns", 0),
      (try_for_range,":cur_town", towns_begin, towns_end),
        (eq, ":result", -1),
        (store_faction_of_party, ":cur_faction", ":cur_town"),
        (store_relation,":reln", ":cur_faction", ":faction_no"),
        (ge, ":reln", 0),
        (val_add, ":no_towns", 1),
        (gt, ":no_towns", ":random_town"),
        (assign, ":result", ":cur_town"),
      (try_end),
      (assign, reg0, ":result"),
  ]),
  
  
  ##  ("cf_select_faction_spawn_point",
  ##    [
  ##      # First count num matching spawn points
  ##      (assign, reg(24), 0),
  ##      (try_for_range,reg(25), spawn_points_begin, spawn_points_end),
  ##        (store_faction_of_party, reg(23), reg(25)),
  ##        (eq, reg(23), "$pin_faction"),
  ##        (val_add, reg(24), 1),
  ##      (end_try,0),
  ##      # reg4 now holds num towns of this faction.
  ##      (gt, reg(24), 0), #Fail if there are no towns
  ##      (store_random, reg(26), reg(24)),
  ##
  ##      (assign, reg(24), 0), # reg24 = num points of this faction.
  ##      (try_for_range,reg(25), spawn_points_begin, spawn_points_end),
  ##        (store_faction_of_party, reg(23), reg(25)),
  ##        (eq, reg(23), "$pin_faction"),
  ##        (try_begin,0),
  ##          (eq, reg(24), reg(26)),
  ##          (assign, "$pout_town", reg(25)), # result is this town
  ##        (end_try,0),
  ##        (val_add, reg(24), 1),
  ##      (end_try,0),
  ##  ]),
  
  
  #script_spawn_party_at_random_town:
  # This script selects a random town in range [towns_begin, towns_end)
  # such that faction of the town is equal to given_faction
  # and spawns a new party there.
  # INPUT:
  # $pin_faction: given_faction
  # $pin_party_template: given_party_template
  
  #OUTPUT:
  # This script may return false if party can not be spawned.
  # $pout_party: id of the spawned party
  ##  ("spawn_party_at_random_town",
  ##    [
  ##      (call_script,"script_select_random_spawn_point"),
  ##      (set_spawn_radius,1),
  ##      (spawn_around_party,"$pout_town","$pin_party_template"),
  ##      (assign, "$pout_party", reg(0)),
  ##  ]),
  
  #script_cf_spawn_party_at_faction_town:
  # This script selects a random town in range [towns_begin, towns_end)
  # such that faction of the town is equal to given_faction
  # and spawns a new party there.
  # INPUT:
  # $pin_faction: given_faction
  # $pin_party_template: given_party_template
  
  #OUTPUT:
  # This script may return false if party can not be spawned.
  # $pout_party: id of the spawned party
  ##  ("cf_spawn_party_at_faction_town",
  ##    [
  ##      (call_script,"script_cf_select_faction_spawn_point"),
  ##      (set_spawn_radius,1),
  ##      (spawn_around_party,"$pout_town","$pin_party_template"),
  ##      (assign, "$pout_party", reg(0)),
  ##  ]),
  
  #script_spawn_party_at_random_town_if_below_limit:
  # This script checks if number of parties
  # of specified template is less than limit,
  # If so, it selects a random town in range [towns_begin, towns_end)
  # and spawns a new party there.
  # INPUT:
  # $pin_party_template: given_party_template
  # $pin_limit: limit value
  
  #OUTPUT:
  # $pout_party: id of the spawned party
  # $pout_town: id of the selected faction town
  # Note:
  # This script may return false if number of parties
  # of specified template is greater or equal to limit,
  # or if party can not be spawned.
##  ("cf_spawn_party_at_random_town_if_below_limit",
##    [
##      (store_num_parties_of_template, reg(22), "$pin_party_template"),
##      (lt,reg(22),"$pin_limit"), #check if we are below limit.
##      (call_script,"script_select_random_spawn_point"),
##      (set_spawn_radius,1),
##      (spawn_around_party,"$pout_town","$pin_party_template"),
##      (assign, "$pout_party", reg(0)),
##  ]),
  
  ##  #script_spawn_party_at_faction_town_if_below_limit:
  ##  # This script checks if number of parties
  ##  # of specified template is less than limit,
  ##  # If so, it selects a random town in range [towns_begin, towns_end)
  ##  # such that faction of the town is equal to given_faction
  ##  # and spawns a new party there.
  ##  # INPUT:
  ##  # $pin_faction: given_faction
  ##  # $pin_party_template: given_party_template
  ##  # $pin_limit: limit value
  ##
  ##  #OUTPUT:
  ##  # $pout_party: id of the spawned party
  ##  # $pout_town: id of the selected faction town
  ##  # Note:
  ##  # This script may return false if number of parties
  ##  # of specified template is greater or equal to limit,
  ##  # or if party can not be spawned.
  ##  ("cf_spawn_party_at_faction_town_if_below_limit",
  ##    [
  ##      (store_num_parties_of_template, reg(22), "$pin_party_template"),
  ##      (lt,reg(22),"$pin_limit"), #check if we are below limit.
  ##      (call_script,"script_cf_select_faction_spawn_point"),
  ##      (set_spawn_radius,1),
  ##      (spawn_around_party,"$pout_town","$pin_party_template"),
  ##      (assign, "$pout_party", reg(0)),
  ##  ]),
  
  # script_shuffle_scene_slots:
  # Shuffles a range of slots of a given troop.
  # Used for exploiting a troop as an array.
  # Input: $pin_troop, arg1 = slot_begin, arg2 = slot_end
  ("shuffle_troop_slots",
    [
      (store_script_param_1, ":slots_begin"),
      (store_script_param_2, ":slots_end"),
      (try_for_range, ":cur_slot_no", ":slots_begin", ":slots_end"),
        (store_random_in_range, ":random_slot_no", ":slots_begin", ":slots_end"), #reg(58) = random slot. Now exchange slots reg(57) and reg(58)
        (troop_get_slot, ":cur_slot_value", "$pin_troop", ":cur_slot_no"), #temporarily store the value in slot reg(57) in reg(59)
        (troop_get_slot, ":random_slot_value", "$pin_troop", ":random_slot_no"), #temporarily store the value in slot reg(58) in reg(60)
        (troop_set_slot, "$pin_troop", ":cur_slot_no", ":random_slot_value"), # Now exchange the two...
        (troop_set_slot, "$pin_troop", ":random_slot_no", ":cur_slot_value"),
      (try_end),
  ]),
  
  
##  # script_get_random_kingdom_quest
##  # Input: arg1 = troop_no (of the lord in conversation), arg2 = min_importance (of the quest)
##  # Output: reg0 = quest_no (the slots of the quest will be filled after calling this script)
##  ("get_random_kingdom_quest",
##    [
##      (store_script_param_1, ":giver_troop"),
##      
##      (store_character_level, ":player_level", "trp_player"),
##      (store_troop_faction, ":giver_faction_no", ":giver_troop"),
##      
##      (troop_get_slot, ":giver_party_no", ":giver_troop", slot_troop_leaded_party),
##      (assign, ":giver_center_no", -1),
##      (try_begin),
##        (ge, ":giver_party_no", 0),
##        (party_get_attached_to, ":giver_center_no", ":giver_party_no"),
##      (try_end),
##      
##      (try_begin),
##        (troop_slot_eq, ":giver_troop", slot_troop_occupation, slto_kingdom_hero),
##        (try_begin),
##          (ge, "$g_talk_troop_faction_relation", 0),
##          (assign, ":quests_begin", lord_quests_begin),
##          (assign, ":quests_end", lord_quests_end),
##        (else_try),
##          (assign, ":quests_begin", enemy_lord_quests_begin),
##          (assign, ":quests_end", enemy_lord_quests_end),
##        (try_end),
##      (else_try),
##        (assign, ":quests_begin", lady_quests_begin),
##        (assign, ":quests_end", lady_quests_end),
##      (try_end),
##      
##      (assign, ":result", -1),
##      (try_for_range, ":unused", 0, 20), #Repeat trial twenty times
##        (eq, ":result", -1),
##        (assign, ":quest_target_troop", -1),
##        (assign, ":quest_target_center", -1),
##        (assign, ":quest_target_faction", -1),
##        (assign, ":quest_object_troop", -1),
##        (assign, ":quest_target_troop_is_prisoner", -1),
##        (assign, ":quest_object_center", -1),
##        (assign, ":quest_target_party", -1),
##        (assign, ":quest_target_party_template", -1),
##        (assign, ":quest_target_amount", -1),
##        (assign, ":quest_importance", 1),
##        (assign, ":quest_xp_reward", 0),
##        (assign, ":quest_gold_reward", 0),
##
##        (store_random_in_range,":quest_no",":quests_begin",":quests_end"),
##        (assign, ":quest_no", "qst_incriminate_loyal_commander"),#CHEAT!
##        (neg|check_quest_active,":quest_no"),
##        (try_begin),
##          (eq, ":quest_no", "qst_rescue_lord_by_replace"),
##          # Lady quests
##          (try_begin),
##            (is_between, ":player_level", 5, 25),
##            (troop_get_slot, ":cur_target_troop", ":giver_troop", slot_troop_father),
##            (try_begin),
##              (eq, ":cur_target_troop", 0),
##              (troop_get_slot, ":cur_target_troop", ":giver_troop", slot_troop_spouse),
##            (try_end),
##            (troop_slot_eq, ":cur_target_troop", slot_troop_is_prisoner, 1),#Skip if the lady's father/husband is not in prison
##            (call_script, "script_search_troop_prisoner_of_party", ":cur_target_troop"),
##            (assign, ":cur_target_center", reg0),
##            (is_between, ":cur_target_center", towns_begin, towns_end),#Skip if he is not in a town
##      
##            (assign, ":quest_target_center", ":cur_target_center"),
##            (assign, ":quest_target_troop", ":cur_target_troop"),
##            (assign, ":quest_importance", 1),
##            (assign, ":quest_xp_reward", 10),
##            (assign, ":quest_gold_reward", 10),
##            (assign, ":result", ":quest_no"),
##          (try_end),
##        (else_try),
##          (eq, ":quest_no", "qst_deliver_message_to_prisoner_lord"),
##          (try_begin),
##            (is_between, ":player_level", 5, 25),
##            (troop_get_slot, ":cur_target_troop", ":giver_troop", slot_troop_father),
##            (try_begin),
##              (eq, ":cur_target_troop", 0),
##              (troop_get_slot, ":cur_target_troop", ":giver_troop", slot_troop_spouse),
##            (try_end),
##            (troop_slot_eq, ":cur_target_troop", slot_troop_is_prisoner, 1),#Skip if the lady's father/husband is not in prison
##            (call_script, "script_search_troop_prisoner_of_party", ":cur_target_troop"),
##            (assign, ":cur_target_center", reg0),
##            (is_between, ":cur_target_center", towns_begin, towns_end),#Skip if he is not in a town
##      
##            (assign, ":quest_target_center", ":cur_target_center"),
##            (assign, ":quest_target_troop", ":cur_target_troop"),
##            (assign, ":quest_importance", 1),
##            (assign, ":quest_xp_reward", 10),
##            (assign, ":quest_gold_reward", 10),
##            (assign, ":result", ":quest_no"),
##          (try_end),
##        (else_try),
##          (eq, ":quest_no", "qst_duel_for_lady"),
##          (try_begin),
##            (ge, ":player_level", 10),
##            (call_script, "script_cf_troop_get_random_enemy_troop_with_occupation", ":giver_troop", slto_kingdom_hero),#Can fail
##            (assign, ":cur_target_troop", reg0),
##            (call_script, "script_get_troop_attached_party", ":cur_target_troop"),
##            (is_between, reg0, towns_begin, towns_end),#Skip if troop is not at a town
##
##            (assign, ":quest_object_center", reg0),
##            (assign, ":quest_target_troop", ":cur_target_troop"),
##            (assign, ":quest_importance", 1),
##            (assign, ":quest_xp_reward", 10),
##            (assign, ":quest_gold_reward", 10),
##            (assign, ":result", ":quest_no"),
##          (try_end),
##          # Enemy Lord Quests
##        (else_try),
##          (eq, ":quest_no", "qst_lend_surgeon"),
##          (try_begin),
##            (eq, "$g_defending_against_siege", 0),#Skip if the center is under siege (because of resting)
##            (assign, ":max_surgery_level", 0),
##            (assign, ":best_surgeon", -1),
##            (party_get_num_companion_stacks, ":num_stacks","p_main_party"),
##            (try_for_range, ":i_stack", 1, ":num_stacks"),
##              (party_stack_get_troop_id, ":stack_troop","p_main_party",":i_stack"),
##              (troop_is_hero, ":stack_troop"),
##              (store_skill_level, ":cur_surgery_skill", skl_surgery, ":stack_troop"),
##              (gt, ":cur_surgery_skill", ":max_surgery_level"),
##              (assign, ":max_surgery_level", ":cur_surgery_skill"),
##              (assign, ":best_surgeon", ":stack_troop"),
##            (try_end),
##            
##            (store_character_level, ":cur_level", "trp_player"),
##            (assign, ":required_skill", 5),
##            (val_div, ":cur_level", 10),
##            (val_add, ":required_skill", ":cur_level"),
##            (ge, ":max_surgery_level", ":required_skill"), #Skip if party skill level is less than the required value
##            
##            (assign, ":quest_object_troop", ":best_surgeon"),
##            (assign, ":quest_importance", 1),
##            (assign, ":quest_xp_reward", 10),
##            (assign, ":quest_gold_reward", 10),
##            (assign, ":result", ":quest_no"),
##          (try_end),
##          # Lord Quests
##        (else_try),
##          (eq, ":quest_no", "qst_deliver_message"),
##          (try_begin),
##            (lt, ":player_level", 20),
##            (call_script, "script_cf_get_random_lord_in_a_center_with_faction", ":giver_faction_no"),#Can fail
##            (assign, ":cur_target_troop", reg0),
##            (neq, ":cur_target_troop", ":giver_troop"),#Skip himself
##            (call_script, "script_get_troop_attached_party", ":cur_target_troop"),
##            (assign, ":cur_target_center", reg0),#cur_target_center will definitely be a valid center
##            (neq,":giver_center_no", ":cur_target_center"),#Skip current center
##
##            (assign, ":quest_target_center", ":cur_target_center"),
##            (assign, ":quest_target_troop", ":cur_target_troop"),
##            (assign, ":quest_xp_reward", 30),
##            (assign, ":quest_gold_reward", 40),
##            (assign, ":result", ":quest_no"),
##          (try_end),
##        (else_try),
##          (eq, ":quest_no", "qst_escort_lady"),
##          (try_begin),
##            (ge, ":player_level", 10),
##            (troop_get_slot, ":cur_object_troop", ":giver_troop", slot_troop_daughter),
##            (store_random_in_range, ":random_no", 0, 2),
##            (try_begin),
##              (this_or_next|eq,  ":cur_object_troop", 0),
##              (eq, ":random_no", 0),
##              (troop_get_slot, ":cur_object_troop_2", ":giver_troop", slot_troop_spouse),
##              (gt, ":cur_object_troop_2", 0),
##              (assign, ":cur_object_troop", ":cur_object_troop_2"),
##            (try_end),
##            (gt, ":cur_object_troop", 0),#Skip lords without a lady
##            (troop_get_type, ":cur_troop_gender", ":cur_object_troop"),
##            (eq, ":cur_troop_gender", 1),#Skip if it is not female
##            (gt, ":giver_center_no", 0),#Skip if lord is outside the center
##            (troop_slot_eq, ":cur_object_troop", slot_troop_cur_center, ":giver_center_no"),#Skip if the lady is not at the same center
##            (call_script, "script_cf_select_random_town_with_faction", ":giver_faction_no"),#Can fail
##            (assign, ":cur_target_center", reg0),
##            (neq, ":cur_target_center", ":giver_center_no"),
##            (hero_can_join),#Skip if player has no available slots
##
##            (assign, ":quest_object_troop", ":cur_object_troop"),
##            (assign, ":quest_target_center", ":cur_target_center"),
##            (assign, ":quest_importance", 1),
##            (assign, ":quest_xp_reward", 150),
##            (assign, ":quest_gold_reward", 100),
##            (assign, ":result", ":quest_no"),
##          (try_end),
##        (else_try),
##          (eq, ":quest_no", "qst_hunt_down_raiders"),
##          (try_begin),
##            (gt, ":player_level", 10),
##            (faction_slot_eq, ":giver_faction_no", slot_faction_leader, ":giver_troop"),
##            (call_script, "script_cf_select_random_town_with_faction", ":giver_faction_no"),#Can fail
##            (assign, ":cur_object_center", reg0),
##            (neq, ":cur_object_center", ":giver_center_no"),#Skip current center
##            (call_script, "script_get_random_enemy_center", ":giver_party_no"),
##            (assign, ":cur_target_center", reg0),
##            (ge, ":cur_target_center", 0),
##            (store_faction_of_party, ":cur_target_faction", ":cur_target_center"),
##            (is_between,  ":cur_target_faction", kingdoms_begin, kingdoms_end),
##
##            (assign, ":quest_object_center", ":cur_object_center"),
##            (assign, ":quest_target_center", ":cur_target_center"),
##            (assign, ":quest_importance", 1),
##            (assign, ":quest_xp_reward", 1500),
##            (assign, ":quest_gold_reward", 1000),
##            (assign, ":result", ":quest_no"),
##          (try_end),
##        (else_try),
##          (eq, ":quest_no", "qst_bring_back_deserters"),
##          (try_begin),
##            (gt, ":player_level", 5),
##            (faction_get_slot, ":cur_target_party_template", ":giver_faction_no", slot_faction_deserter_party_template),
##            (faction_get_slot, ":cur_target_troop", ":giver_faction_no", slot_faction_deserter_troop),
##            (gt, ":cur_target_party_template", 0),#Skip factions with no deserter party templates
##            (store_num_parties_of_template, ":num_deserters", ":cur_target_party_template"),
##            (ge, ":num_deserters", 2),#Skip if there are less than 2 active deserter parties
##
##            (assign, ":quest_target_troop", ":cur_target_troop"),
##            (assign, ":quest_target_party_template", ":cur_target_party_template"),
##            (assign, ":quest_target_amount", 5),
##            (assign, ":quest_importance", 1),
##            (assign, ":quest_xp_reward", 500),
##            (assign, ":quest_gold_reward", 300),
##            (assign, ":result", ":quest_no"),
##          (try_end),
##        (else_try),
##          (eq, ":quest_no", "qst_deliver_supply_to_center_under_siege"),
##          (try_begin),
##            (gt, ":player_level", 10),
##            (gt, ":giver_center_no", 0),#Skip if lord is outside the center
##            (call_script, "script_cf_get_random_siege_location_with_faction", ":giver_faction_no"),#Can fail
##            (assign, ":quest_target_center", reg0),
##            (assign, ":quest_target_amount", 10),
##            (assign, ":quest_importance", 1),
##            (assign, ":quest_xp_reward", 500),
##            (assign, ":quest_gold_reward", 300),
##            (assign, ":result", ":quest_no"),
##          (try_end),
##        (else_try),
##          (eq, ":quest_no", "qst_rescue_lady_under_siege"),
##          (try_begin),
##            (gt, ":player_level", 15),
##            (troop_get_slot, ":cur_object_troop", ":giver_troop", slot_troop_daughter),
##            (store_random_in_range, ":random_no", 0, 2),
##            (try_begin),
##              (this_or_next|eq,  ":cur_object_troop", 0),
##              (eq, ":random_no", 0),
##              (troop_get_slot, ":cur_object_troop_2", ":giver_troop", slot_troop_spouse),
##              (gt, ":cur_object_troop_2", 0),
##              (assign, ":cur_object_troop", ":cur_object_troop_2"),
##            (try_end),
##            (gt, ":cur_object_troop", 0),#Skip lords without a lady
##            (troop_get_type, ":cur_troop_gender", ":cur_object_troop"),
##            (eq, ":cur_troop_gender", 1),#Skip if lady is not female
##            (troop_get_slot, ":cur_target_center", ":cur_object_troop", slot_troop_cur_center),
##            (is_between, ":cur_target_center", centers_begin, centers_end),#Skip if she is not in a center
##            (neq,":giver_center_no", ":cur_target_center"),#Skip current center
##            (call_script, "script_cf_get_random_siege_location_with_faction", ":giver_faction_no"),#Can fail
##            (assign, ":cur_target_center", reg0),
##            (troop_set_slot, ":cur_object_troop", slot_troop_cur_center, ":cur_target_center"),#Move lady to the siege location
##            (assign, ":quest_object_troop", ":cur_object_troop"),
##            (assign, ":quest_target_center", ":cur_target_center"),
##            (assign, ":quest_target_troop", ":giver_troop"),
##            (assign, ":quest_importance", 1),
##            (assign, ":quest_xp_reward", 200),
##            (assign, ":quest_gold_reward", 750),
##            (assign, ":result", ":quest_no"),
##          (try_end),
##        (else_try),
##          (eq, ":quest_no", "qst_deliver_message_to_lover"),
##          (try_begin),
##            (is_between, ":player_level", 5, 30),
##            (troop_get_slot, ":cur_target_troop", ":giver_troop", slot_troop_lover),
##            (gt, ":cur_target_troop", 0),#Skip lords without a lover
##            (troop_get_slot, ":cur_target_center", ":cur_target_troop", slot_troop_cur_center),
##            (is_between, ":cur_target_center", centers_begin, centers_end),#Skip if she is not in a center
##            (neq,":giver_center_no", ":cur_target_center"),#Skip current center
##            (assign, ":quest_target_troop", ":cur_target_troop"),
##            (assign, ":quest_target_center", ":cur_target_center"),
##            (assign, ":result", ":quest_no"),
##          (try_end),
##        (else_try),
##          (eq, ":quest_no", "qst_bring_reinforcements_to_siege"),
##          (try_begin),
##            (gt, ":player_level", 10),
##            (call_script, "script_cf_get_random_siege_location_with_attacker_faction", ":giver_faction_no"),#Can fail
##            (assign, ":cur_target_center", reg0),
##            (store_random_in_range, ":random_no", 5, 11),
##            (troops_can_join, ":random_no"),#Skip if the player doesn't have enough room
##            (call_script, "script_cf_get_number_of_random_troops_from_party", ":giver_party_no", ":random_no"),#Can fail
##            (assign, ":cur_object_troop", reg0),
##            (party_get_battle_opponent, ":cur_target_party", ":cur_target_center"),
##            (party_get_num_companion_stacks, ":num_stacks", ":cur_target_party"),
##            (gt, ":num_stacks", 0),#Skip if the besieger party has no troops
##            (party_stack_get_troop_id, ":cur_target_troop", ":cur_target_party", 0),
##            (troop_is_hero, ":cur_target_troop"),#Skip if the besieger party has no heroes
##            (neq, ":cur_target_troop", ":giver_troop"),#Skip if the quest giver is the same troop
##            (assign, ":quest_target_troop", ":cur_target_troop"),
##            (assign, ":quest_object_troop", ":cur_object_troop"),
##            (assign, ":quest_target_party", ":cur_target_party"),
##            (assign, ":quest_target_center", ":cur_target_center"),
##            (assign, ":quest_target_amount", ":random_no"),
##            (assign, ":quest_importance", 1),
##            (assign, ":quest_xp_reward", 400),
##            (assign, ":quest_gold_reward", 200),
##            (assign, ":result", ":quest_no"),
##          (try_end),
##        (else_try),
##          (eq, ":quest_no", "qst_deliver_message_to_enemy_lord"),
##          (try_begin),
##            (is_between, ":player_level", 5,25),
##            (call_script, "script_cf_get_random_enemy_lord_in_a_center", ":giver_faction_no"),#Can fail
##            (assign, ":cur_target_troop", reg0),
##            (call_script, "script_get_troop_attached_party", ":cur_target_troop"),
##            (assign, ":quest_target_center", reg0),#quest_target_center will definitely be a valid center
##            (assign, ":quest_target_troop", ":cur_target_troop"),
##            (assign, ":quest_importance", 1),
##            (assign, ":quest_xp_reward", 200),
##            (assign, ":quest_gold_reward", 0),
##            (assign, ":result", ":quest_no"),
##          (try_end),
##        (else_try),
##          (eq, ":quest_no", "qst_bring_prisoners_to_enemy"),
##          (try_begin),
##            (gt, ":player_level", 10),
##            (is_between, ":giver_center_no", centers_begin, centers_end),#Skip if the quest giver is not at a center
##            (store_random_in_range, ":random_no", 5, 11),
##            (troops_can_join_as_prisoner, ":random_no"),#Skip if the player doesn't have enough room
##            (call_script, "script_get_random_enemy_town", ":giver_center_no"),
##            (assign, ":cur_target_center", reg0),
##            (ge, ":cur_target_center", 0),#Skip if there are no enemy towns
##            (store_faction_of_party, ":cur_target_faction", ":cur_target_center"),
##            (faction_get_slot, ":cur_object_troop", ":cur_target_faction", slot_faction_tier_5_troop),
##            (assign, ":quest_target_center", ":cur_target_center"),
##            (assign, ":quest_object_troop", ":cur_object_troop"),
##            (assign, ":quest_target_amount", ":random_no"),
##            (assign, ":quest_importance", 1),
##            (assign, ":quest_xp_reward", 300),
##            (assign, ":quest_gold_reward", 200),
##            (assign, ":result", ":quest_no"),
##          (try_end),
##        (else_try),
##          (eq, ":quest_no", "qst_raise_troops"),
##          (try_begin),
##            (store_random_in_range, ":random_no", 3, 7),
##            (store_character_level, ":cur_level"),
##            (try_begin),
##              (ge, ":cur_level", 15),
##              (faction_get_slot, ":cur_target_troop", ":giver_faction_no", slot_faction_tier_5_troop),
##              (assign, ":quest_gold_reward", 300),
##            (else_try),
##              (faction_get_slot, ":cur_target_troop", ":giver_faction_no", slot_faction_tier_4_troop),
##              (assign, ":quest_gold_reward", 150),
##            (try_end),
##            (gt, ":cur_target_troop", 0),
##
##            (assign, ":quest_target_troop", ":cur_target_troop"),
##            (assign, ":quest_target_amount", ":random_no"),
##            (assign, ":quest_importance", 1),
##      
##            (val_mul, ":quest_gold_reward", ":quest_target_amount"),
##            (assign, ":quest_xp_reward", ":quest_gold_reward"),
##            (val_mul, ":quest_xp_reward", 3),
##            (val_div, ":quest_xp_reward", 4),
##            (assign, ":result", ":quest_no"),
##          (try_end),
##        (else_try),
##          (eq, ":quest_no", "qst_capture_messenger"),
##          (try_begin),
##            (call_script, "script_cf_faction_get_random_enemy_faction", ":giver_faction_no"),
##            (assign, ":cur_target_faction", reg0),
##            (faction_get_slot, ":cur_target_troop", ":cur_target_faction", slot_faction_messenger_troop),
##            (gt, ":cur_target_troop", 0),#Checking the validiy of cur_target_troop
##            (store_num_parties_destroyed_by_player, ":quest_target_amount", "pt_messenger_party"),
##
##            (assign, ":quest_target_troop", ":cur_target_troop"),
##            (assign, ":quest_target_party_template", ":cur_target_party_template"),
##            (assign, ":quest_importance", 1),
##            (assign, ":quest_xp_reward", 700),
##            (assign, ":quest_gold_reward", 400),
##            (assign, ":result", ":quest_no"),
##          (try_end),
##        (else_try),
##          (eq, ":quest_no", "qst_kill_local_merchant"),
##          (try_begin),
##            (gt, ":player_level", 5),
##            (assign, ":quest_target_troop", "trp_local_merchant"),
##            (assign, ":quest_target_center", ":giver_center_no"),
##            (assign, ":quest_importance", 1),
##            (assign, ":quest_xp_reward", 300),
##            (assign, ":quest_gold_reward", 1000),
##            (assign, ":result", ":quest_no"),
##          (try_end),
##        (else_try),
##          (eq, ":quest_no", "qst_bring_back_runaway_serfs"),
##          (try_begin),
##            (gt, ":player_level", 10),
##            (eq, "$g_defending_against_siege", 0),#Skip if the center is under siege (because of resting)
##            (call_script, "script_cf_select_random_town_with_faction", ":giver_faction_no"),
##            (assign, ":cur_target_center", reg0),
##            (neq, ":cur_target_center", ":giver_center_no"),#Skip current center
##            (party_slot_eq, ":giver_center_no", slot_town_lord, ":giver_troop"),#Skip if quest giver is not owner of the center
##
##            (assign, ":quest_target_party_template", "pt_runaway_serfs"),
##            (assign, ":quest_object_center", ":giver_center_no"),
##            (assign, ":quest_target_center", ":cur_target_center"),
##            (assign, ":quest_importance", 1),
##            (assign, ":quest_xp_reward", 200),
##            (assign, ":quest_gold_reward", 150),
##            (assign, ":result", ":quest_no"),
##            (assign, "$qst_bring_back_runaway_serfs_num_parties_returned", 0),
##            (assign, "$qst_bring_back_runaway_serfs_num_parties_fleed", 0),
##          (try_end),
##        (else_try),
##          (eq, ":quest_no", "qst_follow_spy"),
##          (try_begin),
##            (eq, 1,0), #TODO: disable this for now
##            (gt, ":player_level", 10),
##            (eq, "$g_defending_against_siege", 0),#Skip if the center is under siege (because of resting)
##            (gt, ":giver_party_no", 0),#Skip if the quest giver doesn't have a party
##            (gt, ":giver_center_no", 0),#skip if the quest giver is not in a center
##            (party_slot_eq, "$g_encountered_party", slot_party_type, spt_town), #skip if we are not in a town.
##            (party_get_position, pos2, "p_main_party"),
##            (assign, ":min_distance", 99999),
##            (try_for_range, ":unused_2", 0, 10),
##              (call_script, "script_get_random_enemy_center", ":giver_party_no"),
##              (assign, ":random_object_center", reg0),
##              (gt, ":random_object_center", 0),#Skip if there are no enemy centers
##              (party_get_position, pos3, ":random_object_center"),
##              (map_get_random_position_around_position, pos4, pos3, 6),
##              (get_distance_between_positions, ":cur_distance", pos2, pos4),
##              (lt, ":cur_distance", ":min_distance"),
##              (assign, ":min_distance", ":cur_distance"),
##              (assign, ":cur_object_center", ":random_object_center"),
##              (copy_position, pos63, pos4),#Do not change pos63 until quest is accepted
##            (try_end),
##            (gt, ":cur_object_center", 0),#Skip if there are no enemy centers
##
##            (assign, ":quest_object_center", ":cur_object_center"),
##            (assign, ":quest_importance", 1),
##            (assign, ":quest_xp_reward", 10),
##            (assign, ":quest_gold_reward", 10),
##            (assign, ":result", ":quest_no"),
##            (assign, "$qst_follow_spy_run_away", 0),
##            (assign, "$qst_follow_spy_meeting_state", 0),
##            (assign, "$qst_follow_spy_meeting_counter", 0),
##            (assign, "$qst_follow_spy_spy_back_in_town", 0),
##            (assign, "$qst_follow_spy_partner_back_in_town", 0),
##          (try_end),
##        (else_try),
##          (eq, ":quest_no", "qst_capture_enemy_hero"),
##          (try_begin),
##            (ge, ":player_level", 15),
##            (call_script, "script_cf_faction_get_random_enemy_faction", ":giver_faction_no"),#Can fail
##
##            (assign, ":quest_target_faction", reg0),
##            (assign, ":quest_importance", 1),
##            (assign, ":quest_xp_reward", 2000),
##            (assign, ":quest_gold_reward", 2000),
##            (assign, ":result", ":quest_no"),
##          (try_end),
##        (else_try),
##          (eq, ":quest_no", "qst_lend_companion"),
##          (try_begin),
##            (assign, ":total_heroes", 0),
##            (party_get_num_companion_stacks, ":num_stacks","p_main_party"),
##            (try_for_range, ":i_stack", 0, ":num_stacks"),
##              (party_stack_get_troop_id, ":stack_troop","p_main_party",":i_stack"),
##              (troop_is_hero, ":stack_troop"),
##              (neq, ":stack_troop", "trp_player"),
##              (store_character_level, ":stack_level", ":stack_troop"),
##              (ge, ":stack_level", 15),
##              (assign, ":is_quest_hero", 0),
##              (try_for_range, ":i_quest", 0, all_quests_end),
##                (check_quest_active, ":i_quest"),
##                (this_or_next|quest_slot_eq, ":i_quest", slot_quest_target_troop, ":stack_troop"),
##                (quest_slot_eq, ":i_quest", slot_quest_object_troop, ":stack_troop"),
##                (assign, ":is_quest_hero", 1),
##              (try_end),
##              (eq, ":is_quest_hero", 0),
##              (val_add, ":total_heroes", 1),
##            (try_end),
##            (gt, ":total_heroes", 0),#Skip if party has no eligible heroes
##            (store_random_in_range, ":random_hero", 0, ":total_heroes"),
##            (assign, ":total_heroes", 0),
##            (assign, ":cur_target_troop", -1),
##            (try_for_range, ":i_stack", 0, ":num_stacks"),
##              (eq, ":cur_target_troop", -1),
##              (party_stack_get_troop_id, ":stack_troop","p_main_party",":i_stack"),
##              (troop_is_hero, ":stack_troop"),
##              (neq, ":stack_troop", "trp_player"),
##              (store_character_level, ":stack_level", ":stack_troop"),
##              (ge, ":stack_level", 15),
##              (assign, ":is_quest_hero", 0),
##              (try_for_range, ":i_quest", 0, all_quests_end),
##                (check_quest_active, ":i_quest"),
##                (this_or_next|quest_slot_eq, ":i_quest", slot_quest_target_troop, ":stack_troop"),
##                (quest_slot_eq, ":i_quest", slot_quest_object_troop, ":stack_troop"),
##                (assign, ":is_quest_hero", 1),
##              (try_end),
##              (eq, ":is_quest_hero", 0),
##              (val_add, ":total_heroes", 1),
##              (gt, ":total_heroes", ":random_hero"),
##              (assign, ":cur_target_troop", ":stack_troop"),
##            (try_end),
##            (assign, ":quest_target_troop", ":cur_target_troop"),
##            (store_current_day, ":quest_target_amount"),
##            (val_add, ":quest_target_amount", 8),
##
##            (assign, ":quest_importance", 1),
##            (assign, ":quest_xp_reward", 300),
##            (assign, ":quest_gold_reward", 400),
##            (assign, ":result", ":quest_no"),
##          (try_end),
##        (else_try),
##          (eq, ":quest_no", "qst_capture_conspirators"),
##          (try_begin),
##            (eq, 1,0), #TODO: disable this for now
##            (ge, ":player_level", 10),
##            (is_between, ":giver_center_no", towns_begin, towns_end),#Skip if quest giver's center is not a town
##            (party_slot_eq, ":giver_center_no", slot_town_lord, ":giver_troop"),#Skip if the current center is not ruled by the quest giver
##            (call_script, "script_cf_get_random_kingdom_hero", ":giver_faction_no"),#Can fail
##
##            (assign, ":quest_target_troop", reg0),
##            (assign, ":quest_target_center", ":giver_center_no"),
##            (assign, ":quest_importance", 1),
##            (assign, ":quest_xp_reward", 10),
##            (assign, ":quest_gold_reward", 10),
##            (assign, ":result", ":quest_no"),
##            (store_character_level, ":cur_level"),
##            (val_div, ":cur_level", 5),
##            (val_max, ":cur_level", 3),
##            (store_add, ":max_parties", 4, ":cur_level"),
##            (store_random_in_range, "$qst_capture_conspirators_num_parties_to_spawn", 4, ":max_parties"),
##            (assign, "$qst_capture_conspirators_num_troops_to_capture", 0),
##            (assign, "$qst_capture_conspirators_num_parties_spawned", 0),
##            (assign, "$qst_capture_conspirators_leave_meeting_counter", 0),
##            (assign, "$qst_capture_conspirators_party_1", 0),
##            (assign, "$qst_capture_conspirators_party_2", 0),
##            (assign, "$qst_capture_conspirators_party_3", 0),
##            (assign, "$qst_capture_conspirators_party_4", 0),
##            (assign, "$qst_capture_conspirators_party_5", 0),
##            (assign, "$qst_capture_conspirators_party_6", 0),
##            (assign, "$qst_capture_conspirators_party_7", 0),
##          (try_end),
##        (else_try),
##          (eq, ":quest_no", "qst_defend_nobles_against_peasants"),
##          (try_begin),
##            (eq, 1,0), #TODO: disable this for now
##            (ge, ":player_level", 10),
##            (is_between, ":giver_center_no", towns_begin, towns_end),#Skip if quest giver's center is not a town
##            (party_slot_eq, ":giver_center_no", slot_town_lord, ":giver_troop"),#Skip if the current center is not ruled by the quest giver
##
##            (assign, ":quest_target_center", ":giver_center_no"),
##            (assign, ":quest_importance", 1),
##            (assign, ":quest_xp_reward", 10),
##            (assign, ":quest_gold_reward", 10),
##            (assign, ":result", ":quest_no"),
##            (store_character_level, ":cur_level"),
##            (val_div, ":cur_level", 5),
##            (val_max, ":cur_level", 4),
##            (store_add, ":max_parties", 4, ":cur_level"),
##            (store_random_in_range, "$qst_defend_nobles_against_peasants_num_peasant_parties_to_spawn", 4, ":cur_level"),
##            (store_random_in_range, "$qst_defend_nobles_against_peasants_num_noble_parties_to_spawn", 4, ":cur_level"),
##            (assign, "$qst_defend_nobles_against_peasants_num_nobles_to_save", 0),
##            (assign, "$qst_defend_nobles_against_peasants_num_nobles_saved", 0),
##            (assign, "$qst_defend_nobles_against_peasants_peasant_party_1", 0),
##            (assign, "$qst_defend_nobles_against_peasants_peasant_party_2", 0),
##            (assign, "$qst_defend_nobles_against_peasants_peasant_party_3", 0),
##            (assign, "$qst_defend_nobles_against_peasants_peasant_party_4", 0),
##            (assign, "$qst_defend_nobles_against_peasants_peasant_party_5", 0),
##            (assign, "$qst_defend_nobles_against_peasants_peasant_party_6", 0),
##            (assign, "$qst_defend_nobles_against_peasants_peasant_party_7", 0),
##            (assign, "$qst_defend_nobles_against_peasants_peasant_party_8", 0),
##            (assign, "$qst_defend_nobles_against_peasants_noble_party_1", 0),
##            (assign, "$qst_defend_nobles_against_peasants_noble_party_2", 0),
##            (assign, "$qst_defend_nobles_against_peasants_noble_party_3", 0),
##            (assign, "$qst_defend_nobles_against_peasants_noble_party_4", 0),
##            (assign, "$qst_defend_nobles_against_peasants_noble_party_5", 0),
##            (assign, "$qst_defend_nobles_against_peasants_noble_party_6", 0),
##            (assign, "$qst_defend_nobles_against_peasants_noble_party_7", 0),
##            (assign, "$qst_defend_nobles_against_peasants_noble_party_8", 0),
##          (try_end),
##        (else_try),
##          (eq, ":quest_no", "qst_incriminate_loyal_commander"),
##          (try_begin),
##            (ge, ":player_level", 10),
##            (faction_slot_eq, ":giver_faction_no", slot_faction_leader, ":giver_troop"),
##            (assign, ":try_times", 5),
##            (try_for_range, ":unused", 0, ":try_times"),
##              (call_script, "script_cf_faction_get_random_enemy_faction", ":giver_faction_no"),#Can fail
##              (assign, ":cur_target_faction", reg0),
##              (faction_get_slot, ":quest_target_troop",":cur_target_faction",slot_faction_leader),
##              (assign, ":num_centerless_heroes", 0),
##              (assign, ":quest_object_troop", -1),
##              (try_for_range, ":cur_kingdom_hero", kingdom_heroes_begin, kingdom_heroes_end),
##                (eq, ":quest_object_troop", -1),
##                (neq, ":quest_target_troop", ":cur_kingdom_hero"),
##                (troop_slot_eq, ":cur_kingdom_hero", slot_troop_occupation, slto_kingdom_hero),
##                (store_troop_faction, ":cur_kingdom_hero_faction", ":cur_kingdom_hero"),
##                (eq, ":cur_target_faction", ":cur_kingdom_hero_faction"),
##                (call_script, "script_get_number_of_hero_centers", ":cur_kingdom_hero"),
##                (eq, reg0, 0),
##                (val_add, ":num_centerless_heroes", 1),
##                (eq, ":num_centerless_heroes", 2),
##                (assign, ":quest_object_troop", ":cur_kingdom_hero"),
##                (assign, ":try_times", -1),#Exit the second loop
##              (try_end),
##            (try_end),
##
##            (call_script, "script_get_troop_attached_party", ":quest_target_troop"),
##            (is_between, reg0, towns_begin, towns_end),
##            (party_slot_eq, reg0, slot_town_lord, ":quest_target_troop"),
##            (assign, ":quest_target_center", reg0),
##
##            (assign, "$incriminate_quest_sacrificed_troop", 0),
##
##            (party_get_num_companion_stacks, ":num_stacks","p_main_party"),
##            (try_for_range, ":i_stack", 1, ":num_stacks"),
##              (eq ,"$incriminate_quest_sacrificed_troop", 0),
##              (party_stack_get_troop_id, ":stack_troop","p_main_party",":i_stack"),
##              (neg|troop_is_hero, ":stack_troop"),
##              (store_character_level, ":stack_troop_level", ":stack_troop"),
##              (ge, ":stack_troop_level", 25),
##              (assign, "$incriminate_quest_sacrificed_troop", ":stack_troop"),
##            (try_end),
##            (gt, "$incriminate_quest_sacrificed_troop", 0),
##
##            (assign, ":quest_importance", 1),
##            (assign, ":quest_xp_reward", 700),
##            (assign, ":quest_gold_reward", 1000),
##            (assign, ":result", ":quest_no"),
##          (try_end),
##        (else_try),
##          (eq, ":quest_no", "qst_capture_prisoners"),
##          (try_begin),
##            (call_script, "script_cf_faction_get_random_enemy_faction", ":giver_faction_no"),#Can fail
##            (assign, ":cur_target_faction", reg0),
##            (store_add, ":max_tier_no", slot_faction_tier_5_troop, 1),
##            (store_random_in_range, ":random_tier_no", slot_faction_tier_1_troop, ":max_tier_no"),
##            (faction_get_slot, ":cur_target_troop", ":cur_target_faction", ":random_tier_no"),
##            (gt, ":cur_target_troop", 0),
##            (store_random_in_range, ":quest_target_amount", 3, 7),
##            (assign, ":quest_target_troop", ":cur_target_troop"),
##            (assign, ":quest_target_faction", ":cur_target_faction"),
##            (assign, ":quest_importance", 1),
##            (store_character_level, ":quest_gold_reward", ":cur_target_troop"),
##            (val_add, ":quest_gold_reward", 5),
##            (val_mul, ":quest_gold_reward", ":quest_gold_reward"),
##            (val_div, ":quest_gold_reward", 5),
##            (val_mul, ":quest_gold_reward", ":quest_target_amount"),
##            (assign, ":quest_xp_reward", ":quest_gold_reward"),
##            (assign, ":result", ":quest_no"),
##          (try_end),
##        (try_end),
##      (try_end),
##      (try_begin),
##        (neq, ":result", -1),
##        
##        (try_begin),
##          (ge, ":quest_target_center", 0),
##          (store_faction_of_party, ":quest_target_faction", ":quest_target_center"),
##        (try_end),
##        (try_begin),
##          (ge, ":quest_target_troop", 0),
##          (troop_get_slot, ":quest_target_troop_is_prisoner", ":quest_target_troop", slot_troop_is_prisoner),
##        (try_end),
##        
##        (quest_set_slot, ":result", slot_quest_target_troop, ":quest_target_troop"),
##        (quest_set_slot, ":result", slot_quest_target_center, ":quest_target_center"),
##        (quest_set_slot, ":result", slot_quest_object_troop, ":quest_object_troop"),
##        (quest_set_slot, ":result", slot_quest_target_troop_is_prisoner, ":quest_target_troop_is_prisoner"),
##        (quest_set_slot, ":result", slot_quest_target_faction, ":quest_target_faction"),
##        (quest_set_slot, ":result", slot_quest_object_center, ":quest_object_center"),
##        (quest_set_slot, ":result", slot_quest_target_party, ":quest_target_party"),
##        (quest_set_slot, ":result", slot_quest_target_party_template, ":quest_target_party_template"),
##        (quest_set_slot, ":result", slot_quest_target_amount, ":quest_target_amount"),
##        (quest_set_slot, ":result", slot_quest_importance, ":quest_importance"),
##        (quest_set_slot, ":result", slot_quest_xp_reward, ":quest_xp_reward"),
##        (quest_set_slot, ":result", slot_quest_gold_reward, ":quest_gold_reward"),
##        (quest_set_slot, ":result", slot_quest_current_state, 0),
##        (quest_set_slot, ":result", slot_quest_giver_troop, ":giver_troop"),
##        (quest_set_slot, ":result", slot_quest_giver_center, ":giver_center_no"),
##      (try_end),
##      
##      (assign, reg0, ":result"),
##  ]),
##  
  
  
  # script_cf_faction_get_random_enemy_faction
  # Input: arg1 = faction_no
  # Output: reg0 = faction_no (Can fail)
  ("cf_faction_get_random_enemy_faction",
    [
      (store_script_param_1, ":faction_no"),
      
      (assign, ":result", -1),
      (assign, ":count_factions", 0),
      (try_for_range, ":cur_faction", kingdoms_begin, kingdoms_end),
        (store_relation, ":cur_relation", ":faction_no", ":cur_faction"),
        (le, ":cur_relation", -1),
        (val_add, ":count_factions", 1),
      (try_end),
      (store_random_in_range,":random_faction",0,":count_factions"),
      (assign, ":count_factions", 0),
      (try_for_range, ":cur_faction", kingdoms_begin, kingdoms_end),
        (eq, ":result", -1),
        (store_relation, ":cur_relation", ":faction_no", ":cur_faction"),
        (le, ":cur_relation", -1),
        (val_add, ":count_factions", 1),
        (gt, ":count_factions", ":random_faction"),
        (assign, ":result", ":cur_faction"),
      (try_end),
      
      (neq, ":result", -1),
      (assign, reg0, ":result"),
  ]),
  
  
  # script_cf_troop_get_random_enemy_troop_with_occupation
  # Input: arg1 = troop_no,
  # Output: reg0 = enemy_troop_no (Can fail)
  ("cf_troop_get_random_enemy_troop_with_occupation",
    [
      (store_script_param_1, ":troop_no"),
      (store_script_param_2, ":occupation"),
      
      (assign, ":result", -1),
      (assign, ":count_enemies", 0),
      (try_for_range, ":cur_slot", slot_troop_enemies_begin, slot_troop_enemies_end),
        (troop_get_slot, ":cur_enemy", ":troop_no", ":cur_slot"),
        (gt, ":cur_enemy", 0),
        (troop_slot_eq, ":cur_enemy", slot_troop_occupation, ":occupation"),
        (val_add, ":count_enemies", 1),
      (try_end),
      (store_random_in_range,":random_enemy",0,":count_enemies"),
      (assign, ":count_enemies", 0),
      (try_for_range, ":cur_slot", slot_troop_enemies_begin, slot_troop_enemies_end),
        (eq, ":result", -1),
        (troop_get_slot, ":cur_enemy", ":troop_no", ":cur_slot"),
        (gt, ":cur_enemy", 0),
        (troop_slot_eq, ":cur_enemy", slot_troop_occupation, ":occupation"),
        (val_add, ":count_enemies", 1),
        (gt, ":count_enemies", ":random_enemy"),
        (assign, ":result", ":cur_enemy"),
      (try_end),
      
      (neq, ":result", -1),
      (assign, reg0, ":result"),
  ]),
  
  
##  # script_cf_troop_get_random_enemy_troop_as_a_town_lord
##  # Input: arg1 = troop_no
##  # Output: reg0 = enemy_troop_no (Can fail)
##  ("cf_troop_get_random_enemy_troop_as_a_town_lord",
##    [
##      (store_script_param_1, ":troop_no"),
##      
##      (assign, ":result", -1),
##      (assign, ":count_enemies", 0),
##      (try_for_range, ":cur_slot", slot_troop_enemies_begin, slot_troop_enemies_end),
##        (troop_get_slot, ":cur_enemy", ":troop_no", ":cur_slot"),
##        (gt, ":cur_enemy", 0),
##        (troop_slot_eq, ":cur_enemy", slot_troop_occupation, slto_kingdom_hero),
##        (call_script, "script_get_number_of_hero_centers", ":cur_enemy"),
##        (gt, reg0, 0),
##        (val_add, ":count_enemies", 1),
##      (try_end),
##      (store_random_in_range,":random_enemy",0,":count_enemies"),
##      (assign, ":count_enemies", 0),
##      (try_for_range, ":cur_slot", slot_troop_enemies_begin, slot_troop_enemies_end),
##        (eq, ":result", -1),
##        (troop_get_slot, ":cur_enemy", ":troop_no", ":cur_slot"),
##        (gt, ":cur_enemy", 0),
##        (troop_slot_eq, ":cur_enemy", slot_troop_occupation, slto_kingdom_hero),
##        (call_script, "script_get_number_of_hero_centers", ":cur_enemy"),
##        (gt, reg0, 0),
##        (val_add, ":count_enemies", 1),
##        (gt, ":count_enemies", ":random_enemy"),
##        (assign, ":result", ":cur_enemy"),
##      (try_end),
##      (neq, ":result", -1),
##      (assign, reg0, ":result"),
##  ]),
  
  
  ##  # script_cf_get_random_enemy_with_valid_slot
  ##  # Input: arg1 = faction_no, arg2 = slot_no
  ##  # Output: reg0 = faction_no (Can fail)
  ##  ("cf_get_random_enemy_with_valid_slot",
  ##    [
  ##      (store_script_param_1, ":faction_no"),
  ##      (store_script_param_2, ":slot_no"),
  ##
  ##      (assign, ":result", -1),
  ##      (assign, ":count_factions", 0),
  ##      (try_for_range, ":cur_faction", kingdoms_begin, kingdoms_end),
  ##        (store_relation, ":cur_relation", ":faction_no", ":cur_faction"),
  ##        (le, ":cur_relation", -10),
  ##        (faction_get_slot, ":cur_value", ":cur_faction", ":slot_no"),
  ##        (gt, ":cur_value", 0),#Checking validity
  ##        (val_add, ":count_factions", 1),
  ##      (try_end),
  ##      (store_random_in_range,":random_faction",0,":count_factions"),
  ##      (assign, ":count_factions", 0),
  ##      (try_for_range, ":cur_faction", kingdoms_begin, kingdoms_end),
  ##        (eq, ":result", -1),
  ##        (store_relation, ":cur_relation", ":faction_no", ":cur_faction"),
  ##        (le, ":cur_relation", -10),
  ##        (faction_get_slot, ":cur_value", ":cur_faction", ":slot_no"),
  ##        (gt, ":cur_value", 0),#Checking validity
  ##        (val_add, ":count_factions", 1),
  ##        (gt, ":count_factions", ":random_faction"),
  ##        (assign, ":result", ":cur_faction"),
  ##      (try_end),
  ##
  ##      (neq, ":result", -1),
  ##      (assign, reg0, ":result"),
  ##  ]),
  
  
##  # script_cf_get_random_kingdom_hero
##  # Input: arg1 = faction_no
##  # Output: reg0 = troop_no (Can fail)
##  ("cf_get_random_kingdom_hero",
##    [
##      (store_script_param_1, ":faction_no"),
##      (assign, ":count_heroes", 0),
##      (try_for_range, ":center_no", centers_begin, centers_end),
##        (store_faction_of_party, ":cur_faction", ":center_no"),
##        (eq, ":cur_faction", ":faction_no"),
##        (party_get_slot, ":cur_lord", ":center_no", slot_town_lord),
##        (is_between, ":cur_lord", heroes_begin, heroes_end),
##        (val_add, ":count_heroes", 1),
##      (try_end),
##      (store_random_in_range, ":random_hero", 0, ":count_heroes"),
##      (assign, ":result", -1),
##      (assign, ":count_heroes", 0),
##      (try_for_range, ":center_no", centers_begin, centers_end),
##        (eq, ":result", -1),
##        (store_faction_of_party, ":cur_faction", ":center_no"),
##        (eq, ":cur_faction", ":faction_no"),
##        (party_get_slot, ":cur_lord", ":center_no", slot_town_lord),
##        (is_between, ":cur_lord", heroes_begin, heroes_end),
##        (val_add, ":count_heroes", 1),
##        (lt, ":random_hero", ":count_heroes"),
##        (assign, ":result", ":cur_lord"),
##      (try_end),
##      (neq, ":result", -1),
##      (assign, reg0, ":result"),
##  ]),
  
  
  # script_cf_get_random_kingdom_hero_as_lover
  # Input: arg1 = troop_no (of the lady)
  # Output: reg0 = troop_no (of the hero) (Can fail)
  ("cf_get_random_kingdom_hero_as_lover",
    [
      #      (store_script_param_1, ":cur_lady"),
      
      
      #      (troop_get_slot, ":cur_father", ":cur_lady", slot_troop_father),
      #      (troop_get_slot, ":fathers_rank", ":cur_father", slot_troop_kingdom_rank),
      (assign, ":result", -1),
      (assign, ":count_heroes", 0),
      (try_for_range, ":troop_no", kingdom_heroes_begin, kingdom_heroes_end),
        (troop_slot_eq, ":troop_no", slot_troop_lover, 0),
        (troop_slot_eq, ":troop_no", slot_troop_spouse, 0),
        #        (troop_get_slot, ":cur_rank", ":troop_no", slot_troop_kingdom_rank),
        #        (lt, ":cur_rank", ":fathers_rank"), # Only heroes with lower ranks may be the lovers of the daughters
        (val_add, ":count_heroes", 1),
      (try_end),
      (store_random_in_range,":random_hero",0,":count_heroes"),
      (assign, ":count_heroes", 0),
      (try_for_range, ":troop_no", kingdom_heroes_begin, kingdom_heroes_end),
        (eq, ":result", -1),
        (troop_slot_eq, ":troop_no", slot_troop_lover, 0),
        (troop_slot_eq, ":troop_no", slot_troop_spouse, 0),
        #        (troop_get_slot, ":cur_rank", ":troop_no", slot_troop_kingdom_rank),
        #        (lt, ":cur_rank", ":fathers_rank"), # Only heroes with lower ranks may be the lovers of the daughters
        (val_add, ":count_heroes", 1),
        (gt, ":count_heroes", ":random_hero"),
        (assign, ":result", ":troop_no"),
      (try_end),
      (neq, ":result", -1),
      (assign, reg0, ":result"),
  ]),
  
  
##  # script_cf_get_random_siege_location_with_faction
##  # Input: arg1 = faction_no
##  # Output: reg0 = center_no, Can Fail!
##  ("cf_get_random_siege_location_with_faction",
##    [
##      (store_script_param_1, ":faction_no"),
##      (assign, ":result", -1),
##      (assign, ":count_sieges", 0),
##      (try_for_range, ":center_no", walled_centers_begin, walled_centers_end),
##        (party_get_battle_opponent, ":besieger_party", ":center_no"),
##        (gt, ":besieger_party", 0),
##        (store_faction_of_party, ":cur_faction_no", ":center_no"),
##        (eq, ":cur_faction_no", ":faction_no"),
##        (val_add, ":count_sieges", 1),
##      (try_end),
##      (store_random_in_range,":random_center",0,":count_sieges"),
##      (assign, ":count_sieges", 0),
##      (try_for_range, ":center_no", walled_centers_begin, walled_centers_end),
##        (eq, ":result", -1),
##        (party_get_battle_opponent, ":besieger_party", ":center_no"),
##        (gt, ":besieger_party", 0),
##        (store_faction_of_party, ":cur_faction_no", ":center_no"),
##        (eq, ":cur_faction_no", ":faction_no"),
##        (val_add, ":count_sieges", 1),
##        (gt, ":count_sieges", ":random_center"),
##        (assign, ":result", ":center_no"),
##      (try_end),
##      (neq, ":result", -1),
##      (assign, reg0, ":result"),
##  ]),
  
##  # script_cf_get_random_siege_location_with_attacker_faction
##  # Input: arg1 = faction_no
##  # Output: reg0 = center_no, Can Fail!
##  ("cf_get_random_siege_location_with_attacker_faction",
##    [
##      (store_script_param_1, ":faction_no"),
##      (assign, ":result", -1),
##      (assign, ":count_sieges", 0),
##      (try_for_range, ":center_no", walled_centers_begin, walled_centers_end),
##        (party_get_battle_opponent, ":besieger_party", ":center_no"),
##        (gt, ":besieger_party", 0),
##        (store_faction_of_party, ":cur_faction_no", ":besieger_party"),
##        (eq, ":cur_faction_no", ":faction_no"),
##        (val_add, ":count_sieges", 1),
##      (try_end),
##      (store_random_in_range,":random_center",0,":count_sieges"),
##      (assign, ":count_sieges", 0),
##      (try_for_range, ":center_no", walled_centers_begin, walled_centers_end),
##        (eq, ":result", -1),
##        (party_get_battle_opponent, ":besieger_party", ":center_no"),
##        (gt, ":besieger_party", 0),
##        (store_faction_of_party, ":cur_faction_no", ":besieger_party"),
##        (eq, ":cur_faction_no", ":faction_no"),
##        (val_add, ":count_sieges", 1),
##        (gt, ":count_sieges", ":random_center"),
##        (assign, ":result", ":center_no"),
##      (try_end),
##      (neq, ":result", -1),
##      (assign, reg0, ":result"),
##  ]),
  
  
  
##  # script_cf_get_number_of_random_troops_from_party
##  # Input: arg1 = party_no, arg2 = number of troops to remove
##  # Output: reg0 = troop_no, Can fail if there are no slots having the required number of units!
##  ("cf_get_number_of_random_troops_from_party",
##    [
##      (store_script_param_1, ":party_no"),
##      (store_script_param_2, ":no_to_remove"),
##      
##      (assign, ":result", -1),
##      (assign, ":count_stacks", 0),
##      
##      (party_get_num_companion_stacks, ":num_stacks",":party_no"),
##      (try_for_range, ":i_stack", 0, ":num_stacks"),
##        (party_stack_get_size, ":stack_size",":party_no",":i_stack"),
##        (party_stack_get_num_wounded, ":num_wounded",":party_no",":i_stack"),
##        (val_sub, ":stack_size", ":num_wounded"),
##        (ge, ":stack_size", ":no_to_remove"),
##        (party_stack_get_troop_id, ":stack_troop",":party_no",":i_stack"),
##        (neg|troop_is_hero, ":stack_troop"),
##        (val_add, ":count_stacks", 1),
##      (try_end),
##      (store_random_in_range,":random_stack",0,":count_stacks"),
##      (assign, ":count_stacks", 0),
##      (try_for_range, ":i_stack", 0, ":num_stacks"),
##        (eq, ":result", -1),
##        (party_stack_get_size, ":stack_size",":party_no",":i_stack"),
##        (party_stack_get_num_wounded, ":num_wounded",":party_no",":i_stack"),
##        (val_sub, ":stack_size", ":num_wounded"),
##        (ge, ":stack_size", ":no_to_remove"),
##        (party_stack_get_troop_id, ":stack_troop",":party_no",":i_stack"),
##        (neg|troop_is_hero, ":stack_troop"),
##        (val_add, ":count_stacks", 1),
##        (gt, ":count_stacks", ":random_stack"),
##        (assign, ":result", ":stack_troop"),
##      (try_end),
##      
##      (neq, ":result", -1),
##      (assign, reg0, ":result"),
##  ]),
  
  
  
  
##  # script_cf_get_random_lord_in_a_center_with_faction
##  # Input: arg1 = faction_no
##  # Output: reg0 = troop_no, Can Fail!
##  ("cf_get_random_lord_in_a_center_with_faction",
##    [
##      (store_script_param_1, ":faction_no"),
##      (assign, ":result", -1),
##      (assign, ":count_lords", 0),
##      (try_for_range, ":lord_no", heroes_begin, heroes_end),
##        (store_troop_faction, ":lord_faction_no", ":lord_no"),
##        (eq, ":faction_no", ":lord_faction_no"),
##        (troop_slot_eq, ":lord_no", slot_troop_occupation, slto_kingdom_hero),
##        (troop_slot_eq, ":lord_no", slot_troop_is_prisoner, 0),
##        (troop_get_slot, ":lord_party", ":lord_no", slot_troop_leaded_party),
##        (ge, ":lord_party", 0),
##        (party_get_attached_to, ":lord_attachment", ":lord_party"),
##        (is_between, ":lord_attachment", centers_begin, centers_end), #is troop in a center?
##        (val_add, ":count_lords", 1),
##      (try_end),
##      (store_random_in_range, ":random_lord", 0, ":count_lords"),
##      (assign, ":count_lords", 0),
##      (try_for_range, ":lord_no", heroes_begin, heroes_end),
##        (eq, ":result", -1),
##        (store_troop_faction, ":lord_faction_no", ":lord_no"),
##        (eq, ":faction_no", ":lord_faction_no"),
##        (troop_slot_eq, ":lord_no", slot_troop_occupation, slto_kingdom_hero),
##        (troop_slot_eq, ":lord_no", slot_troop_is_prisoner, 0),
##        (troop_get_slot, ":lord_party", ":lord_no", slot_troop_leaded_party),
##        (ge, ":lord_party", 0),
##        (party_get_attached_to, ":lord_attachment", ":lord_party"),
##        (is_between, ":lord_attachment", centers_begin, centers_end), #is troop in a center?
##        (val_add, ":count_lords", 1),
##        (lt, ":random_lord", ":count_lords"),
##        (assign, ":result", ":lord_no"),
##      (try_end),
##      (neq, ":result", -1),
##      (assign, reg0, ":result"),
##  ]),
  
  
##  # script_cf_get_random_enemy_lord_in_a_center
##  # Input: arg1 = faction_no
##  # Output: reg0 = troop_no, Can Fail!
##  ("cf_get_random_enemy_lord_in_a_center",
##    [
##      (store_script_param_1, ":faction_no"),
##      (assign, ":result", -1),
##      (assign, ":count_lords", 0),
##      (try_for_range, ":lord_no", heroes_begin, heroes_end),
##        (store_troop_faction, ":lord_faction_no", ":lord_no"),
##        (store_relation, ":lord_relation", ":lord_faction_no", ":faction_no"),
##        (le, ":lord_relation", -10),
##        (troop_slot_eq, ":lord_no", slot_troop_occupation, slto_kingdom_hero),
##        (troop_slot_eq, ":lord_no", slot_troop_is_prisoner, 0),
##        (troop_get_slot, ":lord_party", ":lord_no", slot_troop_leaded_party),
##        (ge, ":lord_party", 0),
##        (party_get_attached_to, ":lord_attachment", ":lord_party"),
##        (is_between, ":lord_attachment", centers_begin, centers_end), #is troop in a center?
##        (val_add, ":count_lords", 1),
##      (try_end),
##      (store_random_in_range, ":random_lord", 0, ":count_lords"),
##      (assign, ":count_lords", 0),
##      (try_for_range, ":lord_no", heroes_begin, heroes_end),
##        (eq, ":result", -1),
##        (store_troop_faction, ":lord_faction_no", ":lord_no"),
##        (store_relation, ":lord_relation", ":lord_faction_no", ":faction_no"),
##        (le, ":lord_relation", -10),
##        (troop_slot_eq, ":lord_no", slot_troop_occupation, slto_kingdom_hero),
##        (troop_slot_eq, ":lord_no", slot_troop_is_prisoner, 0),
##        (troop_get_slot, ":lord_party", ":lord_no", slot_troop_leaded_party),
##        (ge, ":lord_party", 0),
##        (party_get_attached_to, ":lord_attachment", ":lord_party"),
##        (is_between, ":lord_attachment", centers_begin, centers_end), #is troop in a center?
##        (val_add, ":count_lords", 1),
##        (lt, ":random_lord", ":count_lords"),
##        (assign, ":result", ":lord_no"),
##      (try_end),
##      (neq, ":result", -1),
##      (assign, reg0, ":result"),
##  ]),
  
  # script_get_closest_walled_center
  # Input: arg1 = party_no
  # Output: reg0 = center_no (closest)
  ("get_closest_walled_center",
    [
      (store_script_param_1, ":party_no"),
      (assign, ":min_distance", 9999999),
      (assign, reg0, -1),
      (try_for_range, ":center_no", walled_centers_begin, walled_centers_end),
        (store_distance_to_party_from_party, ":party_distance", ":party_no", ":center_no"),
        (lt, ":party_distance", ":min_distance"),
        (assign, ":min_distance", ":party_distance"),
        (assign, reg0, ":center_no"),
      (try_end),
  ]),  
  
  # script_get_closest_center
  # Input: arg1 = party_no
  # Output: reg0 = center_no (closest)
  ("get_closest_center",
    [
      (store_script_param_1, ":party_no"),
      (assign, ":min_distance", 9999999),
      (assign, reg0, -1),
      (try_for_range, ":center_no", centers_begin, centers_end),
        (store_distance_to_party_from_party, ":party_distance", ":party_no", ":center_no"),
        (lt, ":party_distance", ":min_distance"),
        (assign, ":min_distance", ":party_distance"),
        (assign, reg0, ":center_no"),
      (try_end),
  ]),
  
  
  # script_get_closest_center_of_faction
  # Input: arg1 = party_no, arg2 = kingdom_no
  # Output: reg0 = center_no (closest)
  ("get_closest_center_of_faction",
    [
      (store_script_param_1, ":party_no"),
      (store_script_param_2, ":kingdom_no"),
      (assign, ":min_distance", 99999),
      (assign, ":result", -1),
      (try_for_range, ":center_no", centers_begin, centers_end),
        (store_faction_of_party, ":faction_no", ":center_no"),
        (eq, ":faction_no", ":kingdom_no"),
        (store_distance_to_party_from_party, ":party_distance", ":party_no", ":center_no"),
        (lt, ":party_distance", ":min_distance"),
        (assign, ":min_distance", ":party_distance"),
        (assign, ":result", ":center_no"),
      (try_end),
      (assign, reg0, ":result"),
  ]),
  
  # script_get_closest_walled_center_of_faction
  # Input: arg1 = party_no, arg2 = kingdom_no
  # Output: reg0 = center_no (closest)
  ("get_closest_walled_center_of_faction",
    [
      (store_script_param_1, ":party_no"),
      (store_script_param_2, ":kingdom_no"),
      (assign, ":min_distance", 99999),
      (assign, ":result", -1),
      (try_for_range, ":center_no", walled_centers_begin, walled_centers_end),
        (store_faction_of_party, ":faction_no", ":center_no"),
        (eq, ":faction_no", ":kingdom_no"),
        (store_distance_to_party_from_party, ":party_distance", ":party_no", ":center_no"),
        (lt, ":party_distance", ":min_distance"),
        (assign, ":min_distance", ":party_distance"),
        (assign, ":result", ":center_no"),
      (try_end),
      (assign, reg0, ":result"),
  ]),
  
  
##  # script_get_closest_town_of_faction
##  # Input: arg1 = party_no, arg2 = kingdom_no
##  # Output: reg0 = center_no (closest)
##  ("get_closest_town_of_faction",
##    [
##      (store_script_param_1, ":party_no"),
##      (store_script_param_2, ":kingdom_no"),
##      (assign, ":min_distance", 9999999),
##      (assign, ":result", -1),
##      (try_for_range, ":center_no", walled_centers_begin, walled_centers_end),
##        (store_faction_of_party, ":faction_no", ":center_no"),
##        (eq, ":faction_no", ":kingdom_no"),
##        (party_slot_eq, ":center_no", slot_party_type, spt_town),
##        (store_distance_to_party_from_party, ":party_distance", ":party_no", ":center_no"),
##        (lt, ":party_distance", ":min_distance"),
##        (assign, ":min_distance", ":party_distance"),
##        (assign, ":result", ":center_no"),
##      (try_end),
##      (assign, reg0, ":result"),
##  ]),

  
  # script_let_nearby_parties_join_current_battle
  # Input: none
  # Output: none
 ("let_nearby_parties_join_current_battle",
    [
      (assign, ":enemy_party_no", "$g_encountered_party"),
      (try_for_parties, ":party_no"),
        (party_get_battle_opponent, ":opponent",":party_no"),
        (lt, ":opponent", 0), #party is not itself involved in a battle
        (party_get_attached_to, ":attached_to",":party_no"),
        (lt, ":attached_to", 0), #party is not attached to another party
        (get_party_ai_behavior, ":behavior", ":party_no"),
        (neq, ":behavior", ai_bhvr_in_town),

        (assign, ":join_distance", 5),
        (try_begin),
          (is_currently_night),
          (assign, ":join_distance", 3),
        (try_end),
      
        (store_distance_to_party_from_party, ":distance", ":party_no", "p_main_party"),
        (lt, ":distance", ":join_distance"),
##
        (party_get_template_id,":template_id",":party_no"),
#        (this_or_next|eq, ":template_id", "pt_kingdom_hero_party"),
        (is_between, ":template_id", s_pt_begin,s_pt_end),
##
        (store_faction_of_party, ":faction_no", ":party_no"),
        (store_faction_of_party, ":enemy_faction", ":enemy_party_no"),
        (store_relation, ":reln_with_player", ":faction_no", "fac_player_faction"),
        (store_relation, ":reln_with_enemy", ":faction_no", ":enemy_faction"),
        (try_begin),
      #TODO: Fix this
          (lt, ":reln_with_player", 0),
          (gt, ":reln_with_enemy", 0),
          (get_party_ai_behavior, ":ai_bhvr", ":party_no"),
          #Weibao
          (try_begin),
             (eq, "$weibao_active", 1),
             (assign, "$weibao_active", 0),#
             (party_get_skill_level, ":i_stratagem_lv", "p_main_party", skl_stratagem),
             (party_get_skill_level, ":e_stratagem_lv", ":party_no", skl_stratagem),
             (store_sub,":stratagem_sub",":i_stratagem_lv",":e_stratagem_lv"),
             (val_mul,":st_sub",5),
             (store_random_in_range,":rp",0,100),
             (val_add,":rp",":st_sub"),
             (try_begin),
               (eq,"$weibao",1),
               (val_add,":rp",5),
             (else_try),
               (eq,"$weibao",2),
               (val_add,":rp",10),
             (try_end),
             (try_begin),
               (gt, ":rp", 60),
               (str_store_party_name, s58, ":party_no"),
               (display_message, "@enemy zhong ji"),
               (assign, ":ai_bhvr", ai_bhvr_avoid_party),
             (try_end),
          (try_end),

          (neq, ":ai_bhvr", ai_bhvr_avoid_party),
          (party_quick_attach_to_current_battle, ":party_no", 1), #attach as enemy
          (str_store_party_name, s1, ":party_no"),
          (display_message, "str_s1_joined_battle_enemy"),
        (else_try),
      #TODO: Fix this
          (gt, ":reln_with_player", 0),
          (lt, ":reln_with_enemy", 0),

          #Weibao enemy
          (assign, ":rp", 0),
          (try_begin),
            (party_stack_get_troop_id, ":leader", ":enemy_party_no", 0),
            (this_or_next|eq, ":leader", "trp_zhugeliang"),
            (this_or_next|eq, ":leader", "trp_pangtong"),
            (this_or_next|eq, ":leader", "trp_caocao"),
            (this_or_next|eq, ":leader", "trp_simayi"),
            (this_or_next|eq, ":leader", "trp_jiaxu"),
            (this_or_next|eq, ":leader", "trp_xunyu"),
            (this_or_next|eq, ":leader", "trp_luxun"),
            (eq, ":leader", "trp_guojia"),
            (party_get_skill_level, ":i_st_lv", ":party_no", skl_stratagem),
#            (store_skill_level,":e_st_lv",skl_stratagem,":leader"),
            (party_get_skill_level, ":e_st_lv", ":enemy_party_no", skl_stratagem),
            (store_sub,":st_sub",":e_st_lv",":i_st_lv"),
            (val_mul,":stratagem_sub",5),
            (store_random_in_range,":rp",0,100),
            (val_add,":rp",":stratagem_sub"),
          (try_end),
          (try_begin),
            (gt, ":rp", 60),
            (str_store_party_name, s58, ":party_no"),
            (str_store_troop_name,s59,":leader"),
            (display_message, "@ally zhong ji"),
          (else_try),
            (try_begin),
              (eq, ":template_id", "pt_kingdom_hero_party"),
              (party_stack_get_troop_id, ":leader", ":party_no", 0),
              (troop_get_slot, ":player_relation", ":leader", slot_troop_player_relation),
              (ge, ":player_relation", 0),
              (party_quick_attach_to_current_battle, ":party_no", 0), #attach as friend
              (str_store_party_name, s1, ":party_no"),
              (display_message, "str_s1_joined_battle_friend"),
            (else_try),
              (party_quick_attach_to_current_battle, ":party_no", 0), #attach as friend
              (str_store_party_name, s1, ":party_no"),
              (display_message, "str_s1_joined_battle_friend"),
            (try_end),
          (try_end),
        (try_end),
      (try_end),
 ]), 
  
  
  # script_party_wound_all_members_aux
  # Input: arg1 = party_no
  ("party_wound_all_members_aux",
    [
      (store_script_param_1, ":party_no"),
      
      (party_get_num_companion_stacks, ":num_stacks",":party_no"),
      (try_for_range, ":i_stack", 0, ":num_stacks"),
        (party_stack_get_troop_id, ":stack_troop",":party_no",":i_stack"),
        (try_begin),
          (neg|troop_is_hero, ":stack_troop"),
          (party_stack_get_size, ":stack_size",":party_no",":i_stack"),
          (party_wound_members, ":party_no", ":stack_troop", ":stack_size"),
        (else_try),
          (troop_set_health, ":stack_troop", 0),
        (try_end),
      (try_end),
      (party_get_num_attached_parties, ":num_attached_parties", ":party_no"),
      (try_for_range, ":attached_party_rank", 0, ":num_attached_parties"),
        (party_get_attached_party_with_rank, ":attached_party", ":party_no", ":attached_party_rank"),
        (call_script, "script_party_wound_all_members_aux", ":attached_party"),
      (try_end),
      
  ]),
  
  
  
  # script_party_wound_all_members
  # Input: arg1 = party_no
  ("party_wound_all_members",
    [
      (store_script_param_1, ":party_no"),
      
      (call_script, "script_party_wound_all_members_aux", ":party_no"),
  ]),
  
  
  
  # script_calculate_battle_advantage
  # Output: reg0 = battle advantage
  ("calculate_battle_advantage",
    [
      (call_script, "script_party_count_fit_for_battle", "p_collective_friends"),
      (assign, ":friend_count", reg(0)),
      
      (party_get_skill_level, ":player_party_tactics",  "p_main_party", skl_tactics),
      (party_get_skill_level, ":ally_party_tactics",  "p_collective_friends", skl_tactics),
      (val_max, ":player_party_tactics", ":ally_party_tactics"),
     
      (call_script, "script_party_count_fit_for_battle", "p_collective_enemy"),
      (assign, ":enemy_count", reg(0)),
      
      (party_get_skill_level, ":enemy_party_tactics",  "p_collective_enemy", skl_tactics),
      
      (val_add, ":friend_count", 1),
      (val_add, ":enemy_count", 1),
      
      (try_begin),
        (ge, ":friend_count", ":enemy_count"),
        (val_mul, ":friend_count", 100),
        (store_div, ":ratio", ":friend_count", ":enemy_count"),
        (store_sub, ":raw_advantage", ":ratio", 100),
      (else_try),
        (val_mul, ":enemy_count", 100),
        (store_div, ":ratio", ":enemy_count", ":friend_count"),
        (store_sub, ":raw_advantage", 100, ":ratio"),
      (try_end),
      
      (val_mul, ":player_party_tactics", 50),
      (val_mul, ":enemy_party_tactics", 50),
      (val_add, ":raw_advantage", ":player_party_tactics"),
      (val_sub, ":raw_advantage", ":enemy_party_tactics"),
      
      (assign, ":raw_mod_advantage", ":raw_advantage"),
      (val_add, ":raw_mod_advantage", 1000000),
      (val_mod, ":raw_mod_advantage", 100),
      (try_begin),
        (ge, ":raw_mod_advantage", 50),
        (assign, ":raw_mod_advantage", 1),
      (else_try),
        (assign, ":raw_mod_advantage", 0),
      (try_end),
      
      (try_begin),
        (lt, ":raw_advantage", 0),
        (val_sub, ":raw_mod_advantage", 1),
      (try_end),
      
      (val_div, ":raw_advantage", 100),
      (val_add, ":raw_advantage", ":raw_mod_advantage"),
      
      (assign, reg0, ":raw_advantage"),
  ]),
  
  
  # script_cf_check_enemies_nearby
  # Input: none
  # Output: none, fails when enemies are nearby
  ("cf_check_enemies_nearby",
    [
      (get_player_agent_no, ":player_agent"),
      (agent_is_alive, ":player_agent"),
      (try_begin),
        (agent_is_defender, ":player_agent"),
        (assign, ":player_defender", 1),
      (else_try),
        (assign, ":player_defender", 0),
      (try_end),
      (agent_get_position, pos1, ":player_agent"),
      (assign, ":result", 0),
      (try_for_agents,":cur_agent"),
        (neq, ":cur_agent", ":player_agent"),
        (agent_is_alive, ":cur_agent"),
        (agent_is_human, ":cur_agent"),
        (try_begin),
          (agent_is_defender, ":cur_agent"),
          (assign, ":agent_defender", 1),
        (else_try),
          (assign, ":agent_defender", 0),
        (try_end),
        (neq, ":player_defender", ":agent_defender"),
        (agent_get_position, pos2, ":cur_agent"),
        (get_distance_between_positions, ":cur_distance", pos1, pos2),
        (le, ":cur_distance", 1500),
        (assign, ":result", 1),
      (try_end),
      (eq, ":result", 0),
  ]),
  
  # script_get_heroes_attached_to_center_aux
  # For internal use only
  ("get_heroes_attached_to_center_aux",
    [
      (store_script_param_1, ":center_no"),
      (store_script_param_2, ":party_no_to_collect_heroes"),
      (party_get_num_companion_stacks, ":num_stacks",":center_no"),
      (try_for_range, ":i_stack", 0, ":num_stacks"),
        (party_stack_get_troop_id, ":stack_troop",":center_no",":i_stack"),
        (troop_is_hero, ":stack_troop"),
        (party_add_members, ":party_no_to_collect_heroes", ":stack_troop", 1),
      (try_end),
      (party_get_num_attached_parties, ":num_attached_parties", ":center_no"),
      (try_for_range, ":attached_party_rank", 0, ":num_attached_parties"),
        (party_get_attached_party_with_rank, ":attached_party", ":center_no", ":attached_party_rank"),
        (call_script, "script_get_heroes_attached_to_center_aux", ":attached_party", ":party_no_to_collect_heroes"),
      (try_end),
  ]),
  
  # script_get_heroes_attached_to_center
  # Input: arg1 = center_no, arg2 = party_no_to_collect_heroes
  # Output: none, adds heroes to the party_no_to_collect_heroes party
  ("get_heroes_attached_to_center",
    [
      (store_script_param_1, ":center_no"),
      (store_script_param_2, ":party_no_to_collect_heroes"),
      (party_clear, ":party_no_to_collect_heroes"),
      (call_script, "script_get_heroes_attached_to_center_aux", ":center_no", ":party_no_to_collect_heroes"),
  ]),
  
  
  # script_get_heroes_attached_to_center_as_prisoner_aux
  # For internal use only
  ("get_heroes_attached_to_center_as_prisoner_aux",
    [
      (store_script_param_1, ":center_no"),
      (store_script_param_2, ":party_no_to_collect_heroes"),
      (party_get_num_prisoner_stacks, ":num_stacks",":center_no"),
      (try_for_range, ":i_stack", 0, ":num_stacks"),
        (party_prisoner_stack_get_troop_id, ":stack_troop",":center_no",":i_stack"),
        (troop_is_hero, ":stack_troop"),
        (party_add_members, ":party_no_to_collect_heroes", ":stack_troop", 1),
      (try_end),
      (party_get_num_attached_parties, ":num_attached_parties", ":center_no"),
      (try_for_range, ":attached_party_rank", 0, ":num_attached_parties"),
        (party_get_attached_party_with_rank, ":attached_party", ":center_no", ":attached_party_rank"),
        (call_script, "script_get_heroes_attached_to_center_as_prisoner_aux", ":attached_party", ":party_no_to_collect_heroes"),
      (try_end),
  ]),
  
  
  # script_get_heroes_attached_to_center_as_prisoner
  # Input: arg1 = center_no, arg2 = party_no_to_collect_heroes
  # Output: none, adds heroes to the party_no_to_collect_heroes party
  ("get_heroes_attached_to_center_as_prisoner",
    [
      (store_script_param_1, ":center_no"),
      (store_script_param_2, ":party_no_to_collect_heroes"),
      (party_clear, ":party_no_to_collect_heroes"),
      (call_script, "script_get_heroes_attached_to_center_as_prisoner_aux", ":center_no", ":party_no_to_collect_heroes"),
  ]),
  
##  
##  # script_cf_get_party_leader
##  # Input: arg1 = party_no
##  # Output: reg0 = troop_no of the leader (Can fail)
##  ("cf_get_party_leader",
##    [
##      (store_script_param_1, ":party_no"),
##      
##      (party_get_num_companion_stacks, ":num_stacks",":party_no"),
##      (gt, ":num_stacks", 0),
##      (party_stack_get_troop_id, ":stack_troop", ":party_no", 0),
##      (troop_is_hero, ":stack_troop"),
##      (assign, reg0, ":stack_troop"),
##  ]),
  
  # script_give_center_to_faction
  # Input: arg1 = center_no, arg2 = faction
  ("give_center_to_faction",
    [
      (store_script_param_1, ":center_no"),
      (store_script_param_2, ":faction_no"),
      (call_script, "script_give_center_to_faction_aux", ":center_no", ":faction_no"),
      (call_script, "script_update_village_market_towns"),
  ]),
  
  # script_give_center_to_faction_aux
  # Input: arg1 = center_no, arg2 = faction
  ("give_center_to_faction_aux",
    [
      (store_script_param_1, ":center_no"),
      (store_script_param_2, ":faction_no"),
      
      (party_set_faction, ":center_no", ":faction_no"),

      (party_set_slot, ":center_no", slot_town_lord, stl_unassigned),

      (try_begin),
        (party_set_banner_icon, ":center_no", 0),#Removing banner
      (try_end),

      (try_for_range, ":other_center", centers_begin, centers_end),
        (party_slot_eq, ":other_center", slot_village_bound_center, ":center_no"),
        (call_script, "script_give_center_to_faction_aux", ":other_center", ":faction_no"),
      (try_end),
  ]),
  

  # script_give_center_to_lord
  # Input: arg1 = center_no, arg2 = lord_troop
  ("give_center_to_lord",
    [
      (store_script_param_1, ":center_no"),
      (store_script_param_2, ":lord_troop_id"),
      

      (party_get_slot, ":old_lord_troop_id", ":center_no", slot_town_lord),
      
      (store_troop_faction, ":lord_troop_faction", ":lord_troop_id"),
      (try_begin),
        (eq, ":lord_troop_id", "trp_player"),
        (gt, "$players_kingdom", 0),
        (party_set_faction, ":center_no", "$players_kingdom"),
      (else_try),
        (party_set_faction, ":center_no", ":lord_troop_faction"),
      (try_end),
      (party_set_slot, ":center_no", slot_town_lord, ":lord_troop_id"),

#      (str_store_party_name_link, s7, ":center_no"),
#      (str_store_troop_name_link, s8, ":lord_troop_id"),
#      (display_log_message, "@{s7} has been given to {s8}."),

      (try_begin),
        (this_or_next|party_slot_eq, ":center_no", slot_party_type, spt_town),
        (party_slot_eq, ":center_no", slot_party_type, spt_castle),
        (troop_get_slot, ":cur_banner", ":lord_troop_id", slot_troop_banner_scene_prop),
        (gt, ":cur_banner", 0),
        (val_sub, ":cur_banner", "spr_banner_a"),
        (val_add, ":cur_banner", "icon_banner_01"),
        (party_set_banner_icon, ":center_no", ":cur_banner"),
      (try_end),

      (try_begin),
        (eq, ":lord_troop_id", "trp_player"),
        (party_get_slot, ":center_relation", ":center_no", slot_center_player_relation),
        (is_between, ":center_relation", -4, 5),
        (call_script, "script_change_player_relation_with_center", ":center_no", 5),
      (try_end),

      (call_script, "script_update_troop_notes", ":lord_troop_id"),
      (call_script, "script_update_center_notes", ":center_no"),
      (call_script, "script_update_faction_notes", ":lord_troop_faction"),
      (try_begin),
        (ge, ":old_lord_troop_id", 0),
        (call_script, "script_update_troop_notes", ":old_lord_troop_id"),
        (store_troop_faction, ":old_lord_troop_faction", ":old_lord_troop_id"),
        (call_script, "script_update_faction_notes", ":old_lord_troop_faction"),
      (try_end),
  ]),
  
##  # script_give_town_to_besiegers
##  # Input: arg1 = center_no, arg2 = besieger_party
##  ("give_town_to_besiegers",
##    [
##      (store_script_param_1, ":center_no"),
##      (store_script_param_2, ":besieger_party"),
##      (store_faction_of_party, ":besieger_faction", ":besieger_party"),
##      
##      (try_begin),
##        (call_script, "script_cf_get_party_leader", ":besieger_party"),
##        (assign, ":new_leader", reg0),
##      (else_try),
##        (call_script, "script_select_kingdom_hero_for_new_center", ":besieger_faction"),
##        (assign, ":new_leader", reg0),
##      (try_end),
##      
##      (call_script, "script_give_center_to_lord", ":center_no", ":new_leader"),
##      
##      (try_for_parties, ":party_no"),
##        (get_party_ai_object, ":object", ":party_no"),
##        (get_party_ai_behavior, ":behavior", ":party_no"),
##        (eq, ":object", ":center_no"),
##        (this_or_next|eq, ":behavior", ai_bhvr_travel_to_party),
##        (eq, ":behavior", ai_bhvr_attack_party),
##        (party_set_ai_behavior, ":party_no", ai_bhvr_hold),
##        (party_set_slot, ":party_no", slot_party_ai_state, spai_undefined),
##        (party_set_flags, ":party_no", pf_default_behavior, 0),
##      (try_end),
##      
##      #Staying at the center for a while
##      (party_set_ai_behavior, ":besieger_party", ai_bhvr_hold),
##      (party_set_slot, ":besieger_party", slot_party_ai_state, spai_undefined),
##      (party_set_flags, ":besieger_party", pf_default_behavior, 0),
##      
##      (faction_get_slot, ":reinforcement_a", ":besieger_faction", slot_faction_reinforcements_a),
##      (faction_get_slot, ":reinforcement_b", ":besieger_faction", slot_faction_reinforcements_b),
##      (party_add_template, ":center_no", ":reinforcement_a"),
##      (party_add_template, ":center_no", ":reinforcement_b"),
##  ]),
##  
  
  # script_get_number_of_hero_centers
  # Input: arg1 = troop_no
  # Output: reg0 = number of centers that are ruled by the hero
  ("get_number_of_hero_centers",
    [
      (store_script_param_1, ":troop_no"),
      (assign, ":result", 0),
      (try_for_range, ":center_no", centers_begin, centers_end),
        (party_slot_eq, ":center_no", slot_town_lord, ":troop_no"),
        (val_add, ":result", 1),
      (try_end),
      (assign, reg0, ":result"),
  ]),
  
  
  ##  # script_cf_get_new_center_leader_chance_for_troop
  ##  # Input: arg1 = troop_no
  ##  # Output: reg0 = chance of the troop to rule a new center
  ##  ("cf_get_new_center_leader_chance_for_troop",
  ##    [
  ##      (store_script_param_1, ":troop_no"),
  ##      (troop_get_slot, ":troop_rank", ":troop_no", slot_troop_kingdom_rank),
  ##      (try_begin),
  ##        (eq, ":troop_rank", 4),
  ##        (assign, ":troop_chance", 1000),
  ##      (else_try),
  ##        (eq, ":troop_rank", 3),
  ##        (assign, ":troop_chance", 800),
  ##      (else_try),
  ##        (eq, ":troop_rank", 2),
  ##        (assign, ":troop_chance", 400),
  ##      (else_try),
  ##        (eq, ":troop_rank", 1),
  ##        (assign, ":troop_chance", 100),
  ##      (else_try),
  ##        (assign, ":troop_chance", 10),
  ##      (try_end),
  ##
  ##      (call_script, "script_get_number_of_hero_centers", ":troop_no"),
  ##      (assign, ":number_of_hero_centers", reg0),
  ##      (try_begin),
  ##        (gt, ":number_of_hero_centers", 0),
  ##        (val_mul, ":number_of_hero_centers", 2),
  ##        (val_mul, ":number_of_hero_centers", ":number_of_hero_centers"),
  ##        (val_div, ":troop_chance", ":number_of_hero_centers"),
  ##      (try_end),
  ##      (assign, reg0, ":troop_chance"),
  ##      (eq, reg0, 0),
  ##      (assign, reg0, 1),
  ##  ]),
  
  
##  # script_select_kingdom_hero_for_new_center
##  # Input: arg1 = faction_no
##  # Output: reg0 = troop_no as the new leader
##  ("select_kingdom_hero_for_new_center",
##    [
##      (store_script_param_1, ":kingdom"),
##      
##      (assign, ":min_num_centers", -1),
##      (assign, ":min_num_centers_troop", -1),
##      
##      (try_for_range, ":troop_no", kingdom_heroes_begin, kingdom_heroes_end),
##        (troop_slot_eq, ":troop_no", slot_troop_occupation, slto_kingdom_hero),
##        (store_troop_faction, ":troop_faction", ":troop_no"),
##        (eq, ":troop_faction", ":kingdom"),
##        (call_script, "script_get_number_of_hero_centers", ":troop_no"),
##        (assign, ":num_centers", reg0),
##        (try_begin),
##          (lt, ":num_centers", ":min_num_centers"),
##          (assign, ":min_num_centers", ":num_centers"),
##          (assign, ":min_num_centers_troop", ":troop_no"),
##        (try_end),
##      (try_end),
##      (assign, reg0, ":min_num_centers_troop"),
##  ]),
  
  
##  # script_get_random_enemy_center
##  # Input: arg1 = party_no
##  # Output: reg0 = center_no
##  ("get_random_enemy_center",
##    [
##      (store_script_param_1, ":party_no"),
##      
##      (assign, ":result", -1),
##      (assign, ":total_enemy_centers", 0),
##      (store_faction_of_party, ":party_faction_local", ":party_no"),
##      
##      (try_for_range, ":center_no", centers_begin, centers_end),
##        (store_faction_of_party, ":center_faction", ":center_no"),
##        (neq, ":center_faction", ":party_faction_local"),
##        (val_add, ":total_enemy_centers", 1),
##      (try_end),
##      
##      (try_begin),
##        (eq, ":total_enemy_centers", 0),
##      (else_try),
##        (store_random_in_range, ":random_center", 0, ":total_enemy_centers"),
##        (assign, ":total_enemy_centers", 0),
##        (try_for_range, ":center_no", centers_begin, centers_end),
##          (eq, ":result", -1),
##          (store_faction_of_party, ":center_faction", ":center_no"),
##          (neq, ":center_faction", ":party_faction_local"),
##          (store_relation, ":party_relation", ":center_faction", ":party_faction_local"),
##          (le, ":party_relation", -10),
##          (val_add, ":total_enemy_centers", 1),
##          (lt, ":random_center", ":total_enemy_centers"),
##          (assign, ":result", ":center_no"),
##        (try_end),
##      (try_end),
##      (assign, reg0, ":result"),
##  ]),
##  
  
##  # script_get_random_enemy_town
##  # Input: arg1 = party_no
##  # Output: reg0 = center_no
##  ("get_random_enemy_town",
##    [
##      (store_script_param_1, ":party_no"),
##      
##      (assign, ":result", -1),
##      (assign, ":total_enemy_centers", 0),
##      (store_faction_of_party, ":party_faction_local", ":party_no"),
##      
##      (try_for_range, ":center_no", towns_begin, towns_end),
##        (store_faction_of_party, ":center_faction", ":center_no"),
##        (neq, ":center_faction", ":party_faction_local"),
##        (val_add, ":total_enemy_centers", 1),
##      (try_end),
##      
##      (try_begin),
##        (eq, ":total_enemy_centers", 0),
##      (else_try),
##        (store_random_in_range, ":random_center", 0, ":total_enemy_centers"),
##        (assign, ":total_enemy_centers", 0),
##        (try_for_range, ":center_no", towns_begin, towns_end),
##          (eq, ":result", -1),
##          (store_faction_of_party, ":center_faction", ":center_no"),
##          (neq, ":center_faction", ":party_faction_local"),
##          (store_relation, ":party_relation", ":center_faction", ":party_faction_local"),
##          (le, ":party_relation", -10),
##          (val_add, ":total_enemy_centers", 1),
##          (lt, ":random_center", ":total_enemy_centers"),
##          (assign, ":result", ":center_no"),
##        (try_end),
##      (try_end),
##      (assign, reg0, ":result"),
##  ]),
  
  
  
  # script_find_travel_location
  # Input: arg1 = center_no
  # Output: reg0 = new_center_no (to travel within the same faction)
  ("find_travel_location",
    [
      (store_script_param_1, ":center_no"),
      (store_faction_of_party, ":faction_no", ":center_no"),
      (assign, ":total_weight", 0),
      (try_for_range, ":cur_center_no", centers_begin, centers_end),
        (neq, ":center_no", ":cur_center_no"),
        (store_faction_of_party, ":center_faction_no", ":cur_center_no"),
        (eq, ":faction_no", ":center_faction_no"),
        
        (store_distance_to_party_from_party, ":cur_distance", ":center_no", ":cur_center_no"),
        (val_add, ":cur_distance", 1),
        
        (assign, ":new_weight", 100000),
        (val_div, ":new_weight", ":cur_distance"),
        (val_add, ":total_weight", ":new_weight"),
      (try_end),
      
      (assign, reg0, -1),
      
      (try_begin),
        (eq, ":total_weight", 0),
      (else_try),
        (store_random_in_range, ":random_weight", 0 , ":total_weight"),
        (assign, ":total_weight", 0),
        (assign, ":done", 0),
        (try_for_range, ":cur_center_no", centers_begin, centers_end),
          (eq, ":done", 0),
          (neq, ":center_no", ":cur_center_no"),
          (store_faction_of_party, ":center_faction_no", ":cur_center_no"),
          (eq, ":faction_no", ":center_faction_no"),
          
          (store_distance_to_party_from_party, ":cur_distance", ":center_no", ":cur_center_no"),
          (val_add, ":cur_distance", 1),
          
          (assign, ":new_weight", 100000),
          (val_div, ":new_weight", ":cur_distance"),
          (val_add, ":total_weight", ":new_weight"),
          (lt, ":random_weight", ":total_weight"),
          (assign, reg0, ":cur_center_no"),
          (assign, ":done", 1),
        (try_end),
      (try_end),
  ]),
  
  
  # script_get_relation_between_parties
  # Input: arg1 = party_no_1, arg2 = party_no_2
  # Output: reg0 = relation between parties
  ("get_relation_between_parties",
    [
      (store_script_param_1, ":party_no_1"),
      (store_script_param_2, ":party_no_2"),
      
      (store_faction_of_party, ":party_no_1_faction", ":party_no_1"),
      (store_faction_of_party, ":party_no_2_faction", ":party_no_2"),
      (try_begin),
        (eq, ":party_no_1_faction", ":party_no_2_faction"),
        (assign, reg0, 100),
      (else_try),
        (store_relation, ":relation", ":party_no_1_faction", ":party_no_2_faction"),
        (assign, reg0, ":relation"),
      (try_end),
  ]),
  # script_calculate_weekly_party_wage
  # Input: arg1 = party_no
  # Output: reg0 = weekly wage
  ("calculate_weekly_party_wage",
    [
      (store_script_param_1, ":party_no"),
      
      (assign, ":result", 0),
      (party_get_num_companion_stacks, ":num_stacks",":party_no"),
      (try_for_range, ":i_stack", 0, ":num_stacks"),
        (party_stack_get_troop_id, ":stack_troop",":party_no",":i_stack"),
        (party_stack_get_size, ":stack_size",":party_no",":i_stack"),
   #edited start
   (try_begin),
   (neq,":stack_troop","trp_player"),
   (call_script, "script_npc_get_troop_wage", ":stack_troop", ":party_no"),
   (try_end),
   #edited end
        (assign, ":cur_wage", reg0),
        (val_mul, ":cur_wage", ":stack_size"),
        (val_add, ":result", ":cur_wage"),
      (try_end),
      (assign, reg0, ":result"),
  ]),

  # script_calculate_player_faction_wage
  # Input: arg1 = party_no
  # Output: reg0 = weekly wage
  # script_calculate_player_faction_wage
  # Input: arg1 = party_no
  # Output: reg0 = weekly wage
  ("calculate_player_faction_wage",
    [(assign, ":total_wages", 0),
     (try_for_parties, ":party_no"),
       (store_faction_of_party, ":party_faction_local", ":party_no"),
       (assign, ":garrison_troop", 0),
       (try_begin),
         (party_slot_eq, ":party_no", slot_party_type, spt_castle),
         (party_slot_eq, ":party_no", slot_town_lord, "trp_player"),
         (assign, ":garrison_troop", 1),
       (try_end),
       (this_or_next|eq, ":party_faction_local", "fac_player_faction"),
       (eq, ":garrison_troop", 1),
       (party_get_num_companion_stacks, ":num_stacks",":party_no"),
       (try_for_range, ":i_stack", 0, ":num_stacks"),
           (party_stack_get_troop_id, ":stack_troop",":party_no",":i_stack"),
           (party_stack_get_size, ":stack_size",":party_no",":i_stack"),
           #edited start
           (assign,reg59,0),
           (try_begin),
               (neq,":stack_troop","trp_player"),
               (call_script, "script_npc_get_troop_wage", ":stack_troop", ":party_no"),
               (assign, ":cur_wage", reg59),
               (val_mul, ":cur_wage", ":stack_size"),
               (assign,  reg60,":cur_wage"),
               (display_message,"@troop:{s59} wage:{reg59} wage at all:{reg60}"),
               (val_add, ":total_wages", ":cur_wage"),
           (try_end),
           #edited end
       (try_end),
     (try_end),
     (assign, reg0, ":total_wages"),
    ]),

  # script_calculate_hero_weekly_net_income_and_add_to_wealth
  # Input: arg1 = troop_no
  # Output: none
  ("calculate_hero_weekly_net_income_and_add_to_wealth",
    [
      (store_script_param_1, ":troop_no"),
      
      (troop_get_slot, ":party_no", ":troop_no", slot_troop_leaded_party),
      (troop_get_slot, ":cur_wealth", ":troop_no", slot_troop_wealth),
      
      (assign, ":weekly_income", 500), #let every hero receive 500 denars by default
      
      (store_character_level, ":troop_level", ":troop_no"),
      (store_mul, ":level_income", ":troop_level", 10),
      (val_add, ":weekly_income", ":level_income"),
      
      (store_troop_faction,":faction_no", ":troop_no"),
      (try_begin), #check if troop is kingdom leader
        (faction_slot_eq, ":faction_no", slot_faction_leader, ":troop_no"),
        (val_add, ":weekly_income", 2000),
      (try_end),
      
      (assign, ":cur_weekly_wage", 0),
      (try_begin),
        (gt, ":party_no",0),
        (call_script, "script_calculate_weekly_party_wage", ":party_no"),
        (assign, ":cur_weekly_wage", reg0),
      (try_end),
      (val_sub, ":weekly_income", ":cur_weekly_wage"),
      
      (val_add, ":cur_wealth", ":weekly_income"),
      (troop_set_slot, ":troop_no", slot_troop_wealth, ":cur_wealth"),
  ]),
  
  # script_cf_reinforce_party
  # Input: arg1 = party_no,
  # Output: none
  # Adds reinforcement to party according to its type and faction
  ("cf_reinforce_party",
    [
      (store_script_param_1, ":party_no"),
      
      (store_faction_of_party, ":party_faction_local", ":party_no"),
      (party_get_slot, ":party_type",":party_no", slot_party_type),

      (faction_get_slot, ":party_template_a", ":party_faction_local", slot_faction_reinforcements_a),
      (faction_get_slot, ":party_template_b", ":party_faction_local", slot_faction_reinforcements_b),
      (faction_get_slot, ":party_template_c", ":party_faction_local", slot_faction_reinforcements_c),

      (assign, ":party_template", 0),
      (store_random_in_range, ":rand", 0, 100),
      (try_begin),
        (this_or_next|eq, ":party_type", spt_town),
        (eq, ":party_type", spt_castle),  #CASTLE OR TOWN
        (try_begin),
          (lt, ":rand", 50),
          (assign, ":party_template", ":party_template_a"),
        (else_try),
          (assign, ":party_template", ":party_template_b"),
        (try_end),
      (else_try),
        (eq, ":party_type", spt_kingdom_hero_party),
        (try_begin),
          (lt, ":rand", 33),
          (assign, ":party_template", ":party_template_a"),
        (else_try),
          (lt, ":rand", 66),
          (assign, ":party_template", ":party_template_b"),
        (else_try),
          (assign, ":party_template", ":party_template_c"),
        (try_end),
      (else_try),
      (try_end),

      (try_begin),
        (gt, ":party_template", 0),
        (party_add_template, ":party_no", ":party_template"),
      (try_end),
  ]),
  
  # script_hire_men_to_kingdom_hero_party
  # Input: arg1 = troop_no (hero of the party)
  # Output: none
  ("hire_men_to_kingdom_hero_party",
    [
      (store_script_param_1, ":troop_no"),
      
      (troop_get_slot, ":party_no", ":troop_no", slot_troop_leaded_party),
      (troop_get_slot, ":cur_wealth", ":troop_no", slot_troop_wealth),
      

      (assign, ":hiring_budget", ":cur_wealth"),
      (val_mul, ":hiring_budget", 3),
      (val_div, ":hiring_budget", 4),
      
      (assign, ":num_rounds", 1),
    
      (call_script, "script_party_get_ideal_size", "$pout_party"),
      (assign, ":ideal_size", reg0),
    
      (party_get_num_companions, ":party_size", "$pout_party"),
      (try_for_range, ":unused", 0 , ":num_rounds"),
        (lt, ":party_size", ":ideal_size"),
        (gt,  ":hiring_budget", reinforcement_cost),
        (gt, ":party_no", 0),
        (call_script, "script_cf_reinforce_party", ":party_no"),
        (val_sub, ":cur_wealth", reinforcement_cost),
        (troop_set_slot, ":troop_no", slot_troop_wealth, ":cur_wealth"),
      (try_end),
  ]),
  
  # script_cf_create_merchant_party
  # Input: arg1 = troop_no,
  # Output: $pout_party = party_no
##  ("cf_create_merchant_party",
##    [
##      (store_script_param_1, ":troop_no"),
##      (store_troop_faction, ":troop_faction", ":troop_no"),
##      
##      (call_script, "script_cf_select_random_town_at_peace_with_faction", ":troop_faction"),
##      (assign, ":center_no", reg0),
##      
##      (assign, "$pout_party", -1),
##      (set_spawn_radius,0),
##      (spawn_around_party,":center_no", "pt_merchant_party"),
##      (assign, "$pout_party", reg0),
##      
##      (party_set_faction, "$pout_party", ":troop_faction"),
##      (party_set_slot, "$pout_party", slot_party_type, spt_merchant_caravan),
##      (party_set_slot, "$pout_party", slot_party_ai_state, spai_undefined),
##      (troop_set_slot, ":troop_no", slot_troop_leaded_party, "$pout_party"),
##      (party_add_leader, "$pout_party", ":troop_no"),
##      (str_store_troop_name, s5, ":troop_no"),
##      (party_set_name, "$pout_party", "str_s5_s_caravan"),
##      (party_set_ai_behavior, "$pout_party", ai_bhvr_travel_to_party),
##      (party_set_ai_object, "$pout_party", ":center_no"),
##      (party_set_flags, "$pout_party", pf_default_behavior, 0),
##      (store_sub, ":item_to_price_slot", slot_town_trade_good_prices_begin, trade_goods_begin),
##      (try_for_range, ":cur_goods", trade_goods_begin, trade_goods_end),
##        (store_add, ":cur_goods_price_slot", ":cur_goods", ":item_to_price_slot"),
##        (party_set_slot, "$pout_party", ":cur_goods_price_slot", average_price_factor),
##      (try_end),
##      (troop_set_slot, ":troop_no", slot_troop_wealth, 2000),
##  ]),
  
  
  # script_create_kingdom_hero_party
  # Input: arg1 = troop_no, arg2 = center_no
  # Output: $pout_party = party_no
  ("create_kingdom_hero_party",
    [
      (store_script_param_1, ":troop_no"),
      (store_script_param_2, ":center_no"),
      
      #      (store_faction_of_party, ":center_faction", ":center_no"),
      (store_troop_faction, ":troop_faction_no", ":troop_no"),
      
      
      #      (faction_get_slot, ":reinforcements_a", ":troop_faction_no", slot_faction_reinforcements_a),
      #      (faction_get_slot, ":reinforcements_b", ":troop_faction_no", slot_faction_reinforcements_b),
      #      (faction_get_slot, ":reinforcements_c", ":troop_faction_no", slot_faction_reinforcements_c),
      
      
      (assign, "$pout_party", -1),
      (set_spawn_radius,0),
      (spawn_around_party,":center_no", "pt_kingdom_hero_party"),
      (assign, "$pout_party", reg0),
      
      
      (party_set_faction, "$pout_party", ":troop_faction_no"),
      (party_set_slot, "$pout_party", slot_party_type, spt_kingdom_hero_party),
      (party_set_slot, "$pout_party", slot_party_ai_state, spai_undefined),
      (troop_set_slot, ":troop_no", slot_troop_leaded_party, "$pout_party"),
      (party_add_leader, "$pout_party", ":troop_no"),
      (str_store_troop_name, s5, ":troop_no"),
      (party_set_name, "$pout_party", "str_s5_s_party"),
      (display_log_message,"@{s5}'s party created"),
      (party_set_slot, "$pout_party", slot_party_commander_party, -1), #we need this because 0 is player's party!

      (assign, ":num_tries", 20),
      (try_begin),
        (store_troop_faction, ":troop_kingdom", ":troop_no"),
        (faction_slot_eq, ":troop_kingdom", slot_faction_leader, ":troop_no"),
        (assign, ":num_tries", 50),
      (try_end),

      (try_for_range, ":unused", 0, ":num_tries"),
        (call_script, "script_hire_men_to_kingdom_hero_party", ":troop_no" ),
      (else_try),
        (assign, ":num_tries", 0),
      (try_end),
      
      #Setting the flag icon
      (troop_get_slot, ":cur_banner", ":troop_no", slot_troop_banner_scene_prop),
      (try_begin),
        (gt, ":cur_banner", 0),
        (val_sub, ":cur_banner", "spr_banner_a"),
        (val_add, ":cur_banner", "icon_banner_01"),
        (party_set_banner_icon, "$pout_party", ":cur_banner"),
      (try_end),
  ]),
  
  # script_create_kingdom_party_if_below_limit
  # Input: arg1 = faction_no, arg2 = party_type (variables beginning with spt_)
  # Output: reg0 = party_no
  ("create_kingdom_party_if_below_limit",
    [
      (store_script_param_1, ":faction_no"),
      (store_script_param_2, ":party_type"),
      
      (try_begin),
        (eq, ":party_type", spt_deserter),
        (assign, ":faction_no", "fac_deserters"),
      (try_end),
      
      (call_script, "script_count_parties_of_faction_and_party_type", ":faction_no", ":party_type"),
      (assign, ":party_count", reg0),
      
      (assign, ":party_count_limit", 0),
      (try_begin),
        (eq, ":party_type", spt_forager),
        (assign, ":party_count_limit", 1),
      (else_try),
        (eq, ":party_type", spt_scout),
        (assign, ":party_count_limit", 1),
      (else_try),
        (eq, ":party_type", spt_patrol),
        (assign, ":party_count_limit", 1),
      (else_try),
        (eq, ":party_type", spt_messenger),
        (assign, ":party_count_limit", 1),
      (else_try),
        (eq, ":party_type", spt_kingdom_caravan),
        (assign, ":party_count_limit", 4),
      (else_try),
        (eq, ":party_type", spt_prisoner_train),
        (assign, ":party_count_limit", 1),
      (else_try),
        (eq, ":party_type", spt_deserter),
        (assign, ":party_count_limit", 1),
      (try_end),
      
      (assign, reg0, -1),
      (try_begin),
        (lt, ":party_count", ":party_count_limit"),
        (call_script,"script_cf_create_kingdom_party", ":faction_no", ":party_type"),
      (try_end),
  ]),
  
  
  # script_cf_create_kingdom_party
  # Input: arg1 = faction_no, arg2 = party_type (variables beginning with spt_)
  # Output: reg0 = party_no
  ("cf_create_kingdom_party",
    [
      (store_script_param_1, ":faction_no"),
      (store_script_param_2, ":party_type"),
      
      (str_store_faction_name, s7, ":faction_no"),
      (assign, ":party_name_str", "str_no_string"),
      
      (faction_get_slot, ":reinforcements_a", ":faction_no", slot_faction_reinforcements_a),
      (faction_get_slot, ":reinforcements_b", ":faction_no", slot_faction_reinforcements_b),
      (faction_get_slot, ":reinforcements_c", ":faction_no", slot_faction_reinforcements_c),
      
      (try_begin),
        (eq, ":party_type", spt_forager),
        (assign, ":party_template", "pt_forager_party"),
#        (assign, ":party_name_str", "str_s7_foragers"),
      (else_try),
        (eq, ":party_type", spt_scout),
        (assign, ":party_template", "pt_scout_party"),
#        (assign, ":party_name_str", "str_s7_scouts"),
      (else_try),
        (eq, ":party_type", spt_patrol),
        (assign, ":party_template", "pt_patrol_party"),
#        (assign, ":party_name_str", "str_s7_patrol"),
      (else_try),
        (eq, ":party_type", spt_kingdom_caravan),
        (assign, ":party_template", "pt_kingdom_caravan_party"),
#        (assign, ":party_name_str", "str_s7_caravan"),
      (else_try),
        (eq, ":party_type", spt_messenger),
        (assign, ":party_template", "pt_messenger_party"),
#        (assign, ":party_name_str", "str_s7_messenger"),
      (else_try),
        (eq, ":party_type", spt_raider),
        (assign, ":party_template", "pt_raider_party"),
        (assign, ":party_name_str", "str_s7_raiders"),
      (else_try),
        (eq, ":party_type", spt_prisoner_train),
        (assign, ":party_template", "pt_prisoner_train_party"),
#        (assign, ":party_name_str", "str_s7_prisoner_train"),
      (else_try),
        (eq, ":party_type", spt_deserter),
#        (assign, ":party_template", "pt_deserter_party"),
      (try_end),
      
      (assign, ":result", -1),
      (try_begin),
        (call_script,"script_cf_select_random_center_with_faction", ":faction_no"),
        (assign, ":spawn_center",reg0),
        (set_spawn_radius, 1),
        (spawn_around_party,":spawn_center",":party_template"),
        (assign, ":result", reg0),
        (party_set_faction, ":result", ":faction_no"),
        (party_set_slot, ":result", slot_party_type, ":party_type"),
        (party_set_slot, ":result", slot_party_ai_state, spai_undefined),
        (try_begin),
          (neq, ":party_name_str", "str_no_string"),
          (party_set_name, ":result", ":party_name_str"),
        (try_end),
        
        (try_begin),
          (eq, ":party_type", spt_forager),
          (party_add_template, ":result", ":reinforcements_a"),
        (else_try),
          (eq, ":party_type", spt_scout),
          (party_add_template, ":result", ":reinforcements_c"),
        (else_try),
          (eq, ":party_type", spt_patrol),
          (party_add_template, ":result", ":reinforcements_a"),
          (party_add_template, ":result", ":reinforcements_b"),
        (else_try),
          (eq, ":party_type", spt_kingdom_caravan),
          (party_add_template, ":result", ":reinforcements_b"),
          (party_add_template, ":result", ":reinforcements_b"),
          (party_set_ai_behavior,":result",ai_bhvr_travel_to_party),
          (party_set_ai_object,":result",":spawn_center"),
          (party_set_flags, ":result", pf_default_behavior, 1),
          (store_sub, ":item_to_price_slot", slot_town_trade_good_prices_begin, trade_goods_begin),
          (try_for_range, ":cur_goods", trade_goods_begin, trade_goods_end),
            (store_add, ":cur_goods_price_slot", ":cur_goods", ":item_to_price_slot"),
            (party_set_slot, ":result", ":cur_goods_price_slot", average_price_factor),
          (try_end),
        (else_try),
          (eq, ":party_type", spt_messenger),
          (faction_get_slot, ":messenger_troop", ":faction_no", slot_faction_messenger_troop),
          (party_add_leader, ":result", ":messenger_troop"),
          (party_set_ai_behavior,":result",ai_bhvr_travel_to_party),
          (party_set_ai_object,":result",":spawn_center"),
          (party_set_flags, ":result", pf_default_behavior, 0),
        (else_try),
          (eq, ":party_type", spt_raider),
          (party_add_template, ":result", ":reinforcements_c"),
          (party_add_template, ":result", ":reinforcements_b"),
          (party_add_template, ":result", "pt_raider_captives"),
        (else_try),
          (eq, ":party_type", spt_prisoner_train),
          (party_add_template, ":result", ":reinforcements_b"),
          (party_add_template, ":result", ":reinforcements_a"),
          (try_begin),
            (call_script,"script_cf_faction_get_random_enemy_faction",":faction_no"),
            (store_random_in_range,":r",0,2),
            (try_begin),
              (lt, ":r", 1),
              (faction_get_slot, ":captive_reinforcements", reg0, slot_faction_reinforcements_b),
            (else_try),
              (faction_get_slot, ":captive_reinforcements", reg0, slot_faction_reinforcements_a),
            (try_end),
            (party_add_template, ":result", ":captive_reinforcements",1),
          (else_try),
            (party_add_template, ":result", "pt_default_prisoners"),
          (try_end),
        (else_try),
          (eq, ":party_type", spt_deserter),
          (party_set_faction, ":result", "fac_deserters"),
          (faction_get_slot, ":deserter_troop", ":faction_no", slot_faction_deserter_troop),
          (str_store_troop_name_plural, s0, ":deserter_troop"),
          (party_set_name, ":result", "str_s0"),
          (party_get_num_companions, ":num_deserters_in_party", ":result"),
          (party_clear, ":result"),
          (party_add_members, ":result", ":deserter_troop", ":num_deserters_in_party"),
        (try_end),
      (try_end),
      (ge, ":result", 0),
      (assign, reg0, ":result"),
  ]),
  
  # script_get_troop_attached_party
  # Input: arg1 = troop_no
  # Output: reg0 = party_no (-1 if troop's party is not attached to a party)
  ("get_troop_attached_party",
    [
      (store_script_param_1, ":troop_no"),
      
      (troop_get_slot, ":party_no", ":troop_no", slot_troop_leaded_party),
      (assign, ":attached_party_no", -1),
      (try_begin),
        (ge, ":party_no", 0),
        (party_get_attached_to, ":attached_party_no", ":party_no"),
      (try_end),
      (assign, reg0, ":attached_party_no"),
  ]),


  # script_center_get_food_consumption
  # Input: arg1 = center_no
  # Output: reg0: food consumption (1 food item counts as 100 units)
  ("center_get_food_consumption",
    [
      (store_script_param_1, ":center_no"),
      (assign, ":food_consumption", 0),
      (try_begin),
        (party_slot_eq, ":center_no", slot_party_type, spt_town),
        (assign, ":food_consumption", 500),
      (else_try),
        (party_slot_eq, ":center_no", slot_party_type, spt_castle), #TODO: check garrison size?
        (assign, ":food_consumption", 50),
      (try_end),
      (assign, reg0, ":food_consumption"),
  ]),
  
  # script_center_get_food_store_limit
  # Input: arg1 = center_no
  # Output: reg0: food consumption (1 food item counts as 100 units)
  ("center_get_food_store_limit",
    [
      (store_script_param_1, ":center_no"),
      (assign, ":food_store_limit", 0),
      (try_begin),
        (party_slot_eq, ":center_no", slot_party_type, spt_town),
        (assign, ":food_store_limit", 30000),
      (else_try),
        (party_slot_eq, ":center_no", slot_party_type, spt_castle), #TODO: check garrison size?
        (assign, ":food_store_limit", 1500),
      (try_end),
      (assign, reg0, ":food_store_limit"),
  ]),

  # script_refresh_village_merchant_inventory
  # Input: arg1 = village_no
  # Output: none
  ("refresh_village_merchant_inventory",
    [
      (store_script_param_1, ":village_no"),
      (party_get_slot, ":merchant_troop", ":village_no", slot_town_merchant),
      (reset_item_probabilities,0),
      (set_item_probability_in_merchandise,"itm_salt",100),
      (set_item_probability_in_merchandise,"itm_grain",100),
      (troop_add_merchandise,":merchant_troop",itp_type_goods,3),
      (troop_ensure_inventory_space,":merchant_troop", 80),
  ]),

  # script_refresh_village_defenders
  # Input: arg1 = village_no
  # Output: none
  ("refresh_village_defenders",
    [
      (store_script_param_1, ":village_no"),

      (assign, ":ideal_size", 50),
      (try_begin),
        (party_get_num_companions, ":party_size", ":village_no"),
        (lt, ":party_size", ":ideal_size"),
        (party_add_template, ":village_no", "pt_village_defenders"),
      (try_end),
  ]),

  # script_village_set_state
  # Input: arg1 = center_no arg2:new_state
  # Output: reg0: food consumption (1 food item counts as 100 units)
  ("village_set_state",
    [
      (store_script_param_1, ":village_no"),
      (store_script_param_2, ":new_state"),
#      (party_get_slot, ":old_state", ":village_no", slot_village_state),
      (try_begin),
        (eq, ":new_state", 0),
        (party_set_extra_text, ":village_no", "str_empty_string"),
        (party_set_slot, ":village_no", slot_village_raided_by, -1),
      (else_try),
        (eq, ":new_state", svs_being_raided),
        (party_set_extra_text, ":village_no", "@(Being Raided)"),
      (else_try),
        (eq, ":new_state", svs_looted),
        (party_set_extra_text, ":village_no", "@(Looted)"),
        (party_set_slot, ":village_no", slot_village_raided_by, -1),
      (else_try),
        (eq, ":new_state", svs_under_siege),
        (party_set_extra_text, ":village_no", "@(Under Siege)"),
      (try_end),
      (party_set_slot, ":village_no", slot_village_state, ":new_state"),
  ]),


  # script_process_village_raids
  # Input: none
  # Output: none
  # called from triggers every three hours
  ("process_village_raids",
    [
       (try_for_range, ":village_no", villages_begin, villages_end),
         (party_get_slot, ":village_raid_progress", ":village_no", slot_village_raid_progress),
         (party_get_slot, ":village_raid_progress", ":village_no", slot_village_raid_progress),
         (try_begin),
           (party_slot_eq, ":village_no", slot_village_state, 0), #village is normal
           (val_sub, ":village_raid_progress", 10),
           (val_max, ":village_raid_progress", 0),
           (party_set_slot, ":village_no", slot_village_raid_progress, ":village_raid_progress"),
         (else_try),
           (party_slot_eq, ":village_no", slot_village_state, svs_being_raided), #village is being raided
#           (store_faction_of_party, ":village_faction", ":village_no"),
       # End raid unless there is an enemy party nearby
           (assign, ":raid_ended", 1),
           (party_get_slot, ":raider_party", ":village_no", slot_village_raided_by),
           (try_begin),
             (ge, ":raider_party", 0),
             (party_is_active, ":raider_party"),
             (this_or_next|neq, ":raider_party", "p_main_party"),
             (eq, "$g_player_is_captive", 0),
             (store_distance_to_party_from_party, ":distance", ":village_no", ":raider_party"),
             (lt, ":distance", raid_distance),
             (assign, ":raid_ended", 0),
           (try_end),
           (try_begin),
             (eq, ":raid_ended", 1),
             (call_script, "script_village_set_state",  ":village_no", 0), #clear raid flag
             (party_set_slot, ":village_no", slot_village_smoke_added, 0),
             (party_clear_particle_systems, ":village_no"),
           (else_try),
             (val_add, ":village_raid_progress", 8),
             (party_set_slot, ":village_no", slot_village_raid_progress, ":village_raid_progress"),
             (try_begin),
               (ge, ":village_raid_progress", 50),
               (party_slot_eq, ":village_no", slot_village_smoke_added, 0),
               (party_add_particle_system, ":village_no", "psys_map_village_fire"),
               (party_add_particle_system, ":village_no", "psys_map_village_fire_smoke"),
               (party_set_icon, ":village_no", "icon_village_burnt_a"),
               (party_set_slot, ":village_no", slot_village_smoke_added, 1),
             (try_end),
             (try_begin),
               (gt, ":village_raid_progress", 100),
               (str_store_party_name, s1, ":village_no"),
               (party_get_slot, ":looter_party", ":village_no", slot_village_raided_by),
               (str_store_party_name, s2, ":looter_party"),
               (display_log_message, "@The village of {s1} has been looted by {s2}."),
               (call_script, "script_village_set_state",  ":village_no", svs_looted),
               (party_set_slot, ":village_no", slot_village_raid_progress, 0),
               (party_set_slot, ":village_no", slot_village_recover_progress, 0),
             (try_end),
           (try_end),
         (else_try),
           (party_slot_eq, ":village_no", slot_village_state, svs_looted), #village is looted
           (party_get_slot, ":recover_progress", ":village_no", slot_village_recover_progress),
           (val_add, ":recover_progress", 1),
           (party_set_slot, ":village_no", slot_village_recover_progress, ":recover_progress"), #village looted
           (try_begin),
             (ge, ":recover_progress", 10),
             (party_slot_eq, ":village_no", slot_village_smoke_added, 1),
             (party_clear_particle_systems, ":village_no"),
             (party_add_particle_system, ":village_no", "psys_map_village_looted_smoke"),
             (party_set_slot, ":village_no", slot_village_smoke_added, 2),
           (try_end),
           (try_begin),
             (gt, ":recover_progress", 50),
             (party_slot_eq, ":village_no", slot_village_smoke_added, 2),
             (party_clear_particle_systems, ":village_no"),
             (party_set_slot, ":village_no", slot_village_smoke_added, 3),
             (party_set_icon, ":village_no", "icon_village_deserted_a"),
           (try_end),
           (try_begin),
             (gt, ":recover_progress", 100),
             (call_script, "script_village_set_state",  ":village_no", 0),#village back to normal
             (party_set_slot, ":village_no", slot_village_recover_progress, 0),
             (party_clear_particle_systems, ":village_no"),
             (party_set_slot, ":village_no", slot_village_smoke_added, 0),
             (party_set_icon, ":village_no", "icon_village_a"),
           (try_end),
         (try_end),
       (try_end),
  ]),

 
  # script_process_sieges
  # Input: none
  # Output: none
  #called from triggers
  ("process_sieges",
    [
       (try_for_range, ":center_no", walled_centers_begin, walled_centers_end),
         (party_get_slot, ":town_food_store", ":center_no", slot_party_food_store),
         (call_script, "script_center_get_food_store_limit", ":center_no"),
         (assign, ":food_store_limit", reg0),
         (try_begin),
           (party_get_slot, ":besieger_party", ":center_no", slot_center_is_besieged_by),
           (ge, ":besieger_party", 0), #town is under siege
           (store_faction_of_party, ":center_faction", ":center_no"),
        # Lift siege unless there is an enemy party nearby
           (assign, ":siege_lifted", 0),
           (try_begin),
             (store_distance_to_party_from_party, ":besieger_distance", ":center_no", ":besieger_party"),
             (this_or_next|gt, ":besieger_distance", 5),
             (neg|party_is_active, ":besieger_party"),
             (assign, ":siege_lifted", 1),
             (try_for_range, ":enemy_hero", kingdom_heroes_begin, kingdom_heroes_end),
               (troop_slot_eq, ":enemy_hero", slot_troop_occupation, slto_kingdom_hero),
               (troop_get_slot, ":enemy_party", ":enemy_hero", slot_troop_leaded_party),
               (ge, ":enemy_party", 0),
               (store_faction_of_party, ":party_faction_local", ":enemy_party"),
               (store_relation, ":reln", ":party_faction_local", ":center_faction"),
               (lt, ":reln", 0),
               (store_distance_to_party_from_party, ":distance", ":center_no", ":enemy_party"),
               (lt, ":distance", 4),
               (assign, ":besieger_party", ":enemy_party"),
               (party_set_slot, ":center_no", slot_center_is_besieged_by, ":enemy_party"),
               (assign, ":siege_lifted", 0),
             (try_end),
           (try_end),
           (try_begin),
             (eq, ":siege_lifted", 1),
             (party_set_slot, ":center_no", slot_center_is_besieged_by, -1), #clear siege
             (call_script, "script_village_set_state",  ":center_no", 0), #clear siege flag
             (try_begin),
               (eq, ":center_no", "$g_player_besiege_town"),
               (assign, "$g_siege_method", 0), #remove siege progress
             (try_end),
             (str_store_party_name, s3, ":center_no"),
             (display_message, "@{s3} is no longer under siege."),
           (else_try),
             (call_script, "script_center_get_food_consumption", ":center_no"),
             (assign, ":food_consumption", reg0),
             (val_sub, ":town_food_store", ":food_consumption"), #reduce food only under siege???
             (try_begin),
               (le, ":town_food_store", 0), #town is starving
               (store_random_in_range, ":r", 0, 100),
               (lt, ":r", 10), 
               (call_script, "script_party_wound_all_members", ":center_no"), # town falls with 10% chance if starving
             (try_end),
           (try_end),
         (else_try),
           #town is not under siege...
           (val_add, ":town_food_store", 30), #add 30 food (significant for castles only.
         (try_end),

         (val_min, ":town_food_store", ":food_store_limit"),
         (val_max, ":town_food_store", 0),
         (party_set_slot, ":center_no", slot_party_food_store, ":town_food_store"),
       (try_end),
  ]),

  # script_process_alarms
  # Input: none
  # Output: none
  #called from triggers
  ("process_alarms",
    [
       (try_for_range, ":center_no", centers_begin, centers_end),
         (party_set_slot, ":center_no", slot_center_last_spotted_enemy, -1),
       (try_end),
       (assign, ":spotting_range", 6),
       (try_begin),
         (is_currently_night),
         (assign, ":spotting_range", 3),
       (try_end),
       (try_for_parties, ":party_no"),
         (party_slot_eq, ":party_no", slot_party_type, spt_kingdom_hero_party),
         (neg|party_is_in_any_town, ":party_no"),
         (store_faction_of_party, ":party_faction_local", ":party_no"),
         (try_for_range, ":center_no", centers_begin, centers_end),
           (store_distance_to_party_from_party, ":distance", ":party_no", ":center_no"),
           (lt, ":distance", ":spotting_range"),
           (store_faction_of_party, ":center_faction", ":center_no"),
           (store_relation, ":reln", ":center_faction", ":party_faction_local"),
           (lt, ":reln", 0),
           (party_set_slot, ":center_no", slot_center_last_spotted_enemy, ":party_no"), 
         (try_end),
       (try_end),
       (try_for_range, ":center_no", centers_begin, centers_end),
         (store_faction_of_party, ":center_faction", ":center_no"),
         (eq, ":center_faction", "$players_kingdom"),
         (party_get_slot, ":enemy_party", ":center_no", slot_center_last_spotted_enemy),
         (ge, ":enemy_party", 0),
         (str_store_party_name, s1, ":center_no"),
         (display_message, "@Enemies spotted near {s1}"),
       (try_end),
  ]),

  
  # script_party_set_ai_state
  # Input: arg1 = party_no, arg2 = new_ai_state, arg3 = action_object (if necessary)
  # Output: none (Can fail)
  ("party_set_ai_state",
    [
      (store_script_param, ":party_no", 1),
      (store_script_param, ":new_ai_state", 2),
      (store_script_param, ":new_ai_object", 3),

      (party_get_slot, ":old_ai_state", ":party_no", slot_party_ai_state),
      (party_get_slot, ":old_ai_object", ":party_no", slot_party_ai_object),
      (party_get_attached_to, ":attached_to_party", ":party_no"),
      (assign, ":party_is_in_town", 0),
      (try_begin),
        (is_between, ":attached_to_party", centers_begin, centers_end),
        (assign, ":party_is_in_town", ":attached_to_party"),
      (try_end),
      
      (try_begin),
        (eq, ":old_ai_state", ":new_ai_state"),
        (eq, ":old_ai_object", ":new_ai_object"),
        #do nothing. Nothing is changed.
      (else_try),
        (try_begin),
          (eq, ":new_ai_state", spai_accompanying_army),
          (party_set_ai_behavior, ":party_no", ai_bhvr_escort_party),
          (party_set_ai_object, ":party_no", ":new_ai_object"),
          (party_set_flags, ":party_no", pf_default_behavior, 0),
          (try_begin),
            (gt, ":party_is_in_town", 0),
            (party_detach, ":party_no"),
          (try_end),
        (else_try),
          (eq, ":new_ai_state", spai_besieging_center),
          (party_get_position, pos1, ":new_ai_object"),
          (map_get_random_position_around_position, pos2, pos1, 2),
          (party_set_ai_behavior, ":party_no", ai_bhvr_travel_to_point),
          (party_set_ai_target_position, ":party_no", pos2),
          (party_set_ai_object, ":party_no", ":new_ai_object"),
          (party_set_flags, ":party_no", pf_default_behavior, 0),
          (try_begin),
            (gt, ":party_is_in_town", 0),
            (neq, ":party_is_in_town", ":new_ai_object"),
            (party_detach, ":party_no"),
          (try_end),
        (else_try),
          (eq, ":new_ai_state", spai_holding_center),
          (party_set_ai_behavior, ":party_no", ai_bhvr_travel_to_party),
          (party_set_ai_object, ":party_no", ":new_ai_object"),
          (party_set_flags, ":party_no", pf_default_behavior, 0),
          (try_begin),
            (gt, ":party_is_in_town", 0),
            (neq, ":party_is_in_town", ":new_ai_object"),
            (party_detach, ":party_no"),
          (try_end),
        (else_try),
          (eq, ":new_ai_state", spai_raiding_around_center),
          (party_get_position, pos1, ":new_ai_object"),
          (map_get_random_position_around_position, pos2, pos1, 1),
          (party_set_ai_behavior, ":party_no", ai_bhvr_patrol_location),
          (party_set_ai_patrol_radius, ":party_no", 10),
          (party_set_ai_target_position, ":party_no", pos2),
          (party_set_ai_object, ":party_no", ":new_ai_object"),
          (party_set_flags, ":party_no", pf_default_behavior, 0),
          (try_begin),
            (gt, ":party_is_in_town", 0),
            (neq, ":party_is_in_town", ":new_ai_object"),
            (party_detach, ":party_no"),
          (try_end),
        (else_try),
          (eq, ":new_ai_state", spai_raiding_village),
          (party_get_position, pos1, ":new_ai_object"),
          (map_get_random_position_around_position, pos2, pos1, 1),
          (party_set_ai_behavior, ":party_no", ai_bhvr_travel_to_point),
          (party_set_ai_target_position, ":party_no", pos2),
          (party_set_ai_object, ":party_no", ":new_ai_object"),
          (party_set_flags, ":party_no", pf_default_behavior, 0),
          (try_begin),
            (gt, ":party_is_in_town", 0),
            (neq, ":party_is_in_town", ":new_ai_object"),
            (party_detach, ":party_no"),
          (try_end),
        (else_try),
          (eq, ":new_ai_state", spai_engaging_army),
          (party_set_ai_behavior, ":party_no", ai_bhvr_attack_party),
          (party_set_ai_object, ":party_no", ":new_ai_object"),
          (party_set_flags, ":party_no", pf_default_behavior, 0),
          (try_begin),
            (gt, ":party_is_in_town", 0),
            (party_detach, ":party_no"),
          (try_end),
        (else_try),
          (eq, ":new_ai_state", spai_undefined),
          (party_set_ai_behavior, ":party_no", ai_bhvr_hold),
          (party_set_flags, ":party_no", pf_default_behavior, 0),
        (try_end),
      (try_end),

      (party_set_slot, ":party_no", slot_party_ai_state, ":new_ai_state"),
      (party_set_slot, ":party_no", slot_party_ai_object, ":new_ai_object"),
      
  ]),

  # script_decide_kingdom_party_ai
  # Input: none
  # Output: none
  #called from triggers
  ("decide_kingdom_party_ai",
   [
       (store_script_param_1, ":troop_no"),
       (try_begin),
         (troop_slot_eq, ":troop_no", slot_troop_occupation, slto_kingdom_hero),
         (troop_slot_eq, ":troop_no", slot_troop_is_prisoner, 0),
         (troop_get_slot, ":party_no", ":troop_no", slot_troop_leaded_party),
         (gt, ":party_no", 0),

        (call_script, "script_party_count_fit_for_battle", ":party_no"),
        (assign, ":party_fit_for_battle", reg0),

        (call_script, "script_party_get_ideal_size", ":party_no"),
        (assign, ":ideal_size", reg0),
        (store_mul, "$party_relative_strength", ":party_fit_for_battle", 100),
        (val_div, "$party_relative_strength", ":ideal_size"),

        (call_script, "script_party_count_prisoners", ":party_no"),
        (assign, ":num_prisoners", reg0),
        (store_div, "$ratio_of_prisoners", ":num_prisoners", ":party_fit_for_battle"),
       
         (call_script, "script_kingdom_hero_decide_next_ai_state", ":troop_no"),
         (try_begin),
           (party_get_slot, ":commander_party", ":party_no", slot_party_commander_party),
           (ge, ":commander_party", 0),
           (try_begin),
             (gt, "$party_relative_strength", 40),
             (lt,  "$ratio_of_prisoners", 50),
             (call_script, "script_party_decide_next_ai_state_under_command", ":party_no"),
           (else_try),
             (party_set_slot, ":party_no", slot_party_commander_party, -1), #cancel escorting.
           (try_end),
         (try_end),
       (try_end),
  ]),

  # script_party_decide_next_ai_state_under_command
  # Input: arg1 = party_no
  # Output: none
  #called from triggers
  ("party_decide_next_ai_state_under_command",
    [
      (store_script_param_1, ":party_no"),
      (party_get_slot, ":commander_party", ":party_no", slot_party_commander_party),
#      (party_get_slot, ":ai_state", ":party_no", slot_party_ai_state),
#      (party_get_slot, ":ai_object", ":party_no", slot_party_ai_object),
      (party_get_slot, ":commander_ai_state", ":commander_party", slot_party_ai_state),
      (party_get_slot, ":commander_ai_object", ":commander_party", slot_party_ai_object),
      
      (store_distance_to_party_from_party, ":distance_to_commander", ":party_no", ":commander_party"),
      (try_begin),
        (gt, ":distance_to_commander", 5),
        (call_script, "script_party_set_ai_state", ":party_no", spai_accompanying_army, ":commander_party"),
      (else_try),
        (try_begin),
          (eq, ":commander_party", "p_main_party"),
          (call_script, "script_party_set_ai_state", ":party_no", spai_accompanying_army, "p_main_party"),
        (else_try),
          (eq, ":commander_ai_state", spai_besieging_center),
          (call_script, "script_party_set_ai_state", ":party_no", spai_besieging_center, ":commander_ai_object"),
        (try_end),
      (try_end),
  ]),


  # script_kingdom_hero_decide_next_ai_state
  # Input: arg1 = troop_no
  # Output: none
  #called from triggers
  ("kingdom_hero_decide_next_ai_state",
    [
      (store_script_param_1, ":troop_no"),
      (try_begin),
        (troop_get_slot, ":party_no", ":troop_no", slot_troop_leaded_party),
        (gt, ":party_no", 0),
        (troop_slot_eq, ":troop_no", slot_troop_occupation, slto_kingdom_hero),
        (troop_slot_eq, ":troop_no", slot_troop_is_prisoner, 0),

      #find current center
        (party_get_attached_to, ":cur_center_no", ":party_no"),
        (try_begin),
          (lt, ":cur_center_no", 0),
          (party_get_cur_town, ":cur_center_no", ":party_no"),
        (try_end),
        (try_begin),
          (neg|is_between, ":cur_center_no", centers_begin, centers_end),
          (assign, ":cur_center_no", -1),
        (try_end),

        (store_troop_faction, ":faction_no", ":troop_no"),

#        (party_get_slot, ":old_commander_party", ":party_no", slot_party_commander_party),
        (party_get_slot, ":old_ai_state", ":party_no", slot_party_ai_state),
#        (party_get_slot, ":old_ai_object", ":party_no", slot_party_ai_object),

        (assign, ":cancel", 0),
        (try_begin), #if we are retreating to a center keep retreating
          (eq, ":old_ai_state", spai_retreating_to_center),
          (neg|party_is_in_any_town, ":party_no"),
          (assign, ":cancel", 1),
        (try_end),
        (eq, ":cancel", 0),

        (faction_get_slot, ":faction_ai_state",  ":faction_no", slot_faction_ai_state),
        (faction_get_slot, ":faction_ai_object", ":faction_no", slot_faction_ai_object),


        (assign, ":chance_move_to_home_center", 0),
        (assign, ":target_move_to_home_center", -1),
        (assign, ":chance_move_to_other_center", 0),
        (assign, ":target_move_to_other_center", -1),
        (assign, ":chance_besiege_enemy_center", 0),
        (assign, ":target_besiege_enemy_center", -1),
        (assign, ":chance_raid_around_center", 0),
        (assign, ":target_raid_around_center", -1),
      
        (assign, ":chance_patrol_around_center", 0),
        (assign, ":target_patrol_around_center", -1),
        (assign, ":chance_raid_around_center", 0),
        (assign, ":target_raid_around_center", -1),
        (assign, ":chance_to_follow_other_party", 0),
        (assign, ":target_to_follow_other_party", -1),
        (assign, ":chance_stay", 0),
      
#        (assign, ":is_besieging", 0),
#        (assign, ":under_siege", 0),
      
        (try_begin),
#          (is_between, ":cur_center_no", walled_centers_begin, walled_centers_end),
#          (party_slot_ge, ":cur_center_no", slot_center_is_besieged_by, 0),
#          (assign, ":under_siege", 1),
        (try_end),

      
        (try_begin),
          (assign, ":target_move_to_home_center", -1), #Moving to home center
          (try_begin),
            (is_between, ":cur_center_no", centers_begin, centers_end), #already in our center
            (party_slot_eq,  ":cur_center_no", slot_town_lord, ":troop_no"),
            (assign, ":target_move_to_home_center", ":cur_center_no"),
            (assign, ":chance_move_to_home_center", 100),
          (try_end),
          (try_begin),
            (eq, ":target_move_to_home_center", -1),
            (call_script, "script_cf_troop_get_random_leaded_center", ":troop_no"),#Can fail
            (is_between, reg0, walled_centers_begin, walled_centers_end), # Do not move into villages
            (assign, ":target_move_to_home_center", reg0),
            (assign, ":chance_move_to_home_center", 50),
          (try_end),
        (try_end),
        (try_begin),
          (assign, ":target_move_to_other_center", -1),#Moving to other center
          (try_begin),
            (party_slot_eq, ":party_no", slot_party_ai_state, spai_holding_center),
            (party_get_slot, ":target_move_to_other_center", ":party_no", slot_party_ai_object),
           (assign, ":chance_move_to_other_center", 30),
          (try_end),
          (try_begin),
            (eq, ":target_move_to_other_center", -1),
            (call_script, "script_cf_select_random_center_with_faction", ":faction_no"),
            (assign, ":target_move_to_other_center", reg0),
            (assign, ":chance_move_to_other_center", 10),
            (party_get_slot, ":lord_of_center", ":target_move_to_other_center", slot_town_lord),
            (try_begin),
              (call_script, "script_cf_troop_check_troop_is_enemy", ":troop_no", ":lord_of_center"),
            (else_try),
              (assign, ":chance_move_to_other_center", 0),
            (try_end),
          (try_end),
        (try_end),
        (try_begin),
          (lt, "$party_relative_strength", 50),
          (store_sub, ":factor", 100, "$party_relative_strength"),
          (val_mul, ":chance_move_to_home_center", 200),
          (val_div, ":chance_move_to_home_center", ":factor"),
        (try_end),
        (try_begin),
          (gt,  "$ratio_of_prisoners", 50),
          (val_mul, ":chance_move_to_home_center", 2),
        (try_end),
        (try_begin), #raid villages
          (gt, "$party_relative_strength", 75),
          (lt,  "$ratio_of_prisoners", 50),
          (try_for_range, ":enemy_village_no", villages_begin, villages_end),
            (store_faction_of_party, ":enemy_village_faction", ":enemy_village_no"),
            (store_relation, ":reln", ":enemy_village_faction", ":faction_no"),
            (lt, ":reln", 0),
            (store_distance_to_party_from_party, ":dist", ":enemy_village_no", ":party_no"),
            (lt, ":dist", 70),
            (party_slot_eq, ":enemy_village_no", slot_village_state, 0), #village is not already raided
            (store_random_in_range, ":rand", 0, 100),
            (lt, ":rand", 5),
            (assign, ":chance_raid_around_center", 20),
            (assign, ":target_raid_around_center", ":enemy_village_no"),
          (try_end),
        (try_end),
        (try_begin),
          (gt, "$party_relative_strength", 65),
          (lt,  "$ratio_of_prisoners", 50),
          (eq, ":faction_ai_state", sfai_attacking_center),
          (assign, ":target_besiege_enemy_center", ":faction_ai_object"),
          (assign, ":chance_besiege_enemy_center", 30),
        (try_end),
        (try_begin), #patrol alarmed center.
          (gt, "$party_relative_strength", 65),
          (try_begin),
            (party_slot_eq, ":party_no", slot_party_ai_state, spai_patrolling_around_center),
            (party_get_slot, ":target_patrol_around_center", ":party_no", slot_party_ai_object),
          (try_end),
          (assign, ":best_patrol_score", 0),
          (assign, ":best_patrol_target", -1),
          (try_for_range, ":center_no", centers_begin, centers_end), #find closest center that has spotted enemies.
            (store_distance_to_party_from_party, ":distance", ":party_no", ),
            (lt, ":distance", 50),
            (store_faction_of_party, ":center_faction", ":center_no"),
            (eq, ":center_faction", ":faction_no"),
            (party_slot_ge, ":center_no", slot_center_last_spotted_enemy, 0),
            (store_sub, ":this_center_score", 100, ":distance"),
            (try_begin),
              (party_slot_eq, ":center_no", slot_town_lord, ":troop_no"),
              (val_mul, ":this_center_score", 2),
            (try_end),
            (try_begin),
              (gt, ":this_center_score", ":best_patrol_score"),
              (assign, ":best_patrol_score", ":this_center_score"),
              (assign, ":best_patrol_target", ":center_no"),
            (try_end),
          (try_end),
          (try_begin),
            (gt, ":best_patrol_score", 0),
            (assign, ":target_patrol_around_center", ":best_patrol_target"),
          (try_end),
          (try_begin),
             (is_between, ":target_patrol_around_center", centers_begin, centers_end),
             (assign, ":chance_patrol_around_center", 100),
          (try_end),
        (try_end),
        (try_begin), #follow other party
          (gt, "$party_relative_strength", 75),
          (neg|faction_slot_eq, ":faction_no", slot_faction_leader, ":troop_no"),
          (assign, ":done", 0),
          (try_for_range, ":other_hero", kingdom_heroes_begin, kingdom_heroes_end),
            (eq, ":done", 0),
            (neq, ":other_hero", ":troop_no"),
            (store_troop_faction, ":troop_faction", ":other_hero"),
            (eq, ":troop_faction", ":faction_no"),
            (troop_get_slot, ":other_party", ":other_hero", slot_troop_leaded_party),
            (ge, ":other_party", 0),
            (neg|party_slot_ge, ":other_party", slot_party_commander_party, 0), #other party is not under command itself.
            (store_distance_to_party_from_party, ":dist", ":other_party", ":party_no"),
            (lt, ":dist", 25),
            (party_get_slot, ":other_party_ai_state", ":other_party", slot_party_ai_state),
            (this_or_next|eq, ":other_party_ai_state", spai_patrolling_around_center),
            (this_or_next|eq, ":other_party_ai_state", spai_besieging_center),
            (this_or_next|eq, ":other_party_ai_state", spai_raiding_around_center),
            (eq, ":other_party_ai_state", spai_raiding_village),
            (assign, ":chance_to_follow_other_party", 50),
            (try_begin),
              (faction_slot_eq, ":faction_no", slot_faction_leader, ":other_hero"),
              (val_mul, ":chance_to_follow_other_party", 2),
            (try_end),
            (assign, ":target_to_follow_other_party", ":other_party"),
          (try_end),
        (try_end),
        (try_begin),
          (party_get_slot, ":ai_state", ":party_no", slot_party_ai_state),#Stay
          (party_get_slot, ":ai_object", ":party_no", slot_party_ai_object),
          (neq, ":ai_state", spai_undefined),
          (assign, ":cancel_cur_action", 0),
          (try_begin),
            (eq, ":ai_state", spai_patrolling_around_center),
            (neg|party_slot_ge, ":ai_object", slot_center_last_spotted_enemy, 0),
            (store_random_in_range, ":rand", 0, 100),
            (lt, ":rand", 25),
            (assign, ":cancel_cur_action", 1),
          (try_end),
#          (eq, ":is_besieging", 0),
          (eq, ":cancel_cur_action", 0),
          (assign, ":chance_stay", 100),
        (try_end),

##        (try_begin),
##          (eq, ":siege_going_badly", 1),
##          (assign, ":chance_besiege_enemy_center", 0),
##          (assign, ":chance_stay", 0),
##        (try_end),
##        (try_begin),
##          (eq, ":siege_going_well", 1),
##          (assign, ":chance_move_to_home_center", 0),
##          (assign, ":chance_move_to_other_center", 0),
##          (assign, ":chance_patrol_around_center", 0),
##          (assign, ":chance_besiege_enemy_center", 0),
##          (assign, ":chance_help_besieged_center", 0),
##        (try_end),

        (assign, ":sum_chances", ":chance_move_to_home_center"),
        (val_add, ":sum_chances", ":chance_move_to_other_center"),
        (val_add, ":sum_chances", ":chance_raid_around_center"),
        (val_add, ":sum_chances", ":chance_besiege_enemy_center"),
        (val_add, ":sum_chances", ":chance_patrol_around_center"),
        (val_add, ":sum_chances", ":chance_to_follow_other_party"),
        (val_add, ":sum_chances", ":chance_stay"),
        (store_random_in_range, ":random_no", 0, ":sum_chances"),
        (val_sub, ":random_no", ":chance_move_to_home_center"),
        (try_begin),
          (lt, ":random_no", 0),
          (party_set_ai_object, ":party_no", ":target_move_to_home_center"),
          (party_set_ai_behavior, ":party_no", ai_bhvr_travel_to_party),
          (party_set_slot, ":party_no", slot_party_ai_state, spai_holding_center),
          (party_set_slot, ":party_no", slot_party_ai_object, ":target_move_to_home_center"),
          (try_begin),
            (is_between, ":cur_center_no", centers_begin, centers_end),
            (party_detach, ":party_no"),
          (try_end),
          (party_set_flags, ":party_no", pf_default_behavior, 1),
          (party_set_slot, ":party_no", slot_party_commander_party, -1),
        (else_try),
          (val_sub, ":random_no", ":chance_move_to_other_center"),
          (lt, ":random_no", 0),
          (party_set_ai_object, ":party_no", ":target_move_to_other_center"),
          (party_set_ai_behavior, ":party_no", ai_bhvr_travel_to_party),
          (party_set_flags, ":party_no", pf_default_behavior, 0),
          (party_set_slot, ":party_no", slot_party_ai_state, spai_holding_center),
          (party_set_slot, ":party_no", slot_party_ai_object, ":target_move_to_other_center"),
          (try_begin),
            (is_between, ":cur_center_no", centers_begin, centers_end),
            (party_detach, ":party_no"),
          (try_end),
          (party_set_slot, ":party_no", slot_party_commander_party, -1),
        (else_try),
          (val_sub, ":random_no", ":chance_raid_around_center"),
          (lt, ":random_no", 0),
          (call_script, "script_party_set_ai_state", ":party_no", spai_raiding_around_center, ":target_raid_around_center"),
          (party_set_slot, ":party_no", slot_party_commander_party, -1),
        (else_try),
          (val_sub, ":random_no", ":chance_besiege_enemy_center"),
          (lt, ":random_no", 0),
          (call_script, "script_party_set_ai_state", ":party_no", spai_besieging_center, ":target_besiege_enemy_center"),
          (party_set_slot, ":party_no", slot_party_commander_party, -1),
        (else_try),
          (val_sub, ":random_no", ":chance_patrol_around_center"),
          (lt, ":random_no", 0),
          (party_set_ai_object, ":party_no", ":target_patrol_around_center"),
          (party_set_ai_behavior, ":party_no", ai_bhvr_patrol_party),
          (party_set_ai_patrol_radius, ":party_no", 5),
          (party_set_flags, ":party_no", pf_default_behavior, 0),
          (party_set_slot, ":party_no", slot_party_ai_state, spai_patrolling_around_center),
          (party_set_slot, ":party_no", slot_party_ai_object, ":target_patrol_around_center"),
          (try_begin),
            (is_between, ":cur_center_no", centers_begin, centers_end),
            (party_detach, ":party_no"),
          (try_end),
          (party_set_slot, ":party_no", slot_party_commander_party, -1),
        (else_try),
          (val_sub, ":random_no", ":chance_to_follow_other_party"),
          (lt, ":random_no", 0),
          (str_store_troop_name, s1, ":troop_no"),
          (str_store_party_name, s2, ":target_to_follow_other_party"),
#          (display_message, "@{s1} started to follow {s2}"),
          (party_set_slot, ":party_no", slot_party_commander_party, ":target_to_follow_other_party"),
        (try_end),
      (try_end),
  ]),
  


  # script_process_kingdom_parties_ai
  # This is called more frequently than decide_kingdom_parties_ai
  # Input: none
  # Output: none
  #called from triggers
  ("process_kingdom_parties_ai",
    [
       (try_for_range, ":troop_no", kingdom_heroes_begin, kingdom_heroes_end),
         (troop_slot_eq, ":troop_no", slot_troop_occupation, slto_kingdom_hero),
         (troop_slot_eq, ":troop_no", slot_troop_is_prisoner, 0),
         (troop_get_slot, ":party_no", ":troop_no", slot_troop_leaded_party),
         (gt, ":party_no", 0),
         (call_script, "script_process_hero_ai", ":troop_no"),
       (try_end),
  ]),
  


  # script_process_hero_ai
  # This is called more frequently than decide_kingdom_parties_ai
  # Input: none
  # Output: none
  #called from triggers
  ("process_hero_ai",
    [
        (store_script_param_1, ":troop_no"),
        (troop_get_slot, ":party_no", ":troop_no", slot_troop_leaded_party),
        (store_faction_of_party, ":faction_no", ":party_no"),
        (party_get_slot, ":ai_state", ":party_no", slot_party_ai_state),
        (party_get_slot, ":ai_object", ":party_no", slot_party_ai_object),
        (try_begin),
          (eq, ":ai_state", spai_besieging_center),
          (try_begin),
            (store_distance_to_party_from_party, ":distance", ":party_no", ":ai_object"),
            (lt, ":distance", 2),
            (try_begin),
              (party_slot_eq, ":ai_object", slot_center_is_besieged_by, -1),
              (party_set_slot, ":ai_object", slot_center_is_besieged_by, ":party_no"),
              (str_store_party_name, s1, ":ai_object"),
              (str_store_troop_name, s2, ":troop_no"),
              (str_store_faction_name, s3, ":faction_no"),
              (display_message, "@{s1} has been besieged by {s2} of {s3}."),
              (call_script, "script_village_set_state", ":ai_object", svs_under_siege),
            #give siege locations to followers...
            (try_end),
            (party_get_battle_opponent, ":opponent", ":party_no"),
            (lt, ":opponent", 0),
            (call_script, "script_party_calculate_regular_strength", ":party_no"),
            (assign, ":our_strength", reg0),
            (party_collect_attachments_to_party, ":ai_object", "p_collective_enemy"),
            (call_script, "script_party_calculate_regular_strength", "p_collective_enemy"),
            (assign, ":castle_strength", reg0),
#            (assign, ":start_attack", 0),
            (store_mul, ":three_times_castle_strength", ":castle_strength", 3),
            (store_mul, ":ten_times_castle_strength", ":castle_strength", 10),
            (assign, ":do_attack", 0),
            (try_begin),
              (gt, ":our_strength", ":three_times_castle_strength"),
              (store_random_in_range, ":rand", 0, 100),
              (this_or_next|lt, ":rand", 10),
              (gt, ":our_strength", ":ten_times_castle_strength"), #we have enough strength for an attack
              (assign, ":do_attack", 1),
            (try_end),
              
            (try_begin),
              (eq, ":do_attack", 1),
              (party_set_ai_behavior, ":party_no", ai_bhvr_attack_party),
              (party_set_ai_object, ":party_no", ":ai_object"),
              (party_set_flags, ":party_no", pf_default_behavior, 0),
            (else_try),
              (party_set_ai_behavior, ":party_no", ai_bhvr_hold),
              (party_set_flags, ":party_no", pf_default_behavior, 0),
            (try_end),
          (try_end),
        (else_try),
          (eq, ":ai_state", spai_raiding_around_center),
          (assign, ":done", 0),
          (try_for_range, ":enemy_village_no", villages_begin, villages_end),
            (eq, ":done", 0),
            (store_faction_of_party, ":enemy_village_faction", ":enemy_village_no"),
            (store_relation, ":reln", ":enemy_village_faction", ":faction_no"),
            (lt, ":reln", 0),
            (store_distance_to_party_from_party, ":dist", ":enemy_village_no", ":party_no"),
            (lt, ":dist", 15),
            (party_slot_eq, ":enemy_village_no", slot_village_state, 0), #village is not already raided
            #CHANGE STATE TO RAID THIS VILLAGE
            (call_script, "script_party_set_ai_state", ":party_no", spai_raiding_village, ":enemy_village_no"),
            (assign, ":done", 1),
#            (assign, ":ai_state", spai_raiding_village),
#            (assign, ":ai_object", ":enemy_village_no"),
#            (assign, ":last", -1),
          (try_end),
#          (ge, ":last", 0), #HACK: We make the script continue from the next block.
        (else_try),
          (eq, ":ai_state", spai_raiding_village),
          (try_begin),
            (store_distance_to_party_from_party, ":distance", ":party_no", ":ai_object"),
            (lt, ":distance", 2),
            (try_begin),
              (party_slot_eq, ":ai_object", slot_village_state, 0),
              (call_script, "script_village_set_state", ":ai_object", svs_being_raided),
              (party_set_slot, ":ai_object", slot_village_raided_by, ":party_no"),
            (else_try),
              (party_slot_eq, ":ai_object", slot_village_state, svs_being_raided),
            (else_try),
              #if anything other than being_raided leave
              (call_script, "script_party_set_ai_state", ":party_no", spai_raiding_around_center, ":ai_object"),
            (try_end),
          (try_end),
        (else_try),
          (eq, ":ai_state", spai_retreating_to_center),
          (try_begin),
            (party_get_battle_opponent, ":enemy_party", ":party_no"),
            (ge, ":enemy_party", 0), #we are in a battle! we may be caught in a loop!
            (call_script, "script_party_set_ai_state", ":party_no", spai_undefined, -1),
            (party_set_flags, ":party_no", pf_default_behavior, 0),
            (party_set_slot, ":party_no", slot_party_commander_party, -1),
          (try_end),
        (else_try),
          (eq, ":ai_state", spai_holding_center),
          (party_get_attached_to, ":cur_town", ":party_no"),
          # Make the party sortie outside, so that it will drive away any enemies??
          (try_begin),
            (is_between, ":cur_town", walled_centers_begin, walled_centers_end),
            (assign, ":sortie_chance", 50),
            (try_begin),
              (party_get_attached_to, ":cur_town", ":party_no"),
              (party_slot_ge, ":party_no", slot_center_is_besieged_by, 0), #town is under siege
              (assign, ":sortie_chance", 5),
            (try_end),
            (store_random_in_range, ":rand", 0, 100),
            (lt, ":rand", ":sortie_chance"),
            (assign, ":enemies_nearby", 0),
            (call_script, "script_party_calculate_regular_strength", ":party_no"),
            (assign, ":our_strength", reg0),
            (try_for_range, ":enemy_hero", kingdom_heroes_begin, kingdom_heroes_end),
              (store_troop_faction, ":enemy_hero_faction", ":enemy_hero"),
              (store_relation, ":reln", ":enemy_hero_faction", ":faction_no"),
              (lt, ":reln", -1),
              (troop_get_slot, ":enemy_party", ":enemy_hero", slot_troop_leaded_party),
              (gt, ":enemy_party", 0),
              (party_is_active, ":enemy_party"),
              (store_distance_to_party_from_party, ":dist", ":enemy_party", ":party_no"),
              (lt, ":dist", 7),
              (call_script, "script_party_calculate_regular_strength", "p_collective_enemy"),
              (gt, reg0, ":our_strength"),
              (assign, ":enemies_nearby", 1),
            (try_end),
            (eq, ":enemies_nearby", 0),
            (party_set_ai_behavior, ":party_no", ai_bhvr_travel_to_party),
            (party_set_ai_object, ":party_no", ":ai_object"),
            (party_set_flags, ":party_no", pf_default_behavior, 0),
            (party_detach, ":party_no"),
          (try_end),
        (try_end),
  ]),


  # script_decide_faction_ai
  # Input: arg1: faction_no
  # Output: none
  #called from triggers
  ("decide_faction_ai",
   [
       (store_script_param_1, ":faction_no"),
       (faction_get_slot, ":old_faction_ai_state", ":faction_no", slot_faction_ai_state),
       (faction_get_slot, ":old_faction_ai_object", ":faction_no", slot_faction_ai_object),
       (faction_get_slot, ":faction_leader", ":faction_no", slot_faction_leader),
       (troop_get_slot, ":faction_leader_party", ":faction_leader", slot_troop_leaded_party),
       
       (faction_get_slot, ":num_armies", ":faction_no", slot_faction_num_armies),
       (faction_get_slot, ":num_catles", ":faction_no", slot_faction_num_castles),
       (faction_get_slot, ":num_towns",  ":faction_no", slot_faction_num_towns),
       (store_add, ":num_centers", ":num_catles", ":num_towns"),
       (store_mul, ":offensive_capacity", ":num_armies", 100),
       (val_div,  ":offensive_capacity", ":num_centers"),


       (assign, ":ai_defend_weight", 0),
       (assign, ":ai_attack_center_weight", 0),
       (assign, ":ai_attack_center_target", -1),


       (try_begin),
         (assign, ":ai_defend_weight", 100),
       (try_end),
       (try_begin),
         (ge, ":faction_leader_party", 0),
         (gt, ":offensive_capacity", 60), #TODO: We may need to change this arbitrary figure.
         (try_begin),
           (eq, ":old_faction_ai_state", sfai_attacking_center),
           (assign, ":ai_attack_center_target", ":old_faction_ai_object"),
         (else_try),
           (gt, ":faction_leader_party", 0),
           (try_for_range, ":enemy_center", walled_centers_begin, walled_centers_end),
             (eq, ":ai_attack_center_target", -1),
             (store_faction_of_party, ":enemy_center_faction", ":enemy_center"),
             (store_relation, ":reln", ":enemy_center_faction", ":faction_no"),
             (lt, ":reln", -5),
             (store_distance_to_party_from_party, ":distance_to_center", ":enemy_center", ":faction_leader_party"),
             (lt, ":distance_to_center", 60),
             (store_random_in_range, ":rand", 0, 100),
             (lt, ":rand", 20),
             (assign, ":ai_attack_center_target", ":enemy_center"),
           (try_end),
         (try_end),
         (try_begin),
           (is_between, ":ai_attack_center_target", centers_begin, centers_end),
           (assign, ":ai_attack_center_weight", 50),
         (try_end),
       (try_end),

       (assign, ":sum_weights", 0),
       (val_add, ":sum_weights", ":ai_defend_weight"),
       (val_add, ":sum_weights", ":ai_attack_center_weight"),
       (store_random_in_range, ":random_no", 0, ":sum_weights"),
       (val_sub, ":random_no", ":ai_defend_weight"),
       (try_begin),
         (lt, ":random_no", 0),
         (faction_set_slot, ":faction_no", slot_faction_ai_state, sfai_default),
         (faction_set_slot, ":faction_no", slot_faction_ai_object, -1),
       (else_try),
         (val_sub, ":random_no", ":ai_attack_center_weight"),
         (lt, ":random_no", 0),
         (faction_set_slot, ":faction_no", slot_faction_ai_state, sfai_attacking_center),
         (faction_set_slot, ":faction_no", slot_faction_ai_object, ":ai_attack_center_target"),
         (str_store_faction_name, s1, ":faction_no"),
         (str_store_party_name, s2, ":ai_attack_center_target"),
#         (display_log_message, "@{s1} has decided to attack {s2}"),
       (try_end),
  ]),

  
  #  # script_troop_get_personality_stance_to_player
  #  # Input: arg1 = troop_no
  #  # Output: reg0 = personality_adder
  #  ("troop_get_personality_stance_to_player",
  #    [
  #      (store_script_param_1, ":troop_no"),
  #      (assign, ":total_stance", 0),
  #      (troop_get_slot, ":troop_merciful", ":troop_no", slot_troop_personality_merciful),
  #      (store_mul, ":mercifulness_stance", "$g_reputation_merciful", ":troop_merciful"),
  #      (val_add, ":total_stance", ":mercifulness_stance"),
  #      (troop_get_slot, ":troop_honorable", ":troop_no", slot_troop_personality_honorable),
  #      (store_mul, ":honor_stance", "$g_reputation_honorable", ":troop_honorable"),
  #      (val_add, ":total_stance", ":honor_stance"),
  #      (assign, reg0, ":total_stance"),
  #  ]),
  
  # script_change_troop_renown
  # Input: arg1 = troop_no, arg2 = relation difference
  # Output: none
  ("change_troop_renown",
    [
      (store_script_param_1, ":troop_no"),
      (store_script_param_2, ":renown_change"),
      
      (troop_get_slot, ":old_renown", ":troop_no", slot_troop_renown),
      (store_add, ":new_renown", ":old_renown", ":renown_change"),
      (val_max, ":new_renown", 0),
      (troop_set_slot, ":troop_no", slot_troop_renown, ":new_renown"),

      (try_begin),
        (eq, ":troop_no", "trp_player"),
        (str_store_troop_name, s1, ":troop_no"),
        (assign, reg12, ":renown_change"),
        (val_abs, reg12),
        (try_begin),
         (gt, ":renown_change", 0),
         (display_message, "@You gained {reg12} renown."),
        (else_try),
          (lt, ":renown_change", 0),
          (display_message, "@You loose {reg12} renown."),
        (try_end),
      (try_end),
      (call_script, "script_update_troop_notes", ":troop_no"),
  ]),
  
  
  # script_change_player_relation_with_troop
  # Input: arg1 = troop_no, arg2 = relation difference
  # Output: none
  ("change_player_relation_with_troop",
    [
      (store_script_param_1, ":troop_no"),
      (store_script_param_2, ":difference"),
      
      (troop_get_slot, ":player_relation", ":troop_no", slot_troop_player_relation),
      (troop_get_slot, ":player_favor", ":troop_no", slot_troop_player_favor),
      (assign, reg1, ":player_relation"),
      (val_add, ":player_relation", ":difference"),
      (val_clamp, ":player_relation", -100, 100),
      (assign, reg2, ":player_relation"),
      (val_add, ":player_favor", ":difference"),
      (val_add, ":player_favor", ":difference"),
      (troop_set_slot, ":troop_no", slot_troop_player_relation, ":player_relation"),
      (troop_set_slot, ":troop_no", slot_troop_player_favor, ":player_favor"),
      
      (str_store_troop_name, s1, ":troop_no"),
      (try_begin),
        (gt, ":difference", 0),
        (display_message, "str_troop_relation_increased"),
      (else_try),
        (lt, ":difference", 0),
        (display_message, "str_troop_relation_detoriated"),
      (try_end),

      (try_begin),
        (eq, ":troop_no", "$g_talk_troop"),
        (assign, "$g_talk_troop_relation", ":player_relation"),
        (call_script, "script_setup_talk_info"),
      (try_end),
  ]),

  # script_change_player_relation_with_center
  # Input: arg1 = party_no, arg2 = relation difference
  # Output: none
  ("change_player_relation_with_center",
    [
      (store_script_param_1, ":center_no"),
      (store_script_param_2, ":difference"),
      
      (party_get_slot, ":player_relation", ":center_no", slot_center_player_relation),
      (assign, reg1, ":player_relation"),
      (val_add, ":player_relation", ":difference"),
      (val_clamp, ":player_relation", -100, 100),
      (assign, reg2, ":player_relation"),
      (party_set_slot, ":center_no", slot_center_player_relation, ":player_relation"),
      
      (str_store_party_name, s1, ":center_no"),
      (try_begin),
        (gt, ":difference", 0),
        (display_message, "@Your relation with {s1} has improved."),
      (else_try),
        (lt, ":difference", 0),
        (display_message, "@Your relation with {s1} has deteriorated."),
      (try_end),
      (try_begin),
        (party_slot_eq, ":center_no", slot_party_type, spt_village),
        (call_script, "script_update_volunteer_troops_in_village", ":center_no"),
      (try_end),
  ]),
  
  # script_change_player_favor_of_troop
  # Input: arg1 = troop_no, arg2 = favor difference
  # Output: none
  ("change_player_favor_of_troop",
    [
      (store_script_param_1, ":troop_no"),
      (store_script_param_2, ":difference"),
      
      (troop_get_slot, ":player_favor", ":troop_no", slot_troop_player_favor),
      (val_add, ":player_favor", ":difference"),
      (troop_set_slot, ":troop_no", slot_troop_player_favor, ":player_favor"),
  ]),
  
##  # script_change_player_relation_with_faction
##  # Input: arg1 = faction_no, arg2 = relation difference
##  # Output: none
##  ("change_player_relation_with_faction",
##    [
##      (store_script_param_1, ":faction_no"),
##      (store_script_param_2, ":difference"),
##      
##      (store_relation, ":player_relation", ":faction_no", "fac_player_faction"),
##      (assign, reg1, ":player_relation"),
##      (val_add, ":player_relation", ":difference"),
##      (assign, reg2, ":player_relation"),
##      (set_relation, ":faction_no", "fac_player_faction", ":player_relation"),
##      
##      #      (str_store_faction_name, s1, ":faction_no"),
##      #      (try_begin),
##      #        (gt, ":difference", 0),
##      #        (display_message, "str_faction_relation_increased"),
##      #      (else_try),
##      #        (lt, ":difference", 0),
##      #        (display_message, "str_faction_relation_detoriated"),
##      #      (try_end),
##  ]),

  
  
  # script_change_player_relation_with_faction_ex
  # changes relations with other factions also (according to their relations between each other)
  # Input: arg1 = faction_no, arg2 = relation difference
  # Output: none
  ("change_player_relation_with_faction_ex",
    [
      (store_script_param_1, ":faction_no"),
      (store_script_param_2, ":difference"),
      
      (store_relation, ":player_relation", ":faction_no", "fac_player_faction"),
      (assign, reg1, ":player_relation"),
      (val_add, ":player_relation", ":difference"),
      (assign, reg2, ":player_relation"),
      (set_relation, ":faction_no", "fac_player_faction", ":player_relation"),
      
      (str_store_faction_name, s1, ":faction_no"),
      (try_begin),
        (gt, ":difference", 0),
        (display_message, "str_faction_relation_increased"),
      (else_try),
        (lt, ":difference", 0),
        (display_message, "str_faction_relation_detoriated"),
      (try_end),
      
      (try_for_range, ":other_faction", kingdoms_begin, kingdoms_end),
        (neq, ":faction_no", ":other_faction"),
        (store_relation, ":other_faction_relation", ":faction_no", ":other_faction"),
        (store_relation, ":player_relation", ":other_faction", "fac_player_faction"),
        (store_mul, ":relation_change", ":difference", ":other_faction_relation"),
        (val_div, ":relation_change", 100),
        (val_add, ":player_relation", ":relation_change"),
        (set_relation, ":other_faction", "fac_player_faction", ":player_relation"),
      (try_end),
  ]),

  # script_make_kingdom_hostile_to_player
  # Input: arg1 = faction_no, arg2 = relation difference
  # Output: none
  ("make_kingdom_hostile_to_player",
    [
      (store_script_param_1, ":input_faction"),
      (store_script_param_2, ":difference"),

      (try_begin),
        (lt, ":difference", 0),
        (faction_get_slot, ":top_kingdom", ":input_faction", slot_faction_vassal_of),
        (try_begin),
          (le, ":top_kingdom", 0),
          (assign, ":top_kingdom", ":input_faction"),
        (try_end),

        (try_for_range, ":kingdom_no", kingdoms_begin, kingdoms_end),
          (faction_get_slot, ":liege", ":kingdom_no", slot_faction_vassal_of),
          (this_or_next|eq, ":liege", ":top_kingdom"),
          (eq, ":kingdom_no", ":top_kingdom"),

          (store_relation, ":player_relation", ":kingdom_no", "fac_player_faction"),
          (val_min, ":player_relation", 0),
          (val_add, ":player_relation", ":difference"),
          (set_relation, ":kingdom_no", "fac_player_faction", ":player_relation"),
        (try_end),
      (try_end),
  ]),
  
  # script_change_player_honor
  # Input: arg1 = honor difference
  # Output: none
  ("change_player_honor",
    [
      (store_script_param_1, ":honor_dif"),

      (val_mul, ":honor_dif", 1000),
      (assign, ":temp_honor", 0),
      (assign, ":num_nonlinear_steps", 10),
      (try_begin),
        (gt, "$player_honor", 0),
        (lt, ":honor_dif", 0),
        (assign, ":num_nonlinear_steps", 0),
      (else_try),
        (lt, "$player_honor", 0),
        (gt, ":honor_dif", 0),
        (assign, ":num_nonlinear_steps", 3),
      (try_end),
      
      (try_begin),
        (ge, "$player_honor", 0),
        (assign, ":temp_honor", "$player_honor"),
      (try_begin),
        (val_sub, ":temp_honor", "$player_honor"),
      (try_end),
      (try_for_range, ":unused",0,":num_nonlinear_steps"),
        (ge, ":temp_honor", 10000),
        (val_div, ":temp_honor", 2),
        (val_div, ":honor_dif", 2),
      (try_end),
      (val_add, "$player_honor", ":honor_dif"),
  ]),

  # script_change_player_party_morale
  # Input: arg1 = morale difference
  # Output: none
  ("change_player_party_morale",
    [
      (store_script_param_1, ":morale_dif"),
      (party_get_morale, ":cur_morale", "p_main_party"),
      (store_add, ":new_morale", ":cur_morale", ":morale_dif"),
      (val_clamp, ":new_morale", 0, 100),
      (party_set_morale, "p_main_party", ":new_morale"),
      (try_begin),
        (lt, ":new_morale", ":cur_morale"),
        (store_sub, reg1, ":cur_morale", ":new_morale"),
        (display_message, "str_party_lost_morale"),
      (else_try),
        (gt, ":new_morale", ":cur_morale"),
        (store_sub, reg1, ":new_morale", ":cur_morale"),
        (display_message, "str_party_gained_morale"),
      (try_end),
  ]),

  # script_get_player_party_morale_values
  # Output: reg0 = player_party_morale_target
  ("get_player_party_morale_values",
    [
      (party_get_num_companion_stacks, ":num_stacks","p_main_party"),
      (assign, ":num_men", 0),
      (try_for_range, ":i_stack", 0, ":num_stacks"),
        (party_stack_get_troop_id, ":stack_troop","p_main_party",":i_stack"),
        (try_begin),
          (troop_is_hero, ":stack_troop"),
          (val_add, ":num_men", 3),
        (else_try),
          (party_stack_get_size, ":stack_size","p_main_party",":i_stack"),
          (val_add, ":num_men", ":stack_size"),
        (try_end),
      (try_end),
      (assign, "$g_player_party_morale_modifier_party_size", ":num_men"),
    
      (store_skill_level, ":player_leadership", "skl_leadership", "trp_player"),
      (store_mul, "$g_player_party_morale_modifier_leadership", ":player_leadership", 5),
      (assign, ":new_morale", "$g_player_party_morale_modifier_leadership"),
      (val_sub, ":new_morale", "$g_player_party_morale_modifier_party_size"),
      (val_add, ":new_morale", 50),

      (assign, ":available_food", 0),
      (assign, "$g_player_party_morale_modifier_food", 0),
      (try_for_range, ":cur_edible", morale_boosters_begin, morale_boosters_end),
        (player_has_item, ":cur_edible"),
        (try_begin),
          (is_between, ":cur_edible", food_begin, food_end),
          (val_add, ":available_food", 1),
        (try_end),
        (item_get_slot, ":food_bonus", ":cur_edible", slot_item_food_bonus),
        (val_add, "$g_player_party_morale_modifier_food", ":food_bonus"),
      (try_end),
      (val_add, ":new_morale", "$g_player_party_morale_modifier_food"),

      (try_begin),
        (eq, ":available_food", 0),
        (assign, "$g_player_party_morale_modifier_no_food", 30),
        (val_sub, ":new_morale", "$g_player_party_morale_modifier_no_food"),
      (else_try),
        (assign, "$g_player_party_morale_modifier_no_food", 0),
      (try_end),

      (assign, "$g_player_party_morale_modifier_debt", 0),
      (try_begin),
        (gt, "$g_player_debt_to_party_members", 0),
        (call_script, "script_calculate_player_faction_wage"),
        (assign, ":total_wages", reg0),
        (store_mul, "$g_player_party_morale_modifier_debt", "$g_player_debt_to_party_members", 10),
        (val_div, "$g_player_party_morale_modifier_debt", ":total_wages"),
        (val_clamp, "$g_player_party_morale_modifier_debt", 1, 31),
        (val_sub, ":new_morale", "$g_player_party_morale_modifier_debt"),
      (try_end),

      (val_clamp, ":new_morale", 0, 100),
      (assign, reg0, ":new_morale"),
      ]),
  


  # script_diplomacy_start_war_between_kingdoms
  ("diplomacy_start_war_between_kingdoms", #sets relations between two kingdoms and their vassals.
    [
      (store_script_param_1, ":kingdom_a"),
      (store_script_param_2, ":kingdom_b"),
      
      (store_relation, ":relation", ":kingdom_a", ":kingdom_b"),
      (val_min, ":relation", -10),
      (val_add, ":relation", -30),
      (set_relation, ":kingdom_a", ":kingdom_b", ":relation"),
      
      (try_begin),
        (eq, "$players_kingdom", ":kingdom_a"),
        (store_relation, ":relation", "fac_player_faction", ":kingdom_b"),
        (val_min, ":relation", -30),
        (set_relation, "fac_player_faction", ":kingdom_b", ":relation"),
      (else_try),
        (eq, "$players_kingdom", ":kingdom_b"),
        (store_relation, ":relation", "fac_player_faction", ":kingdom_a"),
        (val_min, ":relation", -30),
        (set_relation, "fac_player_faction", ":kingdom_a", ":relation"),
      (try_end),
  ]),

  # script_diplomacy_start_peace_between_kingdoms
  # Input: arg1 = kingdom_1, arg2 = kingdom_2
  # Output: none
  ("diplomacy_start_peace_between_kingdoms", #sets relations between two kingdoms and their vassals.
    [
      (store_script_param_1, ":kingdom_a"),
      (store_script_param_2, ":kingdom_b"),

      (store_relation, ":relation", ":kingdom_a", ":kingdom_b"),
      (val_max, ":relation", 0),
      (set_relation, ":kingdom_a", ":kingdom_b", ":relation"),
      (call_script, "script_exchange_prisoners_between_factions", ":kingdom_a", ":kingdom_b"),
      
      (try_begin),
        (eq, "$players_kingdom", ":kingdom_a"),
        (store_relation, ":relation", "fac_player_faction", ":kingdom_b"),
        (val_max, ":relation", 0),
        (set_relation, "fac_player_faction", ":kingdom_b", ":relation"),
        (call_script, "script_event_kingdom_make_peace_with_kingdom", ":kingdom_b", "fac_player_faction"),
      (else_try),
        (eq, "$players_kingdom", ":kingdom_b"),
        (store_relation, ":relation", "fac_player_faction", ":kingdom_a"),
        (val_max, ":relation", 0),
        (set_relation, "fac_player_faction", ":kingdom_a", ":relation"),
        (call_script, "script_event_kingdom_make_peace_with_kingdom", ":kingdom_a", "fac_player_faction"),
      (try_end),

      (call_script, "script_event_kingdom_make_peace_with_kingdom", ":kingdom_a", ":kingdom_b"),
      (call_script, "script_event_kingdom_make_peace_with_kingdom", ":kingdom_b", ":kingdom_a"),
  ]),

  # script_event_kingdom_make_peace_with_kingdom
  # Input: arg1 = source_kingdom, arg2 = target_kingdom
  # Output: none
  ("event_kingdom_make_peace_with_kingdom",
    [
      (store_script_param_1, ":source_kingdom"),
      (store_script_param_2, ":target_kingdom"),
      (try_begin),
        (faction_get_slot, ":ai_center", ":source_kingdom", slot_faction_ai_object),
        (gt, ":ai_center", 0),
        (store_faction_of_party, ":ai_faction", ":ai_center"),
        (eq, ":ai_faction", ":target_kingdom"),
        (faction_set_slot, ":source_kingdom", slot_faction_ai_state, 0),
      (try_end),
  ]),


  ("diplomacy_make_kingdom_vassal_of_kingdom",
    [
      (store_script_param_1, ":vassal_kingdom"),
      (store_script_param_2, ":protector_kingdom"),
      (store_relation, ":cur_relation", ":vassal_kingdom", ":protector_kingdom"),
      (val_max, ":cur_relation", 0),
      (set_relation, ":vassal_kingdom", ":protector_kingdom", ":cur_relation"),
      (call_script, "script_exchange_prisoners_between_factions", ":vassal_kingdom", ":protector_kingdom"),
      (try_for_range, ":cur_kingdom", kingdoms_begin, kingdoms_end),
        (faction_get_slot, ":cur_liege", ":cur_kingdom", slot_faction_vassal_of),
        (try_begin),
          (eq, ":cur_liege", ":protector_kingdom"),
          (store_relation, ":cur_relation", ":vassal_kingdom", ":cur_kingdom"),
          (val_max, ":cur_relation", 0),
          (set_relation, ":vassal_kingdom", ":cur_kingdom", ":cur_relation"),
          (call_script, "script_exchange_prisoners_between_factions", ":vassal_kingdom", ":cur_kingdom"),
        (else_try),
          (neq, ":cur_liege", ":vassal_kingdom"),
          (store_relation, ":cur_relation", ":protector_kingdom", ":cur_kingdom"),
          (set_relation, ":vassal_kingdom", ":cur_kingdom", ":cur_relation"),
          (ge, ":cur_relation", 0),
          (call_script, "script_exchange_prisoners_between_factions", ":vassal_kingdom", ":cur_kingdom"),
        (try_end),
      (try_end),
      (try_begin),
        (eq, "$players_kingdom", ":protector_kingdom"),
        (store_relation, ":cur_relation", ":vassal_kingdom", "fac_player_faction"),
        (val_max, ":cur_relation", 0),
        (set_relation, ":vassal_kingdom", "fac_player_faction", ":cur_relation"),
      (else_try),
        (neq, "$players_kingdom", ":vassal_kingdom"),
        (store_relation, ":cur_relation", ":protector_kingdom", "fac_player_faction"),
        (set_relation, ":vassal_kingdom", "fac_player_faction", ":cur_relation"),
      (try_end),
      
      (faction_set_slot, ":vassal_kingdom", slot_faction_vassal_of, ":protector_kingdom"),
      (try_for_range, ":cur_kingdom", kingdoms_begin, kingdoms_end),
        (faction_get_slot, ":cur_liege", ":cur_kingdom", slot_faction_vassal_of),
        (eq, ":cur_liege", ":vassal_kingdom"),
        (call_script, "script_diplomacy_make_kingdom_vassal_of_kingdom", ":cur_kingdom", ":protector_kingdom"),
      (try_end),
  ]),

# script_exchange_prisoners_between_factions
# Input: arg1 = faction_no_1, arg2 = faction_no_2
  ("exchange_prisoners_between_factions",
   [
       (store_script_param_1, ":faction_no_1"),
       (store_script_param_2, ":faction_no_2"),

       (try_for_parties, ":party_no"),
         (store_faction_of_party, ":party_faction_local", ":party_no"),
         (this_or_next|eq, ":party_faction_local", ":faction_no_1"),
         (eq, ":party_faction_local", ":faction_no_2"),
         (party_get_num_prisoner_stacks, ":num_stacks", ":party_no"),
         (try_for_range_backwards, ":troop_iterator", 0, ":num_stacks"),
           (party_prisoner_stack_get_troop_id, ":cur_troop_id", ":party_no", ":troop_iterator"),
           (store_troop_faction, ":cur_faction", ":cur_troop_id"),
           (this_or_next|eq, ":cur_faction", ":faction_no_1"),
           (eq, ":cur_faction", ":faction_no_2"),
           (try_begin),
             (troop_is_hero, ":cur_troop_id"),
             (troop_set_slot, ":cur_troop_id", slot_troop_is_prisoner, 0),
           (try_end),
           (party_prisoner_stack_get_size, ":stack_size",":party_no",":troop_iterator"),
           (party_remove_prisoners, ":party_no", ":troop_iterator", ":stack_size"),
        (try_end),
    ]),
  
##  # script_succeed_quest
##  # Input: arg1 = quest_no, arg2 = finish_percentage
##  # Output: none
##  ("succeed_quest",
##    [
##      (store_script_param_1, ":quest_no"),
##      (store_script_param_2, ":finish_percentage"),
##      
##      (quest_get_slot, ":quest_giver", ":quest_no", slot_quest_giver_troop),
##      (quest_get_slot, ":quest_importance", ":quest_no", slot_quest_importance),
##      (quest_get_slot, ":quest_xp_reward", ":quest_no", slot_quest_xp_reward),
##      (quest_get_slot, ":quest_gold_reward", ":quest_no", slot_quest_gold_reward),
##      
##      (try_begin),
##        (lt, ":finish_percentage", 100),
##        (val_mul, ":quest_xp_reward", ":finish_percentage"),
##        (val_div, ":quest_xp_reward", 100),
##        (val_mul, ":quest_gold_reward", ":finish_percentage"),
##        (val_div, ":quest_gold_reward", 100),
##        #Changing the relation factor. Negative relation if less than 75% of the quest is finished.
##        #Positive relation if more than 75% of the quest is finished.
##        (assign, ":importance_multiplier", ":finish_percentage"),
##        (val_sub, ":importance_multiplier", 75),
##        (val_mul, ":quest_importance", ":importance_multiplier"),
##        (val_div, ":quest_importance", 100),
##      (else_try),
##        (val_div, ":quest_importance", 4),
##        (val_add, ":quest_importance", 1),
##        (call_script, "script_change_player_relation_with_troop", ":quest_giver", ":quest_importance"),
##      (try_end),
##      
##      (add_xp_as_reward, ":quest_xp_reward"),
##      (troop_add_gold, "trp_player", ":quest_gold_reward"),
##      (complete_quest,":quest_no"),
##  ]),
  
  
  # script_get_information_about_troops_position
  # Input: arg1 = troop_no, arg2 = time (0 if present tense, 1 if past tense)
  # Output: s1 = String, reg0 = knows-or-not
  ("get_information_about_troops_position",
    [
      (store_script_param_1, ":troop_no"),
      (store_script_param_2, reg3),
      (troop_get_type, reg4, ":troop_no"),
      (str_store_troop_name_link, s2, ":troop_no"),
      
      (assign, ":found", 0),
      (troop_get_slot, ":center_no", ":troop_no", slot_troop_cur_center),
      (try_begin),
        (gt, ":center_no", 0),
        (is_between, ":center_no", centers_begin, centers_end),
        (str_store_party_name_link, s3, ":center_no"),
        (str_store_string, s1, "@{s2} {reg3?was:is currently} at {s3}."),
        (assign, ":found", 1),
      (else_try),
        (troop_get_slot, ":party_no", ":troop_no", slot_troop_leaded_party),
        (gt, ":party_no", 0),
        (call_script, "script_get_troop_attached_party", ":troop_no"),
        (assign, ":center_no", reg0),
        (try_begin),
          (is_between, ":center_no", centers_begin, centers_end),
          (str_store_party_name_link, s3, ":center_no"),
          (str_store_string, s1, "@{s2} {reg3?was:is currently} at {s3}."),
          (assign, ":found", 1),
        (else_try),
          (get_party_ai_behavior, ":ai_behavior", ":party_no"),
          (eq, ":ai_behavior", ai_bhvr_travel_to_party),
          (get_party_ai_object, ":ai_object", ":party_no"),
          (is_between, ":ai_object", centers_begin, centers_end),
          (call_script, "script_get_closest_center", ":party_no"),
          (str_store_party_name_link, s4, reg0),
          (str_store_party_name_link, s3, ":ai_object"),
          (str_store_string, s1, "@{s2} {reg3?was:is} travelling to {s3} and {reg4?she:he} {reg3?was:should be} close to {s4}{reg3?: at the moment}."),
          (assign, ":found", 1),
        (else_try),
          (call_script, "script_get_closest_center", ":party_no"),
          (str_store_party_name_link, s3, reg0),
          (str_store_string, s1, "@{s2} {reg3?was:is} in wilderness and {reg4?she:he} {reg3?was:should be} close to {s3}{reg3?: at the moment}."),
          (assign, ":found", 1),
        (try_end),
      (try_end),
      (try_begin),
        (eq, ":found", 0),
        (str_store_string, s1, "@{reg3?{s2}'s location was unknown:I don't know where {s2} is}."),
      (try_end),
      (assign, reg0, ":found"),
  ]),

  # script_recruit_troop_as_companion
  # Input: arg1 = troop_no,
  # Output: none
  ("recruit_troop_as_companion",
    [
      (store_script_param_1, ":troop_no"),
      (troop_set_slot, ":troop_no", slot_troop_occupation, slto_player_companion),
      (troop_set_auto_equip, ":troop_no",0),
      (party_add_members, "p_main_party", ":troop_no", 1),
      (str_store_troop_name, s6, ":troop_no"),
      (display_message, "@{s6} has joined your party"),
  ]),
  

  # script_setup_random_scene
  # Input: arg1 = center_no, arg2 = mission_template_no
  # Output: none
  ("setup_random_scene",
    [
      (party_get_current_terrain, ":terrain_type", "p_main_party"),
      (assign, ":scene_to_use", "scn_random_scene"),
      (try_begin),
        (eq, ":terrain_type", rt_steppe),
        (assign, ":scene_to_use", "scn_random_scene_steppe"),
        (assign, "$current_terrain",0),##SG ji ce
      (else_try),
        (eq, ":terrain_type", rt_plain),
        (assign, ":scene_to_use", "scn_random_scene_plain"),
        (assign, "$current_terrain",0),##SG ji ce
      (else_try),
        (eq, ":terrain_type", rt_snow),
        (assign, ":scene_to_use", "scn_random_scene_snow"),
        (assign, "$current_terrain",1),##SG ji ce
      (else_try),
        (eq, ":terrain_type", rt_desert),
        (assign, ":scene_to_use", "scn_random_scene_desert"),
        (assign, "$current_terrain",1),##SG ji ce
      (else_try),
        (eq, ":terrain_type", rt_steppe_forest),
        (assign, ":scene_to_use", "scn_random_scene_steppe_forest"),
        (assign, "$current_terrain",2),##SG ji ce
      (else_try),
        (eq, ":terrain_type", rt_forest),
        (assign, ":scene_to_use", "scn_random_scene_plain_forest"),
        (assign, "$current_terrain",2),##SG ji ce
      (else_try),
        (eq, ":terrain_type", rt_snow_forest),
        (assign, ":scene_to_use", "scn_random_scene_snow_forest"),
        (assign, "$current_terrain",3),##SG ji ce
      (else_try),
        (eq, ":terrain_type", rt_desert_forest),
        (assign, ":scene_to_use", "scn_random_scene_desert_forest"),
        (assign, "$current_terrain",2),##SG ji ce
      (try_end),
      (jump_to_scene,":scene_to_use"),
  ]),

  # script_enter_dungeon
  # Input: arg1 = center_no, arg2 = mission_template_no
  # Output: none
  ("enter_dungeon",
    [
      (store_script_param_1, ":center_no"),
      (store_script_param_2, ":mission_template_no"),
      
      (set_jump_mission,":mission_template_no"),
      (party_get_slot, ":dungeon_scene", ":center_no", slot_town_prison),
      
      (modify_visitors_at_site,":dungeon_scene"),(reset_visitors),
      (assign, ":cur_pos", 16),
      (call_script, "script_get_heroes_attached_to_center_as_prisoner", ":center_no", "p_temp_party"),
      (party_get_num_companion_stacks, ":num_stacks","p_temp_party"),
      (try_for_range, ":i_stack", 0, ":num_stacks"),
        (party_stack_get_troop_id, ":stack_troop","p_temp_party",":i_stack"),
        (lt, ":cur_pos", 32), # spawn up to entry point 32
        (set_visitor, ":cur_pos", ":stack_troop"),
        (val_add,":cur_pos", 1),
      (try_end),
      
      (set_jump_entry, 0),
      (jump_to_scene,":dungeon_scene"),
      (scene_set_slot, ":dungeon_scene", slot_scene_visited, 1),
      (change_screen_mission),
  ]),
  
  # script_enter_court
  # Input: arg1 = center_no
  # Output: none
  ("enter_court",
    [
      (store_script_param_1, ":center_no"),
      
      (set_jump_mission,"mt_visit_town_castle"),
      (party_get_slot, ":castle_scene", ":center_no", slot_town_castle),
      (modify_visitors_at_site,":castle_scene"),(reset_visitors),
      (assign, ":cur_pos", 16),
      (call_script, "script_get_heroes_attached_to_center", ":center_no", "p_temp_party"),
      (party_get_num_companion_stacks, ":num_stacks","p_temp_party"),
      (try_for_range, ":i_stack", 0, ":num_stacks"),
        (party_stack_get_troop_id, ":stack_troop","p_temp_party",":i_stack"),
        (lt, ":cur_pos", 32), # spawn up to entry point 32
        (set_visitor, ":cur_pos", ":stack_troop"),
        (val_add,":cur_pos", 1),
      (try_end),
# TODO: Disabling ladies for the time being.
##      (try_for_range, ":cur_troop", heroes_begin, heroes_end),
##        (troop_slot_eq, ":cur_troop", slot_troop_cur_center, ":center_no"),
##        (lt, ":cur_pos", 32), # spawn up to entry point 32
##        (set_visitor, ":cur_pos", ":cur_troop"),
##        (val_add,":cur_pos", 1),
##      (try_end),
      (jump_to_scene,":castle_scene"),
      (scene_set_slot, ":castle_scene", slot_scene_visited, 1),
      (change_screen_mission),
  ]),


  # script_find_high_ground_around_pos1
  # Input: pos1 should hold center_position_no
  #        arg1: search_radius (in meters)
  # Output: pos52 contains highest ground within <search_radius> meters of team leader
  # Destroys position registers: pos10, pos11, pos15
  ("find_high_ground_around_pos1",
    [
      (store_script_param_1, ":search_radius"),
      (val_mul, ":search_radius", 100),
      (get_scene_boundaries, pos10,pos11),
      (team_get_leader, ":ai_leader", "$ai_team"),
      (agent_get_position, pos1, ":ai_leader"),
      (set_fixed_point_multiplier, 100),
      (position_get_x, ":o_x", pos1),
      (position_get_y, ":o_y", pos1),
      (store_sub, ":min_x", ":o_x", ":search_radius"),
      (store_sub, ":min_y", ":o_y", ":search_radius"),
      (store_add, ":max_x", ":o_x", ":search_radius"),
      (store_add, ":max_y", ":o_y", ":search_radius"),
      (position_get_x, ":scene_min_x", pos10),
      (position_get_x, ":scene_max_x", pos11),
      (position_get_y, ":scene_min_y", pos10),
      (position_get_y, ":scene_max_y", pos11),
      (val_max, ":min_x", ":scene_min_x"),
      (val_max, ":min_y", ":scene_min_y"),
      (val_min, ":max_x", ":scene_max_x"),
      (val_min, ":max_y", ":scene_max_y"),
      
      (store_div, ":min_x_meters", ":min_x", 100),
      (store_div, ":min_y_meters", ":min_y", 100),
      (store_div, ":max_x_meters", ":max_x", 100),
      (store_div, ":max_y_meters", ":max_y", 100),
      
      (assign, ":highest_pos_z", -10000),
      (copy_position, pos52, pos1),
      (init_position, pos15),
      
      (try_for_range, ":i_x", ":min_x_meters", ":max_x_meters"),
        (store_mul, ":i_x_cm", ":i_x", 100),
        (try_for_range, ":i_y", ":min_y_meters", ":max_y_meters"),
          (store_mul, ":i_y_cm", ":i_y", 100),
          (position_set_x, pos15, ":i_x_cm"),
          (position_set_y, pos15, ":i_y_cm"),
          (position_set_z, pos15, 10000),
          (position_set_z_to_ground_level, pos15),
          (position_get_z, ":cur_pos_z", pos15),
          (try_begin),
            (gt, ":cur_pos_z", ":highest_pos_z"),
            (copy_position, pos52, pos15),
            (assign, ":highest_pos_z", ":cur_pos_z"),
          (try_end),
        (try_end),
      (try_end),
  ]),
  
  # script_select_battle_tactic
  # Input: none
  # Output: none
  ("select_battle_tactic",
    [
      (assign, "$ai_battle_tactic", 0),
      (assign,":defense_not_an_option",0),
      (try_begin),
        (eq, "$cant_leave_encounter", 1),
        #        (encountered_party_is_attacker),
        (assign,":defense_not_an_option",1),
      (try_end),
      (get_player_agent_no, ":player_agent"),
      (agent_get_team, ":player_team", ":player_agent"),
      #Note that enemy is the player here.
      (assign,":enemy_team",":player_team"),
      (try_begin),
        (eq, ":player_team", 0),
        (assign, "$ai_team", 1),
      (else_try),
        (assign, "$ai_team", 0),
      (try_end),
#      (store_sub,"$ai_team",":player_team", 1),
      (call_script, "script_team_get_class_percentages", "$ai_team"),
      #      (assign, ":ai_perc_infantry", reg0),
      (assign, ":ai_perc_archers",  reg1),
      (assign, ":ai_perc_cavalry",  reg2),
      (call_script, "script_team_get_class_percentages", ":enemy_team"),
      #      (assign, ":enemy_perc_infantry", reg0),
      #      (assign, ":enemy_perc_archers",  reg1),
      #      (assign, ":enemy_perc_cavalry",  reg2),

      (store_random_in_range, ":rand", 0, 100),      
      (try_begin),
        (this_or_next|lt, ":rand", 20),
        (party_slot_eq, "$g_enemy_party", slot_party_type, spt_kingdom_hero_party),
        (try_begin),
          (eq,":defense_not_an_option",0),
          (gt, ":ai_perc_archers",  50),
          (assign, "$ai_battle_tactic", btactic_hold),
        (else_try),
          (lt, ":rand", 20), #TODO: Increase this
          (lt, ":ai_perc_cavalry",  75),
          (assign, "$ai_battle_tactic", btactic_follow_leader),
        (try_end),
      (try_end),
  ]),
  
  # script_battle_tactic_init
  # Input: none
  # Output: none
  ("battle_tactic_init",
    [
      (team_get_leader, ":ai_leader", "$ai_team"),
      (try_begin),
        (eq, "$ai_battle_tactic", btactic_hold),
        (agent_get_position, pos1, ":ai_leader"),
        (call_script, "script_find_high_ground_around_pos1", 30),
        (copy_position, pos1, pos52),
        (call_script, "script_find_high_ground_around_pos1", 30), # call again just in case we are not at peak point.
        (copy_position, pos1, pos52),
        (call_script, "script_find_high_ground_around_pos1", 30), # call again just in case we are not at peak point.
        (team_give_order, "$ai_team", grc_everyone, mordr_hold),
        (team_set_order_position, "$ai_team", grc_everyone, pos52),
        (team_give_order, "$ai_team", grc_archers, mordr_advance),
      (else_try),
        (eq, "$ai_battle_tactic", btactic_follow_leader),
        (team_get_leader, ":ai_leader", "$ai_team"),
        (agent_set_speed_limit, ":ai_leader", 9),
        (team_give_order, "$ai_team", grc_everyone, mordr_charge),
        (team_give_order, "$ai_team", grc_everyone, mordr_follow),
      (try_end),
      
      (assign, "$everyone_charge_order_given", 0),
  ]),
  
  # script_battle_tactic_apply
  # Input: none
  # Output: none
  ("battle_tactic_apply",
    [
      (store_sub,":enemy_team",1,"$ai_team"),
      (store_mission_timer_a,":mission_time"),
      (try_begin),
        (eq, "$ai_battle_tactic", btactic_hold),
        (copy_position, pos1, pos52),
        (call_script, "script_get_closest3_distance_of_team_at_pos1", ":enemy_team"),
        (assign, ":avg_dist", reg0),
        (try_begin),
          (lt, ":avg_dist", 1000),
          (eq, "$everyone_charge_order_given", 0),
          (assign, "$everyone_charge_order_given", 1),
          (team_give_order, "$ai_team", grc_everyone, mordr_charge),
        (try_end),
      (else_try),
        (eq, "$ai_battle_tactic", btactic_follow_leader),
        (eq, "$everyone_charge_order_given", 0),
        (team_get_leader, ":ai_leader", "$ai_team"),
        (call_script, "script_team_get_average_position_of_enemies", "$ai_team"),
        (copy_position, pos60, pos0),
        (team_give_order, "$ai_team", grc_everyone, mordr_hold),
        (team_set_order_position, "$ai_team", grc_everyone, pos60),
        (team_give_order, "$ai_team", grc_everyone, mordr_follow),
        (ge, ":ai_leader", 0),
        (agent_get_position, pos1, ":ai_leader"),
        (call_script, "script_get_closest3_distance_of_team_at_pos1", ":enemy_team"),
        (assign, ":avg_dist", reg0),
        (try_begin),
          (lt, ":avg_dist", 3000),
          (ge,":mission_time",20),
          (assign, "$everyone_charge_order_given", 1),
          (team_give_order, "$ai_team", grc_everyone, mordr_charge),
          (team_get_leader, ":ai_leader", "$ai_team"),
          (agent_set_speed_limit, ":ai_leader", 60),
        (try_end),
      (try_end),
      
      (try_begin), # charge everyone after a while
        (eq, "$everyone_charge_order_given", 0),
        (ge,":mission_time",300),
        (assign, "$everyone_charge_order_given", 1),
        (team_give_order, "$ai_team", grc_everyone, mordr_charge),
        (team_get_leader, ":ai_leader", "$ai_team"),
        (agent_set_speed_limit, ":ai_leader", 60),
      (try_end),
      
  ]),
  
##  # script_siege_defender_tactic_apply
##  # Input: none
##  # Output: none
##  ("siege_defender_tactic_apply",
##    [
##      (try_begin),
##        (eq, "$defender_team", 1),
##        (ge, "$belfry_positioned", 2),
##        
##        (assign, ":enemy_too_weak", 0),
##        (try_begin),
##          (ge, "$attacker_reinforcement_stage", 2),
##          (call_script, "script_calculate_team_strength", "$defender_team"),
##          (assign, ":defender_strength", reg0),
##          (call_script, "script_calculate_team_strength", "$attacker_team"),
##          (assign, ":attacker_strength", reg0),
##          (store_mul, ":attacker_strength_multiplied", ":attacker_strength", 2),
##          (ge, ":defender_strength", ":attacker_strength_multiplied"),
##          (assign, ":enemy_too_weak", 1),
##        (try_end),
##        
##        (try_begin),
##          (eq, ":enemy_too_weak", 1),
##          (neq, "$ai_battle_tactic", btactic_charge),
##          (assign, "$ai_battle_tactic", btactic_charge),
##          (team_give_order, "$defender_team", grc_infantry, mordr_charge),
##        (else_try),
##          (neq, "$ai_battle_tactic", btactic_charge),
##          (neq, "$ai_battle_tactic", btactic_hold),
##          (assign, "$ai_battle_tactic", btactic_hold),
##          (team_give_order, "$defender_team", grc_infantry, mordr_hold),
##          (team_give_order, "$defender_team", grc_heroes, mordr_hold),
##          (entry_point_get_position,pos1,10),
##          (team_set_order_position, "$defender_team", grc_infantry, pos1),
##          (team_set_order_position, "$defender_team", grc_heroes, pos1),
##        (try_end),
##      (try_end),
##  ]),
  
  
  # script_team_get_class_percentages
  # Input: arg1: team_no
  # Output: reg0: percentage infantry, reg1: percentage archers, reg2: percentage cavalry
  ("team_get_class_percentages",
    [
      (assign, ":num_infantry", 0),
      (assign, ":num_archers", 0),
      (assign, ":num_cavalry", 0),
      (assign, ":num_total", 0),
      (store_script_param_1, ":team_no"),
      (try_for_agents,":cur_agent"),
        (agent_is_alive, ":cur_agent"),
        (agent_is_human, ":cur_agent"),
        (agent_get_team, ":agent_team", ":cur_agent"),
        (eq, ":agent_team", ":team_no"),
        
        (val_add, ":num_total", 1),
        (agent_get_class, ":agent_class", ":cur_agent"),
        (try_begin),
          (eq, ":agent_class", grc_infantry),
          (val_add,  ":num_infantry", 1),
        (else_try),
          (eq, ":agent_class", grc_archers),
          (val_add,  ":num_archers", 1),
        (else_try),
          (eq, ":agent_class", grc_cavalry),
          (val_add,  ":num_cavalry", 1),
        (try_end),
      (try_end),
      (try_begin),
        (eq,  ":num_total", 0),
        (assign,  ":num_total", 1),
      (try_end),
      (store_mul, ":perc_infantry",":num_infantry",100),
      (val_div, ":perc_infantry",":num_total"),
      (store_mul, ":perc_archers",":num_archers",100),
      (val_div, ":perc_archers",":num_total"),
      (store_mul, ":perc_cavalry",":num_cavalry",100),
      (val_div, ":perc_cavalry",":num_total"),
      (assign, reg0, ":perc_infantry"),
      (assign, reg1, ":perc_archers"),
      (assign, reg2, ":perc_cavalry"),
  ]),
  
  # script_get_closest3_distance_of_team_at_pos1
  # Input: arg1: team_no, pos1
  # Output: reg0: distance in cms.
  ("get_closest3_distance_of_team_at_pos1",
    [
      (assign, ":min_distance_1", 100000),
      (assign, ":min_distance_2", 100000),
      (assign, ":min_distance_3", 100000),
      
      (store_script_param_1, ":team_no"),
      (try_for_agents,":cur_agent"),
        (agent_is_alive, ":cur_agent"),
        (agent_is_human, ":cur_agent"),
        (agent_get_team, ":agent_team", ":cur_agent"),
        (eq, ":agent_team", ":team_no"),
        
        (agent_get_position, pos2, ":cur_agent"),
        (get_distance_between_positions,":cur_dist",pos2,pos1),
        (try_begin),
          (lt, ":cur_dist", ":min_distance_1"),
          (assign, ":min_distance_3", ":min_distance_2"),
          (assign, ":min_distance_2", ":min_distance_1"),
          (assign, ":min_distance_1", ":cur_dist"),
        (else_try),
          (lt, ":cur_dist", ":min_distance_2"),
          (assign, ":min_distance_3", ":min_distance_2"),
          (assign, ":min_distance_2", ":cur_dist"),
        (else_try),
          (lt, ":cur_dist", ":min_distance_3"),
          (assign, ":min_distance_3", ":cur_dist"),
        (try_end),
      (try_end),
      
      (assign, ":total_distance", 0),
      (assign, ":total_count", 0),
      (try_begin),
        (lt, ":min_distance_1", 100000),
        (val_add, ":total_distance", ":min_distance_1"),
        (val_add, ":total_count", 1),
      (try_end),
      (try_begin),
        (lt, ":min_distance_2", 100000),
        (val_add, ":total_distance", ":min_distance_2"),
        (val_add, ":total_count", 1),
      (try_end),
      (try_begin),
        (lt, ":min_distance_3", 100000),
        (val_add, ":total_distance", ":min_distance_3"),
        (val_add, ":total_count", 1),
      (try_end),
      (assign, ":average_distance", 100000),
      (try_begin),
        (gt, ":total_count", 0),
        (store_div, ":average_distance", ":total_distance", ":total_count"),
      (try_end),
      (assign, reg0, ":average_distance"),
      (assign, reg1, ":min_distance_1"),
      (assign, reg2, ":min_distance_2"),
      (assign, reg3, ":min_distance_3"),
  ]),

  # script_team_get_average_position_of_enemies
  # Input: arg1: team_no, 
  # Output: pos0: average position.
  ("team_get_average_position_of_enemies",
    [
      (store_script_param_1, ":team_no"),
      (init_position, pos0),
      (assign, ":num_enemies", 0),
      (assign, ":accum_x", 0),
      (assign, ":accum_y", 0),
      (assign, ":accum_z", 0),
      (try_for_agents,":enemy_agent"),
        (agent_is_alive, ":enemy_agent"),
        (agent_is_human, ":enemy_agent"),
        (agent_get_team, ":enemy_team", ":enemy_agent"),
        (teams_are_enemies, ":team_no", ":enemy_team"),
      
        (agent_get_position, pos62, ":enemy_agent"),
        (position_get_x, ":x", pos62),
        (position_get_y, ":y", pos62),
        (position_get_z, ":z", pos62),
        (convert_from_fixed_point, ":x"),
        (convert_from_fixed_point, ":y"),
        (convert_from_fixed_point, ":z"),
        (val_add, ":accum_x", ":x"),
        (val_add, ":accum_y", ":y"),
        (val_add, ":accum_z", ":z"),
        (val_add, ":num_enemies", 1),
      (try_end),
      (store_div, ":average_x", ":accum_x", ":num_enemies"),
      (store_div, ":average_y", ":accum_y", ":num_enemies"),
      (store_div, ":average_z", ":accum_z", ":num_enemies"),

      (convert_to_fixed_point, ":average_x"),
      (convert_to_fixed_point, ":average_y"),
      (convert_to_fixed_point, ":average_z"),

      (position_set_x, pos0, ":average_x"),
      (position_set_y, pos0, ":average_y"),
      (position_set_z, pos0, ":average_z"),
      
      (assign, reg0, ":num_enemies"),
  ]),
  
  
##  # script_search_troop_prisoner_of_party
##  # Input: arg1 = troop_no
##  # Output: reg0 = party_no (-1 if troop is not a prisoner.)
##  ("search_troop_prisoner_of_party",
##    [
##      (store_script_param_1, ":troop_no"),
##      (assign, ":prisoner_of", -1),
##      (try_for_parties, ":party_no"),
##        (eq,  ":prisoner_of", -1),
##        (this_or_next|eq, ":party_no", "p_main_party"),
##        (ge, ":party_no", centers_begin),
##        (party_count_prisoners_of_type, ":troop_found", ":party_no", ":troop_no"),
##        (gt, ":troop_found", 0),
##        (assign, ":prisoner_of", ":party_no"),
##      (try_end),
##      (assign, reg0, ":prisoner_of"),
##  ]),
  
  
##  # script_clear_last_quest
##  # Input: arg1 = troop_no
##  # Output: none
##  ("clear_last_quest",
##    [
##      (store_script_param_1, ":troop_no"),
##      
##      (troop_set_slot, ":troop_no",slot_troop_last_quest, 0),
##      (troop_set_slot, ":troop_no",slot_troop_last_quest_betrayed, 0)
##  ]),
  
  
  
##  # script_change_debt_to_troop
##  # Input: arg1 = troop_no, arg2 = new debt amount
##  # Output: none
##  ("change_debt_to_troop",
##    [
##      (store_script_param_1, ":troop_no"),
##      (store_script_param_2, ":new_debt"),
##      
##      (troop_get_slot, ":cur_debt", ":troop_no", slot_troop_player_debt),
##      (assign, reg1, ":cur_debt"),
##      (val_add, ":cur_debt", ":new_debt"),
##      (assign, reg2, ":cur_debt"),
##      (troop_set_slot, ":troop_no", slot_troop_player_debt, ":cur_debt"),
##      (str_store_troop_name, s1, ":troop_no"),
##      (display_message, "str_your_debt_to_s1_is_changed_from_reg1_to_reg2"),
##  ]),
##  
  
  
  
##  # script_abort_quest
##  # Input: arg1 = quest_no, arg2 = apply relation penalty
##  # Output: none
##  ("abort_quest",
##    [
##      (store_script_param_1, ":quest_no"),
##      (store_script_param_2, ":apply_penalty"),
##      
##      (try_begin),
##        (eq, ":quest_no", "qst_deliver_message"),
##      (else_try),
##        (eq, ":quest_no", "qst_escort_lady"),
##        (quest_get_slot, ":quest_object_troop", ":quest_no", slot_quest_object_troop),
##        (party_remove_members, "p_main_party", ":quest_object_troop", 1),
##      (else_try),
##        (eq, ":quest_no", "qst_rescue_lady_under_siege"),
##        (quest_get_slot, ":quest_object_troop", ":quest_no", slot_quest_object_troop),
##        (party_remove_members, "p_main_party", ":quest_object_troop", 1),
##      (else_try),
##        (eq, ":quest_no", "qst_deliver_message_to_lover"),
##      (else_try),
##        (eq, ":quest_no", "qst_deliver_message_to_enemy_lord"),
##      (else_try),
##        (eq, ":quest_no", "qst_bring_prisoners_to_enemy"),
##        (try_begin),
##          (check_quest_succeeded, ":quest_no"),
##          (quest_get_slot, ":quest_target_amount", ":quest_no", slot_quest_target_amount),
##          (quest_get_slot, ":quest_object_troop", ":quest_no", slot_quest_object_troop),
##          (quest_get_slot, ":quest_giver_troop", ":quest_no", slot_quest_giver_troop),
##          (call_script, "script_game_get_join_cost", ":quest_object_troop"),
##          (assign, ":reward", reg0),
##          (val_mul, ":reward", ":quest_target_amount"),
##          (val_div, ":reward", 2),
##        (else_try),
##          (quest_get_slot, ":reward", ":quest_no", slot_quest_target_amount),
##        (try_end),
##        (call_script, "script_change_debt_to_troop", ":quest_giver_troop", ":reward"),
##      (else_try),
##        (eq, ":quest_no", "qst_bring_reinforcements_to_siege"),
##        (quest_get_slot, ":quest_target_amount", ":quest_no", slot_quest_target_amount),
##        (quest_get_slot, ":quest_object_troop", ":quest_no", slot_quest_object_troop),
##        (quest_get_slot, ":quest_giver_troop", ":quest_no", slot_quest_giver_troop),
##        (call_script, "script_game_get_join_cost", ":quest_object_troop"),
##        (assign, ":reward", reg0),
##        (val_mul, ":reward", ":quest_target_amount"),
##        (val_mul, ":reward", 2),
##        (call_script, "script_change_debt_to_troop", ":quest_giver_troop", ":reward"),
##      (else_try),
##        (eq, ":quest_no", "qst_deliver_supply_to_center_under_siege"),
##        (quest_get_slot, ":quest_target_amount", ":quest_no", slot_quest_target_amount),
##        (quest_get_slot, ":quest_giver_troop", ":quest_no", slot_quest_giver_troop),
##        (store_item_value, ":reward", "itm_siege_supply"),
##        (val_mul, ":reward", ":quest_target_amount"),
##        (call_script, "script_change_debt_to_troop", ":quest_giver_troop", ":reward"),
##      (else_try),
##        (eq, ":quest_no", "qst_raise_troops"),
##        (quest_get_slot, ":quest_target_amount", ":quest_no", slot_quest_target_amount),
##        (quest_get_slot, ":quest_target_troop", ":quest_no", slot_quest_target_troop),
##        (quest_get_slot, ":quest_giver_troop", ":quest_no", slot_quest_giver_troop),
##        (call_script, "script_game_get_join_cost", ":quest_object_troop"),
##        (assign, ":reward", reg0),
##        (val_mul, ":reward", ":quest_target_amount"),
##        (val_mul, ":reward", 2),
##        (call_script, "script_change_debt_to_troop", ":quest_giver_troop", ":reward"),
##      (else_try),
##        (eq, ":quest_no", "qst_capture_messenger"),
##      (else_try),
##        (eq, ":quest_no", "qst_bring_back_deserters"),
##      (else_try),
##        (eq, ":quest_no", "qst_kill_local_merchant"),
##      (else_try),
##        (eq, ":quest_no", "qst_bring_back_runaway_serfs"),
##      (else_try),
##        (eq, ":quest_no", "qst_follow_spy"),
##      (else_try),
##        (eq, ":quest_no", "qst_capture_enemy_hero"),
##      (else_try),
##        (eq, ":quest_no", "qst_lend_companion"),
##        (quest_get_slot, ":quest_target_troop", "qst_lend_companion", slot_quest_target_troop),
##        (party_add_members, "p_main_party", ":quest_target_troop", 1),
##      (else_try),
##        (eq, ":quest_no", "qst_capture_conspirators"),
##      (else_try),
##        (eq, ":quest_no", "qst_defend_nobles_against_peasants"),
##      (else_try),
##        (eq, ":quest_no", "qst_incriminate_loyal_commander"),
##      (else_try),
##        (eq, ":quest_no", "qst_hunt_down_raiders"),
##      (else_try),
##        (eq, ":quest_no", "qst_capture_prisoners"),
##        #Enemy lord quests
##      (else_try),
##        (eq, ":quest_no", "qst_lend_surgeon"),
##        #Kingdom lady quests
##      (else_try),
##        (eq, ":quest_no", "qst_rescue_lord_by_replace"),
##      (else_try),
##        (eq, ":quest_no", "qst_deliver_message_to_prisoner_lord"),
##      (else_try),
##        (eq, ":quest_no", "qst_duel_for_lady"),
##      (try_end),
##      
##      (try_begin),
##        (eq, ":apply_penalty", 1),
##        (quest_get_slot, ":quest_giver", ":quest_no", slot_quest_giver_troop),
##        (call_script, "script_change_player_relation_with_troop", ":quest_giver", -1),
##      (try_end),
##      (fail_quest, ":quest_no"),
##      (complete_quest, ":quest_no"),
##  ]),
  
  
##  # script_event_center_captured
##  # Input: arg1 = center_no, arg2 = old_faction_no
##  # Output: none
##  ("event_center_captured",
##    [
##      #      (store_script_param_1, ":center_no"),
##      #       (store_script_param_2, ":old_faction_no"),
##      #       (store_faction_of_party, ":faction_no"),
##      
##      (try_begin),
##        (check_quest_active, "qst_deliver_message"),
##      (try_end),
##      (try_begin),
##        (check_quest_active, "qst_escort_lady"),
##        (quest_slot_eq, "qst_escort_lady", slot_quest_target_center, ":center_no"),
##        (call_script, "script_abort_quest", "qst_escort_lady"),
##      (try_end),
##      (try_begin),
##        (check_quest_active, "qst_rescue_lady_under_siege"),
##        (quest_slot_eq, "qst_rescue_lady_under_siege", slot_quest_target_center, ":center_no"),
##        (quest_slot_eq, "qst_rescue_lady_under_siege", slot_quest_current_state, 0),
##        (call_script, "script_abort_quest", "qst_rescue_lady_under_siege", 1),
##      (try_end),
##      (try_begin),
##        (check_quest_active, "qst_deliver_message_to_lover"),
##      (try_end),
##      (try_begin),
##        (check_quest_active, "qst_deliver_message_to_enemy_lord"),
##      (try_end),
##      (try_begin),
##        (check_quest_active, "qst_bring_prisoners_to_enemy"),
##        (quest_slot_eq, "qst_bring_prisoners_to_enemy", slot_quest_target_center, ":center_no"),
##        (neg|check_quest_succeeded, "qst_bring_prisoners_to_enemy"),
##        (call_script, "script_abort_quest", "qst_bring_prisoners_to_enemy"),
##      (try_end),
##      (try_begin),
##        (check_quest_active, "qst_bring_reinforcements_to_siege"),
##      (try_end),
##      (try_begin),
##        (check_quest_active, "qst_deliver_supply_to_center_under_siege"),
##        (quest_slot_eq, "qst_deliver_supply_to_center_under_siege", slot_quest_target_center, ":center_no"),
##        (call_script, "script_abort_quest", "qst_deliver_supply_to_center_under_siege", 1),
##      (try_end),
##      (try_begin),
##        (check_quest_active, "qst_raise_troops"),
##      (try_end),
##      (try_begin),
##        (check_quest_active, "qst_capture_messenger"),
##      (try_end),
##      (try_begin),
##        (check_quest_active, "qst_bring_back_deserters"),
##      (try_end),
##      (try_begin),
##        (check_quest_active, "qst_kill_local_merchant"),
##      (try_end),
##      (try_begin),
##        (check_quest_active, "qst_bring_back_runaway_serfs"),
##        (quest_slot_eq, "qst_bring_back_runaway_serfs", slot_quest_object_center, ":center_no"),
##        (neg|check_quest_succeeded, "qst_bring_back_runaway_serfs"),
##        (neg|check_quest_failed, "qst_bring_back_runaway_serfs"),
##        (call_script, "script_abort_quest", "qst_bring_back_runaway_serfs"),
##      (try_end),
##      (try_begin),
##        (check_quest_active, "qst_follow_spy"),
##      (try_end),
##      (try_begin),
##        (check_quest_active, "qst_capture_enemy_hero"),
##      (try_end),
##      (try_begin),
##        (check_quest_active, "qst_lend_companion"),
##      (try_end),
##      (try_begin),
##        (check_quest_active, "qst_capture_conspirators"),
##      (try_end),
##      (try_begin),
##        (check_quest_active, "qst_defend_nobles_against_peasants"),
##      (try_end),
##      (try_begin),
##        (check_quest_active, "qst_incriminate_loyal_commander"),
##      (try_end),
##      (try_begin),
##        (check_quest_active, "qst_hunt_down_raiders"),
##      (try_end),
##      (try_begin),
##        (check_quest_active, "qst_capture_prisoners"),
##      (try_end),
##      #Enemy lord quests
##      (try_begin),
##        (check_quest_active, "qst_lend_surgeon"),
##      (try_end),
##      #Kingdom lady quests
##      (try_begin),
##        (check_quest_active, "qst_rescue_lord_by_replace"),
##        (quest_get_slot, ":quest_target_troop", "qst_rescue_lord_by_replace", slot_quest_target_troop),
##        (troop_slot_eq, ":quest_target_troop", slot_troop_is_prisoner, 0),
##        (neg|check_quest_succeeded, "qst_rescue_lord_by_replace"),
##        (call_script, "script_abort_quest", "qst_rescue_lord_by_replace"),
##      (try_end),
##      (try_begin),
##        (check_quest_active, "qst_deliver_message_to_prisoner_lord"),
##      (try_end),
##      (try_begin),
##        (check_quest_active, "qst_duel_for_lady"),
##      (try_end),
##  ]),

  # script_cf_is_quest_troop
  # Input: arg1 = troop_no
  # Output: none (can fail)
  ("cf_is_quest_troop",
    [
      (store_script_param_1, ":troop_no"),
      (assign, ":is_quest_troop", 0),
      (try_for_range, ":cur_quest", all_quests_begin, all_quests_end),
        (check_quest_active, ":cur_quest"),
        (quest_get_slot, ":quest_troop_1", ":cur_quest", slot_quest_target_troop),
        (quest_get_slot, ":quest_troop_2", ":cur_quest", slot_quest_object_troop),
        (quest_get_slot, ":quest_troop_3", ":cur_quest", slot_quest_giver_troop),
        (this_or_next|eq, ":quest_troop_1", ":troop_no"),
        (this_or_next|eq, ":quest_troop_2", ":troop_no"),
        (eq, ":quest_troop_3", ":troop_no"),
        (assign, ":is_quest_troop", 1),
      (try_end),
      (eq, ":is_quest_troop", 1),
  ]),

  
##  # script_calculate_team_strength
##  # Input: arg1 = team_no
##  # Output: strength
##  ("calculate_team_strength",
##    [
##      (store_script_param_1, ":team_no"),
##      (assign, ":total_strength", 0),
##      (try_for_agents, ":cur_agent"),
##        (agent_get_team, ":agent_team", ":cur_agent"),
##        (eq, ":team_no", ":agent_team"),
##        (agent_is_human, ":cur_agent"),
##        (agent_is_alive, ":cur_agent"),
##        
##        (agent_get_troop_id, ":cur_troop", ":cur_agent"),
##        (store_character_level, ":cur_level", ":cur_troop"),
##        (val_add, ":cur_level", 5),
##        (try_begin),
##          (troop_is_hero, ":cur_troop"),
##          (val_add, ":cur_level", 5),
##        (try_end),
##        (val_add, ":total_strength", ":cur_level"),
##      (try_end),
##      (assign, reg0, ":total_strength"),
##  ]),

  # script_check_friendly_kills
  # Input: none
  # Output: none (changes the morale of the player's party)
  ("check_friendly_kills",
    [(get_player_agent_own_troop_kill_count, ":count"),
     (try_begin),
       (neq, "$g_player_current_own_troop_kills", ":count"),
       (val_sub, ":count", "$g_player_current_own_troop_kills"),
       (val_add, "$g_player_current_own_troop_kills", ":count"),
       (val_mul, ":count", -1),
       (call_script, "script_change_player_party_morale", ":count"),
     (try_end),
   ]),

  # script_simulate_retreat
  # Input: arg1 = players_side_damage, arg2 = enemy_side_damage
  # Output: none
  ("simulate_retreat",
    [
      (set_show_messages, 0),
      (store_script_param_1, ":players_side_damage"),
      (store_script_param_2, ":enemy_side_damage"),
      
      (assign, ":players_side_strength", 0),
      (assign, ":enemy_side_strength", 0),
      
      (assign, ":do_calculate", 1),
      (try_begin),
        (eq, "$pin_player_fallen", 0),
        (try_for_agents, ":cur_agent"),
          (agent_is_human, ":cur_agent"),
          (agent_is_alive, ":cur_agent"),
          
          (agent_get_troop_id, ":cur_troop", ":cur_agent"),
          (store_character_level, ":cur_level", ":cur_troop"),
          (val_add, ":cur_level", 5),
          (try_begin),
            (troop_is_hero, ":cur_troop"),
            (val_add, ":cur_level", 5),
          (try_end),
          (try_begin),
            (agent_is_ally, ":cur_agent"),
            (val_add, ":players_side_strength", ":cur_level"),
          (else_try),
            (val_add, ":enemy_side_strength", ":cur_level"),
          (try_end),
        (try_end),
        (lt, ":enemy_side_strength", ":players_side_strength"),
        (assign, ":do_calculate", 0),
      (try_end),
      
      (try_begin),
        (eq, ":do_calculate", 1),
        
        (assign, "$g_last_mission_player_damage", 0),
        (party_clear, "p_temp_party"),
        (party_clear, "p_temp_party_2"),
        (call_script, "script_simulate_battle_with_agents_aux", 0, ":players_side_damage"),
        (call_script, "script_simulate_battle_with_agents_aux", 1, ":enemy_side_damage"),
        
        (assign, ":display_casualties", 0),
        
        (try_begin),
          (gt, "$g_last_mission_player_damage", 0),
          (assign, ":display_casualties", 1),
          (assign, reg1, "$g_last_mission_player_damage"),
          (str_store_string, s12, "str_casualty_display_hp"),
        (else_try),
          (str_clear, s12),
        (try_end),
        
        (call_script, "script_print_casualties_to_s0", "p_temp_party", 1),
        (try_begin),
          (party_get_num_companion_stacks, ":num_stacks", "p_temp_party"),
          (gt, ":num_stacks", 0),
          (assign, ":display_casualties", 1),
        (try_end),
        (str_store_string_reg, s10, s0),
        
        (call_script, "script_print_casualties_to_s0", "p_temp_party_2", 1),
        (try_begin),
          (party_get_num_companion_stacks, ":num_stacks", "p_temp_party_2"),
          (gt, ":num_stacks", 0),
          (assign, ":display_casualties", 1),
        (try_end),
        (str_store_string_reg, s11, s0),
        (try_begin),
          (eq, ":display_casualties", 1),
          (tutorial_box,"str_casualty_display", "str_retreat"),
        (try_end),
      (try_end),
      (set_show_messages, 1),

      #Calculating morale penalty (can be between 0-30)
      (assign, ":ally_casualties", 0),
      (assign, ":enemy_casualties", 0),
      (assign, ":total_allies", 0),
      
      (try_for_agents, ":cur_agent"),
        (agent_is_human, ":cur_agent"),
        (try_begin),
          (agent_is_ally, ":cur_agent"),
          (val_add, ":total_allies", 1),
          (try_begin),
            (neg|agent_is_alive, ":cur_agent"),
            (val_add, ":ally_casualties", 1),
          (try_end),
        (else_try),
          (neg|agent_is_alive, ":cur_agent"),
          (val_add, ":enemy_casualties", 1),
        (try_end),
      (try_end),
      (store_add, ":total_casualties", ":ally_casualties", ":enemy_casualties"),
      (try_begin),
        (gt, ":total_casualties", 0),
        (store_mul, ":morale_adder", ":ally_casualties", 100),
        (val_div, ":morale_adder", ":total_casualties"),
        (val_mul, ":morale_adder", ":ally_casualties"),
        (val_div, ":morale_adder", ":total_allies"),
        (val_mul, ":morale_adder", -30),
        (val_div, ":morale_adder", 100),
        (call_script, "script_change_player_party_morale", ":morale_adder"),
      (try_end),
  ]),

  
  
  # script_simulate_battle_with_agents_aux
  # For internal use only
  # Input: arg1 = attacker_side (0 = ally, 1 = enemy), arg2 = damage amount
  # Output: none
  ("simulate_battle_with_agents_aux",
    [
      (store_script_param_1, ":attacker_side"),
      (store_script_param_2, ":damage"),
      
      (get_player_agent_no, ":player_agent"),
      (try_for_agents, ":cur_agent"),
        (neq, ":player_agent", ":cur_agent"),
        (agent_is_human, ":cur_agent"),
        (agent_is_alive, ":cur_agent"),
        (try_begin),
          (agent_is_ally, ":cur_agent"),
          (assign, ":cur_agents_side", 0),
        (else_try),
          (assign, ":cur_agents_side", 1),
        (try_end),
        (eq, ":cur_agents_side", ":attacker_side"),
        (agent_get_position, pos2, ":cur_agent"),
        (assign, ":closest_agent", -1),
        (assign, ":min_distance", 100000),
        (try_for_agents, ":cur_agent_2"),
          (agent_is_human, ":cur_agent_2"),
          (agent_is_alive, ":cur_agent_2"),
          (try_begin),
            (agent_is_ally, ":cur_agent_2"),
            (assign, ":cur_agents_side_2", 0),
          (else_try),
            (assign, ":cur_agents_side_2", 1),
          (try_end),
          (this_or_next|neq, ":cur_agent_2", ":player_agent"),
          (eq, "$pin_player_fallen", 0),
          (neq, ":attacker_side", ":cur_agents_side_2"),
          (agent_get_position, pos3, ":cur_agent_2"),
          (get_distance_between_positions, ":cur_distance", pos2, pos3),
          (lt, ":cur_distance", ":min_distance"),
          (assign, ":min_distance", ":cur_distance"),
          (assign, ":closest_agent", ":cur_agent_2"),
        (try_end),
        (ge, ":closest_agent", 0),
        #Fight
        (agent_get_class, ":agent_class", ":cur_agent"),
        (assign, ":agents_speed", 1),
        (assign, ":agents_additional_hit", 0),
        (try_begin),
          (eq, ":agent_class", grc_archers),
          (assign, ":agents_additional_hit", 1),
        (else_try),
          (eq, ":agent_class", grc_cavalry),
          (assign, ":agents_speed", 2),
        (try_end),
        (agent_get_class, ":agent_class", ":closest_agent"),
        (assign, ":agents_speed_2", 1),
        (try_begin),
          (eq, ":agent_class", grc_cavalry),
          (assign, ":agents_speed_2", 3),
        (try_end),
        (assign, ":agents_hit", 10000),
        (val_add, ":min_distance", 2000),
        (val_div, ":agents_hit", ":min_distance"),
        (val_mul, ":agents_hit", 2),# max 8, min 2 hits within 80 meters
        
        (val_mul, ":agents_hit", ":agents_speed"),
        (val_div, ":agents_hit", ":agents_speed_2"),
        (val_add, ":agents_hit", ":agents_additional_hit"),
        
        (assign, ":cur_damage", ":damage"),
        (agent_get_troop_id, ":closest_troop", ":closest_agent"),
        (agent_get_troop_id, ":cur_troop", ":cur_agent"),
        (store_character_level, ":closest_level", ":closest_troop"),
        (store_character_level, ":cur_level", ":cur_troop"),
        (store_sub, ":level_dif", ":cur_level", ":closest_level"),
        (val_add, ":cur_damage", ":level_dif"),
        
        (try_begin),
          (eq, ":closest_agent", ":player_agent"),
          (val_div, ":cur_damage", 2),
          (store_agent_hit_points, ":init_player_hit_points", ":player_agent", 1),
        (try_end),
        
        (try_for_range, ":unused", 0, ":agents_hit"),
          (store_random_in_range, ":random_damage", 0, 100),
          (lt, ":random_damage", ":cur_damage"),
          (agent_deliver_damage_to_agent, ":cur_agent", ":closest_agent"),
        (try_end),
        
        (try_begin),
          (eq, ":closest_agent", ":player_agent"),
          (store_agent_hit_points, ":final_player_hit_points", ":player_agent", 1),
          (store_sub, ":hit_points_difference", ":init_player_hit_points", ":final_player_hit_points"),
          (val_add, "$g_last_mission_player_damage", ":hit_points_difference"),
        (try_end),
        
        (neg|agent_is_alive, ":closest_agent"),
        (try_begin),
          (eq, ":attacker_side", 1),
          (party_add_members, "p_temp_party", ":closest_troop", 1),
          (try_begin),
            (agent_is_wounded, ":closest_agent"),
            (party_wound_members, "p_temp_party", ":closest_troop", 1),
          (try_end),
        (else_try),
          (party_add_members, "p_temp_party_2", ":closest_troop", 1),
          (try_begin),
            (agent_is_wounded, ":closest_agent"),
            (party_wound_members, "p_temp_party_2", ":closest_troop", 1),
          (try_end),
        (try_end),
      (try_end),
  ]),
  
  
##  # script_map_get_random_position_around_position_within_range
##  # Input: arg1 = minimum_distance in km, arg2 = maximum_distance in km, pos1 = origin position
##  # Output: pos2 = result position
##  ("map_get_random_position_around_position_within_range",
##    [
##      (store_script_param_1, ":min_distance"),
##      (store_script_param_2, ":max_distance"),
##      (val_mul, ":min_distance", 100),
##      (assign, ":continue", 1),
##      (try_for_range, ":unused", 0, 20),
##        (eq, ":continue", 1),
##        (map_get_random_position_around_position, pos2, pos1, ":max_distance"),
##        (get_distance_between_positions, ":distance", pos2, pos1),
##        (ge, ":distance", ":min_distance"),
##        (assign, ":continue", 0),
##      (try_end),
##  ]),
  
  
  # script_get_number_of_unclaimed_centers_by_player
  # Input: none
  # Output: reg0 = number of unclaimed centers, reg1 = last unclaimed center_no
  ("get_number_of_unclaimed_centers_by_player",
    [
      (assign, ":unclaimed_centers", 0),
      (assign, reg1, -1),
      (try_for_range, ":center_no", centers_begin, centers_end),
        (store_faction_of_party, ":faction_no", ":center_no"),
        (eq, ":faction_no", "fac_player_faction"),
        (party_slot_eq, ":center_no", slot_town_claimed_by_player, 0),
        (party_get_num_companion_stacks, ":num_stacks", ":center_no"),
        (ge, ":num_stacks", 1), #castle is garrisoned
        (assign, reg1, ":center_no"),
        (val_add, ":unclaimed_centers", 1),
      (try_end),
      (assign, reg0, ":unclaimed_centers"),
  ]),
  
  # script_troop_count_number_of_enemy_troops
  # Input: arg1 = troop_no
  # Output: reg0 = number_of_enemy_troops
  ("troop_count_number_of_enemy_troops",
    [
      (store_script_param_1, ":troop_no"),
      (assign, ":enemy_count", 0),
      (try_for_range, ":i_enemy_slot", slot_troop_enemies_begin, slot_troop_enemies_end),
        (troop_slot_ge, ":troop_no", ":i_enemy_slot", 1),
        (val_add, ":enemy_count", 1),
      (try_end),
      (assign, reg0, ":enemy_count"),
  ]),
  
  
  # script_cf_troop_check_troop_is_enemy
  # Input: arg1 = troop_no, arg2 = checked_troop_no
  # Output: none (Can fail)
  ("cf_troop_check_troop_is_enemy",
    [
      (store_script_param_1, ":troop_no"),
      (store_script_param_2, ":checked_troop_no"),
      (assign, ":result", 0),
      (try_for_range, ":i_enemy_slot", slot_troop_enemies_begin, slot_troop_enemies_end),
        (troop_slot_eq, ":troop_no", ":i_enemy_slot", ":checked_troop_no"),
        (assign, ":result", 1),
      (try_end),
      (eq, ":result", 1),
  ]),
  
  
  # script_troop_get_leaded_center_with_index
  # Input: arg1 = troop_no, arg2 = center index within range between zero and the number of centers that troop owns
  # Output: reg0 = center_no
  ("troop_get_leaded_center_with_index",
    [
      (store_script_param_1, ":troop_no"),
      (store_script_param_2, ":random_center"),
      (assign, ":result", -1),
      (assign, ":center_count", 0),
      (try_for_range, ":center_no", centers_begin, centers_end),
        (eq, ":result", -1),
        (party_slot_eq, ":center_no", slot_town_lord, ":troop_no"),
        (val_add, ":center_count", 1),
        (gt, ":center_count", ":random_center"),
        (assign, ":result", ":center_no"),
      (try_end),
      (assign, reg0, ":result"),
  ]),
  
  # script_cf_troop_get_random_leaded_center
  # Input: arg1 = troop_no
  # Output: reg0 = center_no (Can fail)
  ("cf_troop_get_random_leaded_center",
    [
      (store_script_param_1, ":troop_no"),
      
      (call_script, "script_get_number_of_hero_centers", ":troop_no"),
      (assign, ":center_count", reg0),
      (store_random_in_range, ":random_center", 0, ":center_count"),
      (call_script, "script_troop_get_leaded_center_with_index", ":troop_no", ":random_center"),
      (neq, reg0, -1),
  ]),
  
  # script_troop_write_owned_centers_to_s2
  # Input: arg1 = troop_no
  # Output: none
  ("troop_write_owned_centers_to_s2",
    [
      (store_script_param_1, ":troop_no"),
      
      (call_script, "script_get_number_of_hero_centers", ":troop_no"),
      (assign, ":no_centers", reg0),
      
      (str_store_troop_name, s5, ":troop_no"),
      
      (try_begin),
        (gt, ":no_centers", 1),
        (try_for_range, ":i_center", 1, ":no_centers"),
          (call_script, "script_troop_get_leaded_center_with_index", ":troop_no", ":i_center"),
          (str_store_party_name_link, s50, reg0),
          (try_begin),
            (eq, ":i_center", 1),
            (call_script, "script_troop_get_leaded_center_with_index", ":troop_no", 0),
            (str_store_party_name_link, s51, reg0),
            (str_store_string, s51, "str_s50_and_s51"),
          (else_try),
            (str_store_string, s51, "str_s50_comma_s51"),
          (try_end),
        (try_end),
        (str_store_string, s2, "str_s5_is_the_ruler_of_s51"),
      (else_try),
        (eq, ":no_centers", 1),
        (call_script, "script_troop_get_leaded_center_with_index", ":troop_no", 0),
        (str_store_party_name_link, s51, reg0),
        (str_store_string, s2, "str_s5_is_the_ruler_of_s51"),
      (else_try),
        (store_troop_faction, ":faction_no", ":troop_no"),
        (str_store_faction_name_link, s6, ":faction_no"),
        (str_store_string, s2, "str_s5_is_a_nobleman_of_s6"),
      (try_end),
  ]),
  
  # script_troop_write_family_relations_to_s1
  # Input: arg1 = troop_no
  # Output: none
  ("troop_write_family_relations_to_s1",
    [
      (store_script_param_1, ":troop_no"),
      (assign, ":num_family", 0),
      (try_for_range, ":slot_no", slot_troop_family_begin, slot_troop_family_end),
        (troop_slot_ge, ":troop_no", ":slot_no", 1),
        (val_add, ":num_family", 1),
      (try_end),
      
      (troop_get_type, ":gender", ":troop_no"),
      (try_begin),
        (eq, ":gender", 0),
        (str_store_string, s5, "str_he"),
      (else_try),
        (str_store_string, s5, "str_she"),
      (try_end),
      
      (try_begin),
        (gt, ":num_family", 1),
        (try_for_range, ":i_family", 1, ":num_family"),
          (call_script, "script_write_family_relation_as_s3s_s2_to_s4", ":troop_no", ":i_family"),
          (str_store_string_reg, s50, s4),
          (try_begin),
            (eq, ":i_family", 1),
            (call_script, "script_write_family_relation_as_s3s_s2_to_s4", ":troop_no", 0),
            (str_store_string_reg, s51, s4),
            (str_store_string, s51, "str_s50_and_s51"),
          (else_try),
            (str_store_string, s51, "str_s50_comma_s51"),
          (try_end),
        (try_end),
        (str_store_string, s1, "str_s5_is_s51"),
      (else_try),
        (eq, ":num_family", 1),
        (call_script, "script_write_family_relation_as_s3s_s2_to_s4", ":troop_no", 0),
        (str_store_string_reg, s51, s4),
        (str_store_string, s1, "str_s5_is_s51"),
      (else_try),
        (str_store_string, s1, "str_blank_string"),
      (try_end),
  ]),
  
  # script_write_family_relation_as_s3s_s2_to_s4
  # Inputs: arg1 = troop_no, arg2 = family_no (valid slot no after slot_troop_family_begin)
  # Outputs: s50 = s3s_s2 text
  
  ("write_family_relation_as_s3s_s2_to_s4",
    [
      (store_script_param_1, ":troop_no"),
      (store_script_param_2, ":family_no"),
      (troop_get_type, ":gender", ":troop_no"),
      (assign, ":slot_no", slot_troop_family_begin),
      (try_for_range, ":unused", slot_troop_family_begin, slot_troop_family_end),
        (this_or_next|gt, ":family_no", 0),
        (troop_slot_eq, ":troop_no", ":slot_no", 0),
        (try_begin),
          (troop_slot_ge, ":troop_no", ":slot_no", 1),
          (val_sub, ":family_no", 1),
        (try_end),
        (val_add, ":slot_no", 1),
      (try_end),
      (try_begin),
        (eq, ":slot_no", slot_troop_spouse),
        (try_begin),
          (eq, ":gender", 0),
          (str_store_string, s2, "str_husband"),
        (else_try),
          (str_store_string, s2, "str_wife"),
        (try_end),
      (else_try),
        (this_or_next|eq, ":slot_no", slot_troop_son),
        (eq, ":slot_no", slot_troop_daughter),
        (try_begin),
          (eq, ":gender", 0),
          (str_store_string, s2, "str_father"),
        (else_try),
          (str_store_string, s2, "str_mother"),
        (try_end),
      (else_try),
        (this_or_next|eq, ":slot_no", slot_troop_father),
        (eq, ":slot_no", slot_troop_mother),
        (try_begin),
          (eq, ":gender", 0),
          (str_store_string, s2, "str_son"),
        (else_try),
          (str_store_string, s2, "str_daughter"),
        (try_end),
      (else_try),
        (eq, ":slot_no", slot_troop_sibling),
        (try_begin),
          (eq, ":gender", 0),
          (str_store_string, s2, "str_brother"),
        (else_try),
          (str_store_string, s2, "str_sister"),
        (try_end),
      (try_end),
      (troop_get_slot, ":cur_family", ":troop_no", ":slot_no"),
      (str_store_troop_name_link, s3, ":cur_family"),
      (str_store_string, s4, "str_s3s_s2"),
  ]),
  
  
  # script_complete_family_relations
  # Inputs: none
  # Outputs: none
  
  ("complete_family_relations",
    [
      #Completing family relations
      (try_for_range, ":troop_id", heroes_begin, heroes_end),
        (troop_get_type, ":troop_gender", ":troop_id"),
        (try_begin),
          (troop_get_slot, ":cur_spouse", ":troop_id", slot_troop_spouse),
          (gt, ":cur_spouse", 0),
          (troop_set_slot, ":cur_spouse", slot_troop_spouse, ":troop_id"),
          #Adding children from troop to new spouse
          (troop_get_slot, ":cur_daughter", ":troop_id", slot_troop_daughter),
          (troop_get_slot, ":cur_son", ":troop_id", slot_troop_son),
          (try_begin),
            (gt, ":cur_daughter", 0),
            (troop_set_slot, ":cur_spouse", slot_troop_daughter, ":cur_daughter"),
          (try_end),
          (try_begin),
            (gt, ":cur_son", 0),
            (troop_set_slot, ":cur_spouse", slot_troop_son, ":cur_son"),
          (try_end),
          #Adding children from new spouse to troop
          (troop_get_slot, ":cur_daughter", ":cur_spouse", slot_troop_daughter),
          (troop_get_slot, ":cur_son", ":cur_spouse", slot_troop_son),
          (try_begin),
            (gt, ":cur_daughter", 0),
            (troop_set_slot, ":troop_id", slot_troop_daughter, ":cur_daughter"),
          (try_end),
          (try_begin),
            (gt, ":cur_son", 0),
            (troop_set_slot, ":troop_id", slot_troop_son, ":cur_son"),
          (try_end),
        (try_end),
        (try_begin),
          (troop_get_slot, ":cur_sibling", ":troop_id", slot_troop_sibling),
          (gt, ":cur_sibling", 0),
          (troop_set_slot, ":cur_sibling", slot_troop_sibling, ":troop_id"),
          #Adding parents from troop to new sibling
          (troop_get_slot, ":cur_mother", ":troop_id", slot_troop_mother),
          (troop_get_slot, ":cur_father", ":troop_id", slot_troop_father),
          (try_begin),
            (gt, ":cur_mother", 0),
            (troop_set_slot, ":cur_sibling", slot_troop_mother, ":cur_mother"),
          (try_end),
          (try_begin),
            (gt, ":cur_father", 0),
            (troop_set_slot, ":cur_sibling", slot_troop_father, ":cur_father"),
          (try_end),
          #Adding parents from new sibling to troop
          (troop_get_slot, ":cur_mother", ":cur_sibling", slot_troop_mother),
          (troop_get_slot, ":cur_father", ":cur_sibling", slot_troop_father),
          (try_begin),
            (gt, ":cur_mother", 0),
            (troop_set_slot, ":troop_id", slot_troop_mother, ":cur_mother"),
          (try_end),
          (try_begin),
            (gt, ":cur_father", 0),
            (troop_set_slot, ":troop_id", slot_troop_father, ":cur_father"),
          (try_end),
        (try_end),
        (try_begin),
          (troop_get_slot, ":cur_child", ":troop_id", slot_troop_son),
          (gt, ":cur_child", 0),
          (try_begin),
            (eq, ":troop_gender", 0),
            (troop_set_slot, ":cur_child", slot_troop_father, ":troop_id"),
          (else_try),
            (troop_set_slot, ":cur_child", slot_troop_mother, ":troop_id"),
          (try_end),
          #Adding mother/father and sibling from troop to new son
          (troop_get_slot, ":cur_mother_father", ":troop_id", slot_troop_spouse),
          (troop_get_slot, ":cur_sibling", ":troop_id", slot_troop_daughter),
          (try_begin),
            (gt, ":cur_mother_father", 0),
            (try_begin),
              (eq, ":troop_gender", 1),
              (troop_set_slot, ":cur_child", slot_troop_father, ":cur_mother_father"),
            (else_try),
              (troop_set_slot, ":cur_child", slot_troop_mother, ":cur_mother_father"),
            (try_end),
          (try_end),
          (try_begin),
            (gt, ":cur_sibling", 0),
            (troop_set_slot, ":cur_child", slot_troop_sibling, ":cur_sibling"),
          (try_end),
          #Adding son/daughter and spouse from new son to troop
          (try_begin),
            (eq, ":troop_gender", 0),
            (troop_get_slot, ":cur_spouse", ":cur_child", slot_troop_mother),
          (else_try),
            (troop_get_slot, ":cur_spouse", ":cur_child", slot_troop_father),
          (try_end),
          (troop_get_slot, ":cur_daughter", ":cur_child", slot_troop_sibling),
          (try_begin),
            (gt, ":cur_spouse", 0),
            (troop_set_slot, ":troop_id", slot_troop_spouse, ":cur_spouse"),
          (try_end),
          (try_begin),
            (gt, ":cur_daughter", 0),
            (troop_set_slot, ":troop_id", slot_troop_daughter, ":cur_daughter"),
          (try_end),
        (try_end),
        (try_begin),
          (troop_get_slot, ":cur_child", ":troop_id", slot_troop_daughter),
          (gt, ":cur_child", 0),
          (try_begin),
            (eq, ":troop_gender", 0),
            (troop_set_slot, ":cur_child", slot_troop_father, ":troop_id"),
          (else_try),
            (troop_set_slot, ":cur_child", slot_troop_mother, ":troop_id"),
          (try_end),
          #Adding mother/father and sibling from troop to new daughter
          (troop_get_slot, ":cur_mother_father", ":troop_id", slot_troop_spouse),
          (troop_get_slot, ":cur_sibling", ":troop_id", slot_troop_son),
          (try_begin),
            (gt, ":cur_mother_father", 0),
            (try_begin),
              (eq, ":troop_gender", 1),
              (troop_set_slot, ":cur_child", slot_troop_father, ":cur_mother_father"),
            (else_try),
              (troop_set_slot, ":cur_child", slot_troop_mother, ":cur_mother_father"),
            (try_end),
          (try_end),
          (try_begin),
            (gt, ":cur_sibling", 0),
            (troop_set_slot, ":cur_child", slot_troop_sibling, ":cur_sibling"),
          (try_end),
          #Adding son/daughter and spouse from new daughter to troop
          (try_begin),
            (eq, ":troop_gender", 0),
            (troop_get_slot, ":cur_spouse", ":cur_child", slot_troop_mother),
          (else_try),
            (troop_get_slot, ":cur_spouse", ":cur_child", slot_troop_father),
          (try_end),
          (troop_get_slot, ":cur_son", ":cur_child", slot_troop_sibling),
          (try_begin),
            (gt, ":cur_spouse", 0),
            (troop_set_slot, ":troop_id", slot_troop_spouse, ":cur_spouse"),
          (try_end),
          (try_begin),
            (gt, ":cur_son", 0),
            (troop_set_slot, ":troop_id", slot_troop_son, ":cur_son"),
          (try_end),
        (try_end),
        (try_begin),
          (troop_get_slot, ":cur_father", ":troop_id", slot_troop_father),
          (gt, ":cur_father", 0),
          (try_begin),
            (eq, ":troop_gender", 0),
            (troop_set_slot, ":cur_father", slot_troop_son, ":troop_id"),
          (else_try),
            (troop_set_slot, ":cur_father", slot_troop_daughter, ":troop_id"),
          (try_end),
          #Adding son/daughter and spouse from troop to new father
          (troop_get_slot, ":cur_spouse", ":troop_id", slot_troop_mother),
          (troop_get_slot, ":cur_son_daughter", ":troop_id", slot_troop_sibling),
          (try_begin),
            (gt, ":cur_spouse", 0),
            (troop_set_slot, ":cur_father", slot_troop_spouse, ":cur_spouse"),
          (try_end),
          (try_begin),
            (gt, ":cur_son_daughter", 0),
            (try_begin),
              (eq, ":troop_gender", 0),
              (troop_set_slot, ":cur_father", slot_troop_daughter, ":cur_son_daughter"),
            (else_try),
              (troop_set_slot, ":cur_father", slot_troop_son, ":cur_son_daughter"),
            (try_end),
          (try_end),
          #Adding mother/father and sibling from new father to troop
          (try_begin),
            (eq, ":troop_gender", 0),
            (troop_get_slot, ":cur_sibling", ":cur_father", slot_troop_daughter),
          (else_try),
            (troop_get_slot, ":cur_sibling", ":cur_father", slot_troop_son),
          (try_end),
          (troop_get_slot, ":cur_mother", ":cur_father", slot_troop_spouse),
          (try_begin),
            (gt, ":cur_sibling", 0),
            (troop_set_slot, ":troop_id", slot_troop_sibling, ":cur_sibling"),
          (try_end),
          (try_begin),
            (gt, ":cur_mother", 0),
            (troop_set_slot, ":troop_id", slot_troop_mother, ":cur_mother"),
          (try_end),
        (try_end),
        (try_begin),
          (troop_get_slot, ":cur_mother", ":troop_id", slot_troop_mother),
          (gt, ":cur_mother", 0),
          (try_begin),
            (eq, ":troop_gender", 0),
            (troop_set_slot, ":cur_mother", slot_troop_son, ":troop_id"),
          (else_try),
            (troop_set_slot, ":cur_mother", slot_troop_daughter, ":troop_id"),
          (try_end),
          #Adding son/daughter and spouse from troop to new mother
          (troop_get_slot, ":cur_spouse", ":troop_id", slot_troop_father),
          (troop_get_slot, ":cur_son_daughter", ":troop_id", slot_troop_sibling),
          (try_begin),
            (gt, ":cur_spouse", 0),
            (troop_set_slot, ":cur_mother", slot_troop_spouse, ":cur_spouse"),
          (try_end),
          (try_begin),
            (gt, ":cur_son_daughter", 0),
            (try_begin),
              (eq, ":troop_gender", 0),
              (troop_set_slot, ":cur_mother", slot_troop_daughter, ":cur_son_daughter"),
            (else_try),
              (troop_set_slot, ":cur_mother", slot_troop_son, ":cur_son_daughter"),
            (try_end),
          (try_end),
          #Adding mother/father and sibling from new mother to troop
          (try_begin),
            (eq, ":troop_gender", 0),
            (troop_get_slot, ":cur_sibling", ":cur_mother", slot_troop_daughter),
          (else_try),
            (troop_get_slot, ":cur_sibling", ":cur_mother", slot_troop_son),
          (try_end),
          (troop_get_slot, ":cur_father", ":cur_mother", slot_troop_spouse),
          (try_begin),
            (gt, ":cur_sibling", 0),
            (troop_set_slot, ":troop_id", slot_troop_sibling, ":cur_sibling"),
          (try_end),
          (try_begin),
            (gt, ":cur_father", 0),
            (troop_set_slot, ":troop_id", slot_troop_father, ":cur_father"),
          (try_end),
        (try_end),
      (try_end),
  ]),
  
  # script_collect friendly_parties
  # Fills the party p_collective_friends with the members of parties attached to main_party and ally_party_no
  ("collect_friendly_parties",
    [
      (party_collect_attachments_to_party, "p_main_party", "p_collective_friends"),
      (try_begin),
        (gt, "$g_ally_party", 0),
        (party_collect_attachments_to_party, "$g_ally_party", "p_temp_party"),
        (assign, "$g_move_heroes", 1),
        (call_script, "script_party_add_party", "p_collective_friends", "p_temp_party"),
      (try_end),
  ]),

  # script_encounter_calculate_fit
  # Input: arg1 = troop_no
  # Output: none
  ("encounter_calculate_fit",
    [
#      (assign, "$g_enemy_fit_for_battle_old",  "$g_enemy_fit_for_battle"),
#      (assign, "$g_friend_fit_for_battle_old", "$g_friend_fit_for_battle"),
#      (assign, "$g_main_party_fit_for_battle_old", "$g_main_party_fit_for_battle"),
      (call_script, "script_party_count_fit_for_battle", "p_main_party"),
 #     (assign, "$g_main_party_fit_for_battle", reg(0)),
      (call_script, "script_collect_friendly_parties"),
      (call_script, "script_party_count_fit_for_battle", "p_collective_friends"),
      (assign, "$g_friend_fit_for_battle", reg(0)),

      (try_begin),
        (gt, "$g_ally_party", 0),
        (party_collect_attachments_to_party, "$g_ally_party", "p_collective_ally"),
#        (call_script, "script_party_count_fit_for_battle", "p_collective_ally"),
#        (val_add, "$g_friend_fit_for_battle", reg(0)),
      (try_end),
      
      (party_collect_attachments_to_party, "$g_enemy_party", "p_collective_enemy"),
      (call_script, "script_party_count_fit_for_battle", "p_collective_enemy"),
      (assign, "$g_enemy_fit_for_battle", reg(0)),
      (assign, reg11, "$g_enemy_fit_for_battle"),
      (assign, reg10, "$g_friend_fit_for_battle"),
  ]),
  
  # script_encounter_init_variables
  # Input: arg1 = troop_no
  # Output: none
  ("encounter_init_variables",
    [
      (assign, "$capture_screen_shown", 0),
      (assign, "$loot_screen_shown", 0),
      (assign, "$thanked_by_ally_leader", 0),
      (assign, "$g_battle_result", 0),
      (assign, "$cant_leave_encounter", 0),
      (assign, "$cant_talk_to_enemy", 0),
      (assign, "$last_defeated_hero", 0),
      (assign, "$last_freed_hero", 0),

      (call_script, "script_encounter_calculate_fit"),
      (call_script, "script_party_copy", "p_main_party_backup", "p_main_party"),
      (call_script, "script_party_calculate_strength", "p_main_party"),
      (assign, "$g_starting_strength_main_party", reg0),
      (call_script, "script_party_copy", "p_encountered_party_backup", "p_collective_enemy"),
      (call_script, "script_party_calculate_strength", "p_collective_enemy"),
      (assign, "$g_starting_strength_enemy_party", reg0),
#      (assign, "$g_starting_strength_ally_party", 0),
      (assign, "$g_strength_contribution_of_player", 100),

      (call_script, "script_party_copy", "p_collective_friends_backup", "p_collective_friends"),
      (call_script, "script_party_calculate_strength", "p_collective_friends"),
      (assign, "$g_starting_strength_friends", reg0),

      (store_mul, "$g_strength_contribution_of_player","$g_starting_strength_main_party", 100), # reduce contribution if we are helping someone.
      (val_div, "$g_strength_contribution_of_player","$g_starting_strength_friends"),

#      (try_begin),
#        (gt, "$g_ally_party", 0),
#        (call_script, "script_party_copy", "p_ally_party_backup", "p_collective_ally"),
#        (call_script, "script_party_calculate_strength", "p_collective_ally"),
#        (assign, "$g_starting_strength_ally_party", reg0),
#        (store_add, ":starting_strength_factor_combined","$g_starting_strength_ally_party","$g_starting_strength_main_party"),
#         (store_mul, "$g_strength_contribution_of_player","$g_starting_strength_main_party", 80), #reduce contribution if we are helping someone.
#        (val_div, "$g_strength_contribution_of_player",":starting_strength_factor_combined"),
#      (try_end),
  ]),
  
  # script_calculate_renown_value
  # Input: arg1 = troop_no
  # Output: fills $battle_renown_value
  ("calculate_renown_value",
   [
      (call_script, "script_party_calculate_strength", "p_main_party"),
      (assign, ":main_party_strength", reg0),
      (call_script, "script_party_calculate_strength", "p_collective_enemy"),
      (assign, ":enemy_strength", reg0),
      (call_script, "script_party_calculate_strength", "p_collective_friends"),
      (assign, ":friends_strength", reg0),

      (val_add, ":friends_strength", 1),
      (store_mul, ":enemy_strength_ratio", ":enemy_strength", 100),
      (val_div, ":enemy_strength_ratio", ":friends_strength"),

      (assign, ":renown_val", ":enemy_strength"),
      (val_mul, ":renown_val", ":enemy_strength_ratio"),
      (val_div, ":renown_val", 100),

      (val_mul, ":renown_val", ":main_party_strength"),
      (val_div, ":renown_val",":friends_strength"),

      (store_div, "$battle_renown_value", ":renown_val", 5),
      (val_min, "$battle_renown_value", 2500),
      (convert_to_fixed_point, "$battle_renown_value"),
      (store_sqrt, "$battle_renown_value", "$battle_renown_value"),
      (convert_from_fixed_point, "$battle_renown_value"),
      (assign, reg8, "$battle_renown_value"),
      (display_message, "@Renown value for this battle is {reg8}.",0xFFFFFFFF),
  ]),
       
  
  ##  # script_calculate_weekly_wage_for_player
  ##  # Input: none
  ##  # Output: none
  ##  ("calculate_weekly_wage_for_player",
  ##    [
  ##        (call_script, "script_calculate_weekly_party_wage", "p_main_party"),
  ##        (assign, ":result", reg0),
  ##        (try_for_parties, ":party_no"),
  ##          (store_faction_of_party, ":party_faction_local", ":party_no"),
  ##          (eq, ":party_faction_local", "fac_player_faction"),
  ##          (call_script, "script_calculate_weekly_party_wage", ":party_no"),
  ##          (val_add, ":result", reg0),
  ##        (try_end),
  ##        (assign, reg0, ":result"),
  ##  ]),
  
  
  # script_get_first_agent_with_troop_id
  # Input: arg1 = troop_no
  # Output: agent_id
  ("cf_get_first_agent_with_troop_id",
    [
      (store_script_param_1, ":troop_no"),
      #      (store_script_param_2, ":agent_no_to_begin_searching_after"),
      (assign, ":result", -1),
      (try_for_agents, ":cur_agent"),
        (eq, ":result", -1),
        ##        (try_begin),
        ##          (eq, ":cur_agent", ":agent_no_to_begin_searching_after"),
        ##          (assign, ":agent_no_to_begin_searching_after", -1),
        ##        (try_end),
        ##        (eq, ":agent_no_to_begin_searching_after", -1),
        (agent_get_troop_id, ":cur_troop_no", ":cur_agent"),
        (eq, ":cur_troop_no", ":troop_no"),
        (assign, ":result", ":cur_agent"),
      (try_end),
      (assign, reg0, ":result"),
      (neq, reg0, -1),
  ]),
  
  
  # script_cf_team_get_average_position_of_agents_with_type_to_pos1
  # Input: arg1 = team_no, arg2 = class_no (grc_everyone, grc_infantry, grc_cavalry, grc_archers, grc_heroes)
  # Output: none, pos1 = average_position (0,0,0 if there are no matching agents)
  ("cf_team_get_average_position_of_agents_with_type_to_pos1",
    [
      (store_script_param_1, ":team_no"),
      (store_script_param_2, ":class_no"),
      (assign, ":total_pos_x", 0),
      (assign, ":total_pos_y", 0),
      (assign, ":total_pos_z", 0),
      (assign, ":num_agents", 0),
      (set_fixed_point_multiplier, 100),
      (try_for_agents, ":cur_agent"),
        (agent_is_alive, ":cur_agent"),
        (agent_is_human, ":cur_agent"),
        (agent_get_team, ":cur_team_no", ":cur_agent"),
        (eq, ":cur_team_no", ":team_no"),
        (agent_get_class, ":cur_class_no", ":cur_agent"),
        (this_or_next|eq, ":class_no", grc_everyone),
        (eq, ":class_no", ":cur_class_no"),
        (agent_get_position, pos1, ":cur_agent"),
        (position_get_x, ":cur_pos_x", pos1),
        (val_add, ":total_pos_x", ":cur_pos_x"),
        (position_get_y, ":cur_pos_y", pos1),
        (val_add, ":total_pos_y", ":cur_pos_y"),
        (position_get_z, ":cur_pos_z", pos1),
        (val_add, ":total_pos_z", ":cur_pos_z"),
        (val_add, ":num_agents", 1),
      (try_end),
      (gt, ":num_agents", 1),
      (val_div, ":total_pos_x", ":num_agents"),
      (val_div, ":total_pos_y", ":num_agents"),
      (val_div, ":total_pos_z", ":num_agents"),
      (init_position, pos1),
      (position_move_x, pos1, ":total_pos_x"),
      (position_move_y, pos1, ":total_pos_y"),
      (position_move_z, pos1, ":total_pos_z"),
  ]),
  
  # script_cf_turn_windmill_fans
  # Input: arg1 = instance_no (none = 0)
  # Output: none
  ("cf_turn_windmill_fans",
    [(store_script_param_1, ":instance_no"),
      (scene_prop_get_instance, ":windmill_fan_object", "spr_windmill_fan_turning", ":instance_no"),
      (ge, ":windmill_fan_object", 0),
      (prop_instance_get_position, pos1, ":windmill_fan_object"),
      (position_rotate_y, pos1, 10),
      (prop_instance_animate_to_position, ":windmill_fan_object", pos1, 100),
      (val_add, ":instance_no", 1),
      (call_script, "script_cf_turn_windmill_fans", ":instance_no"),
  ]),
  
  # script_print_party_members
  # Input: arg1 = party_no
  # Output: s51 = output string. "noone" if the party is empty
  ("print_party_members",
    [(store_script_param_1, ":party_no"),
      (party_get_num_companion_stacks, ":num_stacks",":party_no"),
      (try_for_range, ":i_stack", 0, ":num_stacks"),
        (party_stack_get_troop_id, ":stack_troop",":party_no",":i_stack"),
        (troop_is_hero, ":stack_troop"),
        (try_begin),
          (eq, ":i_stack", 0),
          (str_store_troop_name, s51, ":stack_troop"),
        (try_end),
        (str_store_troop_name, s50, ":stack_troop"),
        (try_begin),
          (eq, ":i_stack", 1),
          (str_store_string, s51, "str_s50_and_s51"),
        (else_try),
          (gt, ":i_stack", 1),
          (str_store_string, s51, "str_s50_comma_s51"),
        (try_end),
      (try_end),
      (try_begin),
        (eq, ":num_stacks", 0),
        (str_store_string, s51, "str_noone"),
      (try_end),
  ]),
  
##  # script_print_productions_above_or_below_50
##  # Input: arg1 = center_no, arg2 = sign of the production, 1 if produced goods, -1 if consumed goods
##  # Output: s51 = output string. "nothing" if there are no productions above or below 50
##  ("print_productions_above_or_below_50",
##    [(store_script_param_1, ":center_no"),
##      (store_script_param_2, ":sign"),
##      (store_sub, ":item_to_slot", slot_town_trade_good_productions_begin, trade_goods_begin),
##      (assign, ":cur_print_index", 0),
##      (try_for_range, ":cur_goods", trade_goods_begin, trade_goods_end),
##        (store_add, ":cur_good_slot", ":cur_goods", ":item_to_slot"),
##        (party_get_slot, ":cur_production", ":center_no", ":cur_good_slot"),
##        (val_mul, ":cur_production", ":sign"),
##        (ge, ":cur_production", 50),
##        (try_begin),
##          (eq, ":cur_print_index", 0),
##          (str_store_item_name, s51, ":cur_goods"),
##        (try_end),
##        (str_store_item_name, s50, ":cur_goods"),
##        (try_begin),
##          (eq, ":cur_print_index", 1),
##          (str_store_string, s51, "str_s50_and_s51"),
##        (else_try),
##          (gt, ":cur_print_index", 1),
##          (str_store_string, s51, "str_s50_comma_s51"),
##        (try_end),
##        (val_add, ":cur_print_index", 1),
##      (try_end),
##      (try_begin),
##        (eq, ":cur_print_index", 0),
##        (str_store_string, s51, "str_nothing"),
##      (try_end),
##  ]),
  
  # script_change_banners
  # Input: none
  # Output: none
  ("change_banners",
    [(party_get_slot, ":cur_leader", "$g_encountered_party", slot_town_lord),
     (try_begin),
       (ge, ":cur_leader", 0),
       (troop_get_slot, ":troop_banner_object", ":cur_leader", slot_troop_banner_scene_prop),
       (replace_scene_props, "spr_banner_a", ":troop_banner_object"),
     (try_end),
  ]),
  
  # script_describe_relation_to_s63
  # Input: arg1 = relation (-100 .. 100)
  # Output: none
  ("describe_relation_to_s63",
    [(store_script_param_1, ":relation"),
      (store_add, ":normalized_relation", ":relation", 100),
      (val_add, ":normalized_relation", 5),
      (store_div, ":str_offset", ":normalized_relation", 10),
      (store_add, ":str_id", "str_relation_mnus_100",  ":str_offset"),
      (str_store_string, s63, ":str_id"),
  ]),
  
  # script_describe_center_relation_to_s3
  # Input: arg1 = relation (-100 .. 100)
  # Output: none
  ("describe_center_relation_to_s3",
    [(store_script_param_1, ":relation"),
      (store_add, ":normalized_relation", ":relation", 100),
      (val_add, ":normalized_relation", 5),
      (store_div, ":str_offset", ":normalized_relation", 10),
      (store_add, ":str_id", "str_center_relation_mnus_100",  ":str_offset"),
      (str_store_string, s3, ":str_id"),
  ]),

  # script_init_town_walkers
  # Input: none
  # Output: none
  ("init_town_walkers",
    [(try_begin),
       (neg|is_currently_night),
       (store_random_in_range, ":num_walkers", 8, 9),
       (try_for_range, ":cur_walker", 0, 8),
         (try_begin),
           (lt, ":cur_walker", ":num_walkers"),
           (store_random_in_range, ":walker_troop", town_walkers_begin, town_walkers_end),
         (else_try),
           (assign, ":walker_troop", -1),
         (try_end),
         (try_begin),
           (eq, ":cur_walker", 0),
           (assign, reg0, ":walker_troop"),
         (else_try),
           (eq, ":cur_walker", 1),
           (assign, reg1, ":walker_troop"),
         (else_try),
           (eq, ":cur_walker", 2),
           (assign, reg2, ":walker_troop"),
         (else_try),
           (eq, ":cur_walker", 3),
           (assign, reg3, ":walker_troop"),
         (else_try),
           (eq, ":cur_walker", 4),
           (assign, reg4, ":walker_troop"),
         (else_try),
           (eq, ":cur_walker", 5),
           (assign, reg5, ":walker_troop"),
         (else_try),
           (eq, ":cur_walker", 6),
           (assign, reg6, ":walker_troop"),
         (else_try),
           (eq, ":cur_walker", 7),
           (assign, reg7, ":walker_troop"),
         (try_end),
       (try_end),
       (shuffle_range, 0, 8),
       (set_visitor, 32, reg0),
       (set_visitor, 33, reg1),
       (set_visitor, 34, reg2),
       (set_visitor, 35, reg3),
       (set_visitor, 36, reg4),
       (set_visitor, 37, reg5),
       (set_visitor, 38, reg6),
       (set_visitor, 39, reg7),
     (try_end),
  ]),
  
  # script_init_town_walker_agents
  # Input: none
  # Output: none
  ("init_town_walker_agents",
    [(try_for_agents, ":cur_agent"),
       (agent_get_troop_id, ":cur_troop", ":cur_agent"),
       (is_between, ":cur_troop", town_walkers_begin, town_walkers_end),
       (agent_get_position, pos1, ":cur_agent"),
       (try_for_range, ":i_e_p", 9, 40),#Entry points
         (entry_point_get_position, pos2, ":i_e_p"),
         (get_distance_between_positions, ":distance", pos1, pos2),
         (lt, ":distance", 200),
         (agent_set_slot, ":cur_agent", 0, ":i_e_p"),
       (try_end),
       (call_script, "script_set_town_walker_destination", ":cur_agent"),
     (try_end),
  ]),
  
  # script_tick_town_walkers
  # Input: none
  # Output: none
  ("tick_town_walkers",
    [(try_for_agents, ":cur_agent"),
       (agent_get_troop_id, ":cur_troop", ":cur_agent"),
       (is_between, ":cur_troop", town_walkers_begin, town_walkers_end),
       (agent_get_slot, ":target_entry_point", ":cur_agent", 0),
       (entry_point_get_position, pos1, ":target_entry_point"),
       (try_begin),
         (lt, ":target_entry_point", 32),
         (init_position, pos2),
         (position_set_y, pos2, 250),
         (position_transform_position_to_parent, pos1, pos1, pos2),
       (try_end),
       (agent_get_position, pos2, ":cur_agent"),
       (get_distance_between_positions, ":distance", pos1, pos2),
       (lt, ":distance", 400),
       (assign, ":random_no", 0),
       (try_begin),
         (lt, ":target_entry_point", 32),
         (store_random_in_range, ":random_no", 0, 100),
       (try_end),
       (lt, ":random_no", 20),
       (call_script, "script_set_town_walker_destination", ":cur_agent"),
     (try_end),
  ]),


  # script_set_town_walker_destination
  # Input: arg1 = agent_no
  # Output: none
  ("set_town_walker_destination",
    [(store_script_param_1, ":agent_no"),
     (assign, reg0, 9),
     (assign, reg1, 10),
     (assign, reg2, 12),
     (assign, reg3, 32),
     (assign, reg4, 33),
     (assign, reg5, 34),
     (assign, reg6, 35),
     (assign, reg7, 36),
     (assign, reg8, 37),
     (assign, reg9, 38),
     (assign, reg10, 39),
     (try_for_agents, ":cur_agent"),
       (agent_get_troop_id, ":cur_troop", ":cur_agent"),
       (is_between, ":cur_troop", town_walkers_begin, town_walkers_end),
       (agent_get_slot, ":target_entry_point", ":cur_agent", 0),
       (try_begin),
         (eq, ":target_entry_point", 9),
         (assign, reg0, 0),
       (else_try),
         (eq, ":target_entry_point", 10),
         (assign, reg1, 0),
       (else_try),
         (eq, ":target_entry_point", 12),
         (assign, reg2, 0),
       (else_try),
         (eq, ":target_entry_point", 32),
         (assign, reg3, 0),
       (else_try),
         (eq, ":target_entry_point", 33),
         (assign, reg4, 0),
       (else_try),
         (eq, ":target_entry_point", 34),
         (assign, reg5, 0),
       (else_try),
         (eq, ":target_entry_point", 35),
         (assign, reg6, 0),
       (else_try),
         (eq, ":target_entry_point", 36),
         (assign, reg7, 0),
       (else_try),
         (eq, ":target_entry_point", 37),
         (assign, reg8, 0),
       (else_try),
         (eq, ":target_entry_point", 38),
         (assign, reg9, 0),
       (else_try),
         (eq, ":target_entry_point", 39),
         (assign, reg10, 0),
       (try_end),
     (try_end),
     (assign, ":try_limit", 100),
     (assign, ":target_entry_point", 0),
     (try_for_range, ":unused", 0, ":try_limit"),
       (shuffle_range, 0, 11),
       (gt, reg0, 0),
       (assign, ":target_entry_point", reg0),
       (assign, ":try_limit", 0),
     (try_end),
     (try_begin),
       (gt, ":target_entry_point", 0),
       (agent_set_slot, ":agent_no", 0, ":target_entry_point"),
       (entry_point_get_position, pos1, ":target_entry_point"),
       (try_begin),
         (lt, ":target_entry_point", 32),
         (init_position, pos2),
         (position_set_y, pos2, 250),
         (position_transform_position_to_parent, pos1, pos1, pos2),
       (try_end),
       (agent_set_scripted_destination, ":agent_no", pos1, 1),
       (agent_set_speed_limit, ":agent_no", 5),
     (try_end),
  ]),

##  # script_change_troop_faction
##  # Input: arg1 = troop_no, arg2 = faction_no
##  # Output: none
##  ("change_troop_faction",
##    [(store_script_param_1, ":troop_no"),
##     (store_script_param_2, ":faction_no"),
##     (troop_get_slot, ":party_no", ":troop_no", slot_troop_leaded_party),
##     (try_begin),
##       (gt, ":party_no", 0),
##       (party_set_faction, ":party_no", ":faction_no"),
##       (party_set_slot, ":party_no", slot_party_ai_state, spai_undefined),
##     (try_end),
##     (troop_set_faction, ":troop_no", ":faction_no"),
##  ]),

  # script_siege_init_ai_and_belfry
  # Input: none
  # Output: none (required for siege mission templates)
  ("siege_init_ai_and_belfry",
   [(assign, "$cur_belfry_pos", 50),
    (assign, ":cur_belfry_object_pos", slot_scene_belfry_props_begin),
    (store_current_scene, ":cur_scene"),
    #Collecting belfry objects
    (try_for_range, ":i_belfry_instance", 0, 3),
      (scene_prop_get_instance, ":belfry_object", "spr_belfry_a", ":i_belfry_instance"),
      (ge, ":belfry_object", 0),
      (scene_set_slot, ":cur_scene", ":cur_belfry_object_pos", ":belfry_object"),
      (val_add, ":cur_belfry_object_pos", 1),
    (try_end),
    (try_for_range, ":i_belfry_instance", 0, 3),
      (scene_prop_get_instance, ":belfry_object", "spr_belfry_platform_a", ":i_belfry_instance"),
      (ge, ":belfry_object", 0),
      (scene_set_slot, ":cur_scene", ":cur_belfry_object_pos", ":belfry_object"),
      (val_add, ":cur_belfry_object_pos", 1),
    (try_end),
    (try_for_range, ":i_belfry_instance", 0, 3),
      (scene_prop_get_instance, ":belfry_object", "spr_belfry_platform_b", ":i_belfry_instance"),
      (ge, ":belfry_object", 0),
      (scene_set_slot, ":cur_scene", ":cur_belfry_object_pos", ":belfry_object"),
      (val_add, ":cur_belfry_object_pos", 1),
    (try_end),
    (assign, "$belfry_rotating_objects_begin", ":cur_belfry_object_pos"),
    (try_for_range, ":i_belfry_instance", 0, 5),
      (scene_prop_get_instance, ":belfry_object", "spr_belfry_wheel", ":i_belfry_instance"),
      (ge, ":belfry_object", 0),
      (scene_set_slot, ":cur_scene", ":cur_belfry_object_pos", ":belfry_object"),
      (val_add, ":cur_belfry_object_pos", 1),
    (try_end),
    (assign, "$last_belfry_object_pos", ":cur_belfry_object_pos"),

    #Lifting up the platform  at the beginning
    (scene_prop_get_instance, ":belfry_object_to_rotate", "spr_belfry_platform_a", 0),
    
    #Moving the belfry objects to their starting position
    (entry_point_get_position,pos1,55),
    (entry_point_get_position,pos3,50),
    (try_for_range, ":i_belfry_object_pos", slot_scene_belfry_props_begin, "$last_belfry_object_pos"),
      (assign, ":pos_no", 10),
      (val_add, ":pos_no", ":i_belfry_object_pos"),
      (val_sub, ":pos_no", slot_scene_belfry_props_begin),
      (scene_get_slot, ":cur_belfry_object", ":cur_scene", ":i_belfry_object_pos"),
      (prop_instance_get_position, pos2, ":cur_belfry_object"),
      (try_begin),
        (eq, ":cur_belfry_object", ":belfry_object_to_rotate"),
        (position_rotate_x, pos2, 90),
      (try_end),
      (position_transform_position_to_local, ":pos_no", pos1, pos2),
      (position_transform_position_to_parent, pos4, pos3, ":pos_no"),
      (prop_instance_animate_to_position, ":cur_belfry_object", pos4, 1),
    (try_end),
    (assign, "$belfry_positioned", 0),
    (assign, "$belfry_num_slots_positioned", 0),
    (assign, "$belfry_num_men_pushing", 0),
  ]),

  # script_cf_siege_move_belfry
  # Input: none
  # Output: none (required for siege mission templates)
  ("cf_siege_move_belfry",
   [(neq, "$last_belfry_object_pos", slot_scene_belfry_props_begin),
    (entry_point_get_position,pos1,50),
    (entry_point_get_position,pos4,55),
    (get_distance_between_positions, ":total_distance", pos4, pos1),
    (store_current_scene, ":cur_scene"),
    (scene_get_slot, ":first_belfry_object", ":cur_scene", slot_scene_belfry_props_begin),
    (prop_instance_get_position, pos2, ":first_belfry_object"),
    (entry_point_get_position,pos1,"$cur_belfry_pos"),
    (position_transform_position_to_parent, pos3, pos1, pos10),
    (position_transform_position_to_parent, pos5, pos4, pos10),
    (get_distance_between_positions, ":cur_distance", pos2, pos3),
    (get_distance_between_positions, ":distance_left", pos2, pos5),
    (try_begin),
      (le, ":cur_distance", 10),
      (val_add, "$cur_belfry_pos", 1),
      (entry_point_get_position,pos1,"$cur_belfry_pos"),
      (position_transform_position_to_parent, pos3, pos1, pos10),
      (get_distance_between_positions, ":cur_distance", pos2, pos3),
    (try_end),
    (neq, "$cur_belfry_pos", 50),

    (assign, ":base_speed", 20),
    (store_div, ":slow_range", ":total_distance", 60),
    (store_sub, ":distance_moved", ":total_distance", ":distance_left"),

    (try_begin),
      (lt, ":distance_moved", ":slow_range"),
      (store_mul, ":base_speed", ":distance_moved", -60),
      (val_div, ":base_speed", ":slow_range"),
      (val_add, ":base_speed", 80),
    (else_try),
      (lt, ":distance_left", ":slow_range"),
      (store_mul, ":base_speed", ":distance_left", -60),
      (val_div, ":base_speed", ":slow_range"),
      (val_add, ":base_speed", 80),
    (try_end),
    (store_mul, ":belfry_speed", ":cur_distance", ":base_speed"),
    (try_begin),
      (eq, "$belfry_num_men_pushing", 0),
      (assign, ":belfry_speed", 1000000),
    (else_try),
      (val_div, ":belfry_speed", "$belfry_num_men_pushing"),
    (try_end),

    (try_begin),
      (le, "$cur_belfry_pos", 55),
      (init_position, pos3),
      (position_rotate_x, pos3, ":distance_moved"),
      (scene_get_slot, ":base_belfry_object", ":cur_scene", slot_scene_belfry_props_begin),
      (prop_instance_get_position, pos4, ":base_belfry_object"),
      (entry_point_get_position,pos1,"$cur_belfry_pos"),
      (try_for_range, ":i_belfry_object_pos", slot_scene_belfry_props_begin, "$last_belfry_object_pos"),
        (scene_get_slot, ":cur_belfry_object", ":cur_scene", ":i_belfry_object_pos"),
        (try_begin),
          (ge, ":i_belfry_object_pos", "$belfry_rotating_objects_begin"),
          (prop_instance_get_starting_position, pos5, ":base_belfry_object"),
          (prop_instance_get_starting_position, pos6, ":cur_belfry_object"),
          (position_transform_position_to_local, pos7, pos5, pos6),
          (position_transform_position_to_parent, pos5, pos4, pos7),
          (position_transform_position_to_parent, pos6, pos5, pos3),
          (prop_instance_set_position, ":cur_belfry_object", pos6),
        (else_try),
          (assign, ":pos_no", 10),
          (val_add, ":pos_no", ":i_belfry_object_pos"),
          (val_sub, ":pos_no", slot_scene_belfry_props_begin),
          (position_transform_position_to_parent, pos2, pos1, ":pos_no"),
          (prop_instance_animate_to_position, ":cur_belfry_object", pos2, ":belfry_speed"),
        (try_end),
      (try_end),
    (try_end),
    (gt, "$cur_belfry_pos", 55),
    (assign, "$belfry_positioned", 1),
  ]),

  # script_cf_siege_rotate_belfry_platform
  # Input: none
  # Output: none (required for siege mission templates)
  ("cf_siege_rotate_belfry_platform",
   [(eq, "$belfry_positioned", 1),
    (scene_prop_get_instance, ":belfry_object", "spr_belfry_platform_a", 0),
    (prop_instance_get_position, pos1, ":belfry_object"),
    (position_rotate_x, pos1, -90),
    (prop_instance_animate_to_position, ":belfry_object", pos1, 400),
    (assign, "$belfry_positioned", 2),
  ]),

  # script_cf_siege_assign_men_to_belfry
  # Input: none
  # Output: none (required for siege mission templates)
  ("cf_siege_assign_men_to_belfry",
   [(neq, "$last_belfry_object_pos", slot_scene_belfry_props_begin),
    (assign, ":end_trigger", 0),
    (try_begin),
      (lt, "$belfry_positioned", 3),
      (get_player_agent_no, ":player_agent"),
      (store_current_scene, ":cur_scene"),
      (scene_get_slot, ":first_belfry_object", ":cur_scene", slot_scene_belfry_props_begin),
      (prop_instance_get_position, pos2, ":first_belfry_object"),
      (assign, ":slot_1_positioned", 0),
      (assign, ":slot_2_positioned", 0),
      (assign, ":slot_3_positioned", 0),
      (assign, ":slot_4_positioned", 0),
      (assign, ":slot_5_positioned", 0),
      (assign, ":slot_6_positioned", 0),
      (assign, "$belfry_num_slots_positioned", 0),
      (assign, "$belfry_num_men_pushing", 0),
      (try_for_agents, ":cur_agent"),
        (try_begin),
          (agent_is_alive, ":cur_agent"),
          (agent_get_slot, ":x_pos", ":cur_agent", 1),
          (neq, ":x_pos", 0),
          (agent_get_slot, ":y_pos", ":cur_agent", 2),
          (try_begin),
            (eq, ":x_pos", -600),
            (try_begin),
              (eq, ":y_pos", 0),
              (assign, ":slot_1_positioned", 1),
            (else_try),
              (eq, ":y_pos", -200),
              (assign, ":slot_2_positioned", 1),
            (else_try),
              (assign, ":slot_3_positioned", 1),
            (try_end),
          (else_try),
            (try_begin),
              (eq, ":y_pos", 0),
              (assign, ":slot_4_positioned", 1),
            (else_try),
              (eq, ":y_pos", -200),
              (assign, ":slot_5_positioned", 1),
            (else_try),
              (assign, ":slot_6_positioned", 1),
            (try_end),
          (try_end),
          (val_add, "$belfry_num_slots_positioned", 1),
          (init_position, pos1),
          (position_move_x, pos1, ":x_pos"),
          (position_move_y, pos1, ":y_pos"),
          (init_position, pos3),
          (position_move_x, pos3, ":x_pos"),
          (position_move_y, pos3, -1000),
          (position_transform_position_to_parent, pos4, pos2, pos1),
          (position_transform_position_to_parent, pos5, pos2, pos3),
          (agent_get_position, pos6, ":cur_agent"),
          (get_distance_between_positions, ":target_distance", pos6, pos4),
          (get_distance_between_positions, ":waypoint_distance", pos6, pos5),
          (try_begin),
            (this_or_next|lt, ":target_distance", ":waypoint_distance"),
            (lt, ":waypoint_distance", 600),
            (agent_set_scripted_destination, ":cur_agent", pos4, 1),
          (else_try),
            (agent_set_scripted_destination, ":cur_agent", pos5, 1),
          (try_end),
          (try_begin),
            (le, ":target_distance", 300),
            (val_add, "$belfry_num_men_pushing", 1),
          (try_end),
        (else_try),
          (agent_get_team, ":cur_agent_team", ":cur_agent"),
          (eq, "$attacker_team", ":cur_agent_team"),
          (agent_get_position, pos1, ":cur_agent"),
          (agent_set_scripted_destination, ":cur_agent", pos1, 0),
        (try_end),
      (try_end),
      (try_begin),
        (lt, "$belfry_num_slots_positioned", 6),
        (try_for_agents, ":cur_agent"),
          (agent_is_alive, ":cur_agent"),
          (agent_get_team, ":cur_agent_team", ":cur_agent"),
          (eq, "$attacker_team", ":cur_agent_team"),
          (neq, ":player_agent", ":cur_agent"),
          (agent_get_class, ":agent_class", ":cur_agent"),
          (this_or_next|eq, ":agent_class", grc_infantry),
          (eq, ":agent_class", grc_cavalry),
          (agent_get_slot, ":x_pos", ":cur_agent", 1),
          (eq, ":x_pos", 0),
          (assign, ":y_pos", 0),
          (try_begin),
            (eq, ":slot_1_positioned", 0),
            (assign, ":x_pos", -600),
            (assign, ":y_pos", 0),
            (val_add, ":slot_1_positioned", 1),
          (else_try),
            (eq, ":slot_2_positioned", 0),
            (assign, ":x_pos", -600),
            (assign, ":y_pos", -200),
            (val_add, ":slot_2_positioned", 1),
          (else_try),
            (eq, ":slot_3_positioned", 0),
            (assign, ":x_pos", -600),
            (assign, ":y_pos", -400),
            (val_add, ":slot_3_positioned", 1),
          (else_try),
            (eq, ":slot_4_positioned", 0),
            (assign, ":x_pos", 600),
            (assign, ":y_pos", 0),
            (val_add, ":slot_4_positioned", 1),
          (else_try),
            (eq, ":slot_5_positioned", 0),
            (assign, ":x_pos", 600),
            (assign, ":y_pos", -200),
            (val_add, ":slot_5_positioned", 1),
          (else_try),
            (eq, ":slot_6_positioned", 0),
            (assign, ":x_pos", 600),
            (assign, ":y_pos", -400),
            (val_add, ":slot_6_positioned", 1),
          (try_end),
          (val_add, "$belfry_num_slots_positioned", 1),
          (agent_set_slot, ":cur_agent", 1, ":x_pos"),
          (agent_set_slot, ":cur_agent", 2, ":y_pos"),
        (try_end),
      (try_end),
      (try_begin),
        (store_mission_timer_a, ":cur_timer"),
        (gt, ":cur_timer", 20),
        (lt, "$belfry_num_slots_positioned", 6),
        (try_for_agents, ":cur_agent"),
          (agent_is_alive, ":cur_agent"),
          (agent_get_team, ":cur_agent_team", ":cur_agent"),
          (eq, "$attacker_team", ":cur_agent_team"),
          (neq, ":player_agent", ":cur_agent"),
          (agent_get_slot, ":x_pos", ":cur_agent", 1),
          (eq, ":x_pos", 0),
          (assign, ":y_pos", 0),
          (try_begin),
            (eq, ":slot_1_positioned", 0),
            (assign, ":x_pos", -600),
            (assign, ":y_pos", 0),
            (val_add, ":slot_1_positioned", 1),
          (else_try),
            (eq, ":slot_2_positioned", 0),
            (assign, ":x_pos", -600),
            (assign, ":y_pos", -200),
            (val_add, ":slot_2_positioned", 1),
          (else_try),
            (eq, ":slot_3_positioned", 0),
            (assign, ":x_pos", -600),
            (assign, ":y_pos", -400),
            (val_add, ":slot_3_positioned", 1),
          (else_try),
            (eq, ":slot_4_positioned", 0),
            (assign, ":x_pos", 600),
            (assign, ":y_pos", 0),
            (val_add, ":slot_4_positioned", 1),
          (else_try),
            (eq, ":slot_5_positioned", 0),
            (assign, ":x_pos", 600),
            (assign, ":y_pos", -200),
            (val_add, ":slot_5_positioned", 1),
          (else_try),
            (eq, ":slot_6_positioned", 0),
            (assign, ":x_pos", 600),
            (assign, ":y_pos", -400),
            (val_add, ":slot_6_positioned", 1),
          (try_end),
          (val_add, "$belfry_num_slots_positioned", 1),
          (agent_set_slot, ":cur_agent", 1, ":x_pos"),
          (agent_set_slot, ":cur_agent", 2, ":y_pos"),
        (try_end),
      (try_end),
    (else_try),
      (assign, ":end_trigger", 1),
      (try_for_agents, ":cur_agent"),
        (agent_clear_scripted_mode, ":cur_agent"),
      (try_end),
    (try_end),
    (eq, ":end_trigger", 1),
  ]),

  # script_store_movement_order_name_to_s1
  # Input: arg1 = team_no, arg2 = class_no
  # Output: s1 = order_name
  ("store_movement_order_name_to_s1",
   [(store_script_param_1, ":team_no"),
    (store_script_param_2, ":class_no"),
    (team_get_movement_order, ":cur_order", ":team_no", ":class_no"),
    (try_begin),
      (eq, ":cur_order", mordr_hold),
      (str_store_string, s1, "@Holding"),
    (else_try),
      (eq, ":cur_order", mordr_follow),
      (str_store_string, s1, "@Following"),
    (else_try),
      (eq, ":cur_order", mordr_charge),
      (str_store_string, s1, "@Charging"),
    (else_try),
      (eq, ":cur_order", mordr_advance),
      (str_store_string, s1, "@Advancing"),
    (else_try),
      (eq, ":cur_order", mordr_fall_back),
      (str_store_string, s1, "@Falling Back"),
    (else_try),
      (eq, ":cur_order", mordr_stand_closer),
      (str_store_string, s1, "@Standing Closer"),
    (else_try),
      (eq, ":cur_order", mordr_spread_out),
      (str_store_string, s1, "@Spreading Out"),
    (else_try),
      (eq, ":cur_order", mordr_stand_ground),
      (str_store_string, s1, "@Standing"),
    (else_try),
      (str_store_string, s1, "@N/A"),
    (try_end),
  ]),

  # script_store_riding_order_name_to_s1
  # Input: arg1 = team_no, arg2 = class_no
  # Output: s1 = order_name
  ("store_riding_order_name_to_s1",
   [(store_script_param_1, ":team_no"),
    (store_script_param_2, ":class_no"),
    (team_get_riding_order, ":cur_order", ":team_no", ":class_no"),
    (try_begin),
      (eq, ":cur_order", rordr_free),
      (str_store_string, s1, "@Free"),
    (else_try),
      (eq, ":cur_order", rordr_mount),
      (str_store_string, s1, "@Mount"),
    (else_try),
      (eq, ":cur_order", rordr_dismount),
      (str_store_string, s1, "@Dismount"),
    (else_try),
      (str_store_string, s1, "@N/A"),
    (try_end),
  ]),

  # script_store_weapon_usage_order_name_to_s1
  # Input: arg1 = team_no, arg2 = class_no
  # Output: s1 = order_name
  ("store_weapon_usage_order_name_to_s1",
   [(store_script_param_1, ":team_no"),
    (store_script_param_2, ":class_no"),
    (team_get_weapon_usage_order, ":cur_order", ":team_no", ":class_no"),
    (try_begin),
      (eq, ":cur_order", wordr_use_any_weapon),
      (str_store_string, s1, "@Any Weapon"),
    (else_try),
      (eq, ":cur_order", wordr_use_blunt_weapons),
      (str_store_string, s1, "@Blunt Weapons"),
    (else_try),
      (str_store_string, s1, "@N/A"),
    (try_end),
  ]),

  # script_team_give_order_from_order_panel
  # Input: arg1 = leader_agent_no, arg2 = class_no
  # Output: none
  ("team_give_order_from_order_panel",
   [(store_script_param_1, ":leader_agent_no"),
    (store_script_param_2, ":order"),
    (agent_get_team, ":team_no", ":leader_agent_no"),
    (set_show_messages, 0),
    (try_begin),
      (eq, "$g_formation_infantry_selected", 1),
      (team_give_order, ":team_no", grc_infantry, ":order"),
    (try_end),
    (try_begin),
      (eq, "$g_formation_archers_selected", 1),
      (team_give_order, ":team_no", grc_archers, ":order"),
    (try_end),
    (try_begin),
      (eq, "$g_formation_cavalry_selected", 1),
      (team_give_order, ":team_no", grc_cavalry, ":order"),
    (try_end),

    (try_begin),
      (eq, ":order", mordr_hold),
      (agent_get_position, pos1, ":leader_agent_no"),
      (try_begin),
        (eq, "$g_formation_infantry_selected", 1),
        (team_set_order_position, ":team_no", grc_infantry, pos1),
      (try_end),
      (try_begin),
        (eq, "$g_formation_archers_selected", 1),
        (team_set_order_position, ":team_no", grc_archers, pos1),
      (try_end),
      (try_begin),
        (eq, "$g_formation_cavalry_selected", 1),
        (team_set_order_position, ":team_no", grc_cavalry, pos1),
      (try_end),
    (try_end),
    (set_show_messages, 1),
  ]),  


  # script_update_order_panel
  # Input: arg1 = team_no
  # Output: none
  ("update_order_panel",
   [(store_script_param_1, ":team_no"),
    (set_fixed_point_multiplier, 1000),

    (assign, ":old_is_infantry_listening", 0),
    (try_begin),
      (class_is_listening_order, ":team_no", grc_infantry),
      (assign, ":old_is_infantry_listening", 1),
    (try_end),
    (assign, ":old_is_archers_listening", 0),
    (try_begin),
      (class_is_listening_order, ":team_no", grc_archers),
      (assign, ":old_is_archers_listening", 1),
    (try_end),
    (assign, ":old_is_cavalry_listening", 0),
    (try_begin),
      (class_is_listening_order, ":team_no", grc_cavalry),
      (assign, ":old_is_cavalry_listening", 1),
    (try_end),

    (call_script, "script_store_movement_order_name_to_s1", ":team_no", grc_infantry),
    (overlay_set_text, "$g_presentation_infantry_movement", s1),
    (call_script, "script_store_riding_order_name_to_s1", ":team_no", grc_infantry),
    (overlay_set_text, "$g_presentation_infantry_riding", s1),
    (call_script, "script_store_weapon_usage_order_name_to_s1", ":team_no", grc_infantry),
    (overlay_set_text, "$g_presentation_infantry_weapon_usage", s1),
    (call_script, "script_store_movement_order_name_to_s1", ":team_no", grc_archers),
    (overlay_set_text, "$g_presentation_archers_movement", s1),
    (call_script, "script_store_riding_order_name_to_s1", ":team_no", grc_archers),
    (overlay_set_text, "$g_presentation_archers_riding", s1),
    (call_script, "script_store_weapon_usage_order_name_to_s1", ":team_no", grc_archers),
    (overlay_set_text, "$g_presentation_archers_weapon_usage", s1),
    (call_script, "script_store_movement_order_name_to_s1", ":team_no", grc_cavalry),
    (overlay_set_text, "$g_presentation_cavalry_movement", s1),
    (call_script, "script_store_riding_order_name_to_s1", ":team_no", grc_cavalry),
    (overlay_set_text, "$g_presentation_cavalry_riding", s1),
    (call_script, "script_store_weapon_usage_order_name_to_s1", ":team_no", grc_cavalry),
    (overlay_set_text, "$g_presentation_cavalry_weapon_usage", s1),

    (try_begin),
      (eq, ":old_is_infantry_listening", 1),
      (eq, ":old_is_archers_listening", 1),
      (eq, ":old_is_cavalry_listening", 1),
      (team_set_order_listener, ":team_no", grc_everyone),
    (else_try),
      (eq, ":old_is_infantry_listening", 1),
      (team_set_order_listener, ":team_no", grc_infantry),
    (else_try),
      (eq, ":old_is_archers_listening", 1),
      (team_set_order_listener, ":team_no", grc_archers),
    (else_try),
      (eq, ":old_is_cavalry_listening", 1),
      (team_set_order_listener, ":team_no", grc_cavalry),
    (try_end),

    (position_set_y, pos1, 660),
    (position_set_x, pos1, 250),
    (overlay_set_position, "$g_presentation_infantry_movement", pos1),
    (position_set_x, pos1, 400),
    (overlay_set_position, "$g_presentation_infantry_riding", pos1),
    (position_set_x, pos1, 550),
    (overlay_set_position, "$g_presentation_infantry_weapon_usage", pos1),

    (position_set_y, pos1, 620),
    (position_set_x, pos1, 250),
    (overlay_set_position, "$g_presentation_archers_movement", pos1),
    (position_set_x, pos1, 400),
    (overlay_set_position, "$g_presentation_archers_riding", pos1),
    (position_set_x, pos1, 550),
    (overlay_set_position, "$g_presentation_archers_weapon_usage", pos1),

    (position_set_y, pos1, 580),
    (position_set_x, pos1, 250),
    (overlay_set_position, "$g_presentation_cavalry_movement", pos1),
    (position_set_x, pos1, 400),
    (overlay_set_position, "$g_presentation_cavalry_riding", pos1),
    (position_set_x, pos1, 550),
    (overlay_set_position, "$g_presentation_cavalry_weapon_usage", pos1),
  ]),


  # script_update_agent_position_on_map
  # Input: arg1 = agent_no, pos2 = map_size_pos
  # Output: none
  ("update_agent_position_on_map",
   [(store_script_param_1, ":agent_no"),
    (agent_get_slot, ":agent_overlay", ":agent_no", slot_agent_map_overlay_id),

    (get_player_agent_no, ":player_agent"),
    (try_begin),
      (le, ":agent_overlay", 0),
      (set_fixed_point_multiplier, 1000),
      (try_begin),
        (eq, ":agent_no", ":player_agent"),
        (create_mesh_overlay, reg1, "mesh_player_dot"),
        (position_set_x, pos1, 500),
        (position_set_y, pos1, 500),
        (overlay_set_size, reg1, pos1),
      (else_try),
        (create_mesh_overlay, reg1, "mesh_white_dot"),
        (position_set_x, pos1, 200),
        (position_set_y, pos1, 200),
        (overlay_set_size, reg1, pos1),
      (try_end),
      (overlay_set_alpha, reg1, 0x88),
      (agent_set_slot, ":agent_no", slot_agent_map_overlay_id, reg1),
      (assign, ":agent_overlay", reg1),
    (try_end),

    (try_begin),
      (neq, ":agent_no", ":player_agent"),
      (agent_get_party_id, ":agent_party", ":agent_no"),
      (try_begin),
        (eq, ":agent_party", "p_main_party"),
        (agent_get_class, ":agent_class", ":agent_no"),
        (try_begin),
          (eq, ":agent_class", grc_infantry),
          (overlay_set_color, ":agent_overlay", 0x8d5220),
        (else_try),
          (eq, ":agent_class", grc_archers),
          (overlay_set_color, ":agent_overlay", 0x34c6e4),
        (else_try),
          (eq, ":agent_class", grc_cavalry),
          (overlay_set_color, ":agent_overlay", 0x569619),
        (try_end),
      (else_try),
        (agent_is_ally, ":agent_no"),
        (overlay_set_color, ":agent_overlay", 0x5555FF),
      (else_try),
        (overlay_set_color, ":agent_overlay", 0xFF0000),
      (try_end),
    (try_end),

    (try_begin),
      (eq, ":agent_no", ":player_agent"),
      (agent_get_look_position, pos1, ":agent_no"),
      (position_get_rotation_around_z, ":rot", pos1),
      (init_position, pos10),
      (position_rotate_z, pos10, ":rot"),
      (overlay_set_mesh_rotation, ":agent_overlay", pos10),
      (call_script, "script_convert_3d_pos_to_map_pos"),
    (else_try),
      (agent_get_position, pos1, ":agent_no"),
      (call_script, "script_convert_3d_pos_to_map_pos"),
    (try_end),
    (overlay_set_position, ":agent_overlay", pos0),
  ]),

  # script_convert_3d_pos_to_map_pos
  # Input: pos1 = 3d_pos, pos2 = map_size_pos
  # Output: pos0 = map_pos
  ("convert_3d_pos_to_map_pos",
   [(set_fixed_point_multiplier, 1000),
    (position_transform_position_to_local, pos3, pos2, pos1),
    (position_get_x, ":agent_x_pos", pos3),
    (position_get_y, ":agent_y_pos", pos3),
    (val_div, ":agent_x_pos", "$g_battle_map_scale"),
    (val_div, ":agent_y_pos", "$g_battle_map_scale"),
    (set_fixed_point_multiplier, 1000),
    (store_sub, ":map_x", 980, "$g_battle_map_width"),
    (store_sub, ":map_y", 730, "$g_battle_map_height"),
    (val_add, ":agent_x_pos", ":map_x"),
    (val_add, ":agent_y_pos", ":map_y"),
    (position_set_x, pos0, ":agent_x_pos"),
    (position_set_y, pos0, ":agent_y_pos"),
  ]),

  # script_update_order_flags_on_map
  # Input: none
  # Output: none
  ("update_order_flags_on_map",
   [(set_fixed_point_multiplier, 1000),
    (get_player_agent_no, ":player_agent"),
    (agent_get_team, ":player_team", ":player_agent"),

    (assign, ":old_is_infantry_listening", 0),
    (try_begin),
      (class_is_listening_order, ":player_team", grc_infantry),
      (assign, ":old_is_infantry_listening", 1),
    (try_end),
    (assign, ":old_is_archers_listening", 0),
    (try_begin),
      (class_is_listening_order, ":player_team", grc_archers),
      (assign, ":old_is_archers_listening", 1),
    (try_end),
    (assign, ":old_is_cavalry_listening", 0),
    (try_begin),
      (class_is_listening_order, ":player_team", grc_cavalry),
      (assign, ":old_is_cavalry_listening", 1),
    (try_end),

    (get_scene_boundaries, pos2, pos3),

    (team_get_movement_order, ":cur_order", ":player_team", grc_infantry),
    (try_begin),
      (eq, ":cur_order", mordr_hold),
      (team_get_order_position, pos1, ":player_team", grc_infantry),
      (call_script, "script_convert_3d_pos_to_map_pos"),
      (overlay_set_alpha, "$g_battle_map_infantry_order_flag", 0xFF),
      (overlay_set_position, "$g_battle_map_infantry_order_flag", pos0),
    (else_try),
      (overlay_set_alpha, "$g_battle_map_infantry_order_flag", 0),
    (try_end),
    (team_get_movement_order, ":cur_order", ":player_team", grc_archers),
    (try_begin),
      (eq, ":cur_order", mordr_hold),
      (team_get_order_position, pos1, ":player_team", grc_archers),
      (call_script, "script_convert_3d_pos_to_map_pos"),
      (overlay_set_alpha, "$g_battle_map_archers_order_flag", 0xFF),
      (overlay_set_position, "$g_battle_map_archers_order_flag", pos0),
    (else_try),
      (overlay_set_alpha, "$g_battle_map_archers_order_flag", 0),
    (try_end),
    (team_get_movement_order, ":cur_order", ":player_team", grc_cavalry),
    (try_begin),
      (eq, ":cur_order", mordr_hold),
      (team_get_order_position, pos1, ":player_team", grc_cavalry),
      (call_script, "script_convert_3d_pos_to_map_pos"),
      (overlay_set_alpha, "$g_battle_map_cavalry_order_flag", 0xFF),
      (overlay_set_position, "$g_battle_map_cavalry_order_flag", pos0),
    (else_try),
      (overlay_set_alpha, "$g_battle_map_cavalry_order_flag", 0),
    (try_end),

    (try_begin),
      (eq, ":old_is_infantry_listening", 1),
      (eq, ":old_is_archers_listening", 1),
      (eq, ":old_is_cavalry_listening", 1),
      (team_set_order_listener, ":player_team", grc_everyone),
    (else_try),
      (eq, ":old_is_infantry_listening", 1),
      (team_set_order_listener, ":player_team", grc_infantry),
    (else_try),
      (eq, ":old_is_archers_listening", 1),
      (team_set_order_listener, ":player_team", grc_archers),
    (else_try),
      (eq, ":old_is_cavalry_listening", 1),
      (team_set_order_listener, ":player_team", grc_cavalry),
    (try_end),
  ]),

  # script_update_order_panel_checked_classes
  # Input: none
  # Output: none
  ("update_order_panel_checked_classes",
   [(get_player_agent_no, ":player_agent"),
    (agent_get_team, ":player_team", ":player_agent"),

    (try_begin),
      (class_is_listening_order, ":player_team", grc_infantry),
      (overlay_set_val, "$g_presentation_obj_4", 1),
      (assign, "$g_formation_infantry_selected", 1),
      (overlay_animate_to_alpha, "$g_presentation_obj_1", 250, 0x44),
    (else_try),
      (overlay_set_val, "$g_presentation_obj_4", 0),
      (assign, "$g_formation_infantry_selected", 0),
      (overlay_animate_to_alpha, "$g_presentation_obj_1", 250, 0),
    (try_end),
    (try_begin),
      (class_is_listening_order, ":player_team", grc_archers),
      (overlay_set_val, "$g_presentation_obj_5", 1),
      (assign, "$g_formation_archers_selected", 1),
      (overlay_animate_to_alpha, "$g_presentation_obj_2", 250, 0x44),
    (else_try),
      (overlay_set_val, "$g_presentation_obj_5", 0),
      (assign, "$g_formation_archers_selected", 0),
      (overlay_animate_to_alpha, "$g_presentation_obj_2", 250, 0),
    (try_end),
    (try_begin),
      (class_is_listening_order, ":player_team", grc_cavalry),
      (overlay_set_val, "$g_presentation_obj_6", 1),
      (assign, "$g_formation_cavalry_selected", 1),
      (overlay_animate_to_alpha, "$g_presentation_obj_3", 250, 0x44),
    (else_try),
      (overlay_set_val, "$g_presentation_obj_6", 0),
      (assign, "$g_formation_cavalry_selected", 0),
      (overlay_animate_to_alpha, "$g_presentation_obj_3", 250, 0),
    (try_end),
  ]),

  # script_update_order_panel_statistics_and_map
  # Input: none
  # Output: none
  ("update_order_panel_statistics_and_map", #TODO: Call this in every battle mission template, once per second
   [(set_fixed_point_multiplier, 1000),
    (assign, ":num_us_ready_infantry", 0),
    (assign, ":num_us_ready_archers", 0),
    (assign, ":num_us_ready_cavalry", 0),
    (assign, ":num_us_wounded_infantry", 0),
    (assign, ":num_us_wounded_archers", 0),
    (assign, ":num_us_wounded_cavalry", 0),
    (assign, ":num_us_dead_infantry", 0),
    (assign, ":num_us_dead_archers", 0),
    (assign, ":num_us_dead_cavalry", 0),
    (assign, ":num_allies_ready_men", 0),
    (assign, ":num_allies_wounded_men", 0),
    (assign, ":num_allies_dead_men", 0),
    (assign, ":num_enemies_ready_men", 0),
    (assign, ":num_enemies_wounded_men", 0),
    (assign, ":num_enemies_dead_men", 0),

    (get_player_agent_no, ":player_agent"),
    (agent_get_team, ":player_team", ":player_agent"),

    (assign, ":old_is_infantry_listening", 0),
    (try_begin),
      (class_is_listening_order, ":player_team", grc_infantry),
      (assign, ":old_is_infantry_listening", 1),
    (try_end),
    (assign, ":old_is_archers_listening", 0),
    (try_begin),
      (class_is_listening_order, ":player_team", grc_archers),
      (assign, ":old_is_archers_listening", 1),
    (try_end),
    (assign, ":old_is_cavalry_listening", 0),
    (try_begin),
      (class_is_listening_order, ":player_team", grc_cavalry),
      (assign, ":old_is_cavalry_listening", 1),
    (try_end),

    (get_scene_boundaries, pos2, pos3),

    (try_for_agents,":cur_agent"),
      (agent_is_human, ":cur_agent"),
      (agent_get_class, ":agent_class", ":cur_agent"),
      (agent_get_party_id, ":agent_party", ":cur_agent"),
      (agent_get_slot, ":agent_overlay", ":cur_agent", slot_agent_map_overlay_id),
      (try_begin),
        (eq, ":agent_party", "p_main_party"),
        (try_begin),
          (agent_is_alive, ":cur_agent"),
          (call_script, "script_update_agent_position_on_map", ":cur_agent"),
          
          (try_begin),
            (eq, ":agent_class", grc_infantry),
            (val_add, ":num_us_ready_infantry", 1),
          (else_try),
            (eq, ":agent_class", grc_archers),
            (val_add, ":num_us_ready_archers", 1),
          (else_try),
            (eq, ":agent_class", grc_cavalry),
            (val_add, ":num_us_ready_cavalry", 1),
          (try_end),
        (else_try),
          (overlay_set_alpha, ":agent_overlay", 0),
          (agent_is_wounded, ":cur_agent"),
          (try_begin),
            (eq, ":agent_class", grc_infantry),
            (val_add, ":num_us_wounded_infantry", 1),
          (else_try),
            (eq, ":agent_class", grc_archers),
            (val_add, ":num_us_wounded_archers", 1),
          (else_try),
            (eq, ":agent_class", grc_cavalry),
            (val_add, ":num_us_wounded_cavalry", 1),
          (try_end),
        (else_try),
          (try_begin),
            (eq, ":agent_class", grc_infantry),
            (val_add, ":num_us_dead_infantry", 1),
          (else_try),
            (eq, ":agent_class", grc_archers),
            (val_add, ":num_us_dead_archers", 1),
          (else_try),
            (eq, ":agent_class", grc_cavalry),
            (val_add, ":num_us_dead_cavalry", 1),
          (try_end),
        (try_end),
      (else_try),
        (agent_is_ally, ":cur_agent"),
        (try_begin),
          (agent_is_alive, ":cur_agent"),
          (call_script, "script_update_agent_position_on_map", ":cur_agent"),
          (val_add, ":num_allies_ready_men", 1),
        (else_try),
          (overlay_set_alpha, ":agent_overlay", 0),
          (agent_is_wounded, ":cur_agent"),
          (val_add, ":num_allies_wounded_men", 1),
        (else_try),
          (val_add, ":num_allies_dead_men", 1),
        (try_end),
      (else_try),
        (try_begin),
          (agent_is_alive, ":cur_agent"),
          (call_script, "script_update_agent_position_on_map", ":cur_agent"),
          (val_add, ":num_enemies_ready_men", 1),
        (else_try),
          (overlay_set_alpha, ":agent_overlay", 0),
          (agent_is_wounded, ":cur_agent"),
          (val_add, ":num_enemies_wounded_men", 1),
        (else_try),
          (val_add, ":num_enemies_dead_men", 1),
        (try_end),
      (try_end),
    (try_end),
    (assign, reg1, ":num_us_ready_infantry"),
    (assign, reg2, ":num_us_ready_archers"),
    (assign, reg3, ":num_us_ready_cavalry"),
    (store_add, ":num_us_ready_men", ":num_us_ready_infantry", ":num_us_ready_archers"),
    (val_add, ":num_us_ready_men", ":num_us_ready_cavalry"),
    (store_add, ":num_us_wounded_men", ":num_us_wounded_infantry", ":num_us_wounded_archers"),
    (val_add, ":num_us_wounded_men", ":num_us_wounded_cavalry"),
    (store_add, ":num_us_dead_men", ":num_us_dead_infantry", ":num_us_dead_archers"),
    (val_add, ":num_us_dead_men", ":num_us_dead_cavalry"),
    (assign, reg4, ":num_us_ready_men"),
    (assign, reg5, ":num_us_wounded_men"),
    (assign, reg6, ":num_us_dead_men"),
    (assign, reg7, ":num_allies_ready_men"),
    (assign, reg8, ":num_allies_wounded_men"),
    (assign, reg9, ":num_allies_dead_men"),
    (assign, reg10, ":num_enemies_ready_men"),
    (assign, reg11, ":num_enemies_wounded_men"),
    (assign, reg12, ":num_enemies_dead_men"),
    (overlay_set_text, "$g_presentation_obj_7", "@Infantry ({reg1})"),
    (overlay_set_text, "$g_presentation_obj_8", "@Archers ({reg2})"),
    (overlay_set_text, "$g_presentation_obj_9", "@Cavalry ({reg3})"),
    (overlay_set_text, "$g_battle_us_ready", "@{reg4}"),
    (overlay_set_text, "$g_battle_us_wounded", "@{reg5}"),
    (overlay_set_text, "$g_battle_us_dead", "@{reg6}"),
    (overlay_set_text, "$g_battle_allies_ready", "@{reg7}"),
    (overlay_set_text, "$g_battle_allies_wounded", "@{reg8}"),
    (overlay_set_text, "$g_battle_allies_dead", "@{reg9}"),
    (overlay_set_text, "$g_battle_enemies_ready", "@{reg10}"),
    (overlay_set_text, "$g_battle_enemies_wounded", "@{reg11}"),
    (overlay_set_text, "$g_battle_enemies_dead", "@{reg12}"),

    (assign, ":stat_position_x", 100),
    (assign, ":stat_position_y", 100),
    (val_add, ":stat_position_x", 150),
    (val_add, ":stat_position_y", 80),
    (position_set_x, pos1, ":stat_position_x"),
    (position_set_y, pos1, ":stat_position_y"),
    (overlay_set_position, "$g_battle_us_ready", pos1),
    (val_add, ":stat_position_x", 150),
    (position_set_x, pos1, ":stat_position_x"),
    (overlay_set_position, "$g_battle_us_wounded", pos1),
    (val_add, ":stat_position_x", 150),
    (position_set_x, pos1, ":stat_position_x"),
    (overlay_set_position, "$g_battle_us_dead", pos1),
    (val_add, ":stat_position_x", -300),
    (val_add, ":stat_position_y", -40),
    (position_set_x, pos1, ":stat_position_x"),
    (position_set_y, pos1, ":stat_position_y"),
    (overlay_set_position, "$g_battle_allies_ready", pos1),
    (val_add, ":stat_position_x", 150),
    (position_set_x, pos1, ":stat_position_x"),
    (overlay_set_position, "$g_battle_allies_wounded", pos1),
    (val_add, ":stat_position_x", 150),
    (position_set_x, pos1, ":stat_position_x"),
    (overlay_set_position, "$g_battle_allies_dead", pos1),
    (val_add, ":stat_position_x", -300),
    (val_add, ":stat_position_y", -40),
    (position_set_x, pos1, ":stat_position_x"),
    (position_set_y, pos1, ":stat_position_y"),
    (overlay_set_position, "$g_battle_enemies_ready", pos1),
    (val_add, ":stat_position_x", 150),
    (position_set_x, pos1, ":stat_position_x"),
    (overlay_set_position, "$g_battle_enemies_wounded", pos1),
    (val_add, ":stat_position_x", 150),
    (position_set_x, pos1, ":stat_position_x"),
    (overlay_set_position, "$g_battle_enemies_dead", pos1),

    (call_script, "script_update_order_flags_on_map"),

    (try_begin),
      (eq, ":old_is_infantry_listening", 1),
      (eq, ":old_is_archers_listening", 1),
      (eq, ":old_is_cavalry_listening", 1),
      (team_set_order_listener, ":player_team", grc_everyone),
    (else_try),
      (eq, ":old_is_infantry_listening", 1),
      (team_set_order_listener, ":player_team", grc_infantry),
    (else_try),
      (eq, ":old_is_archers_listening", 1),
      (team_set_order_listener, ":player_team", grc_archers),
    (else_try),
      (eq, ":old_is_cavalry_listening", 1),
      (team_set_order_listener, ":player_team", grc_cavalry),
    (try_end),
  ]),


  # script_consume_food
  # Input: arg1: order of the food to be consumed
  # Output: none
  ("consume_food",
   [(store_script_param, ":selected_food", 1),
    (troop_get_inventory_capacity, ":capacity", "trp_player"),
    (try_for_range, ":cur_slot", 0, ":capacity"),
      (troop_get_inventory_slot, ":cur_item", "trp_player", ":cur_slot"),
      (is_between, ":cur_item", morale_boosters_begin, morale_boosters_end),
      (item_slot_eq, ":cur_item", slot_item_is_checked, 0),
      (item_set_slot, ":cur_item", slot_item_is_checked, 1),
      (val_sub, ":selected_food", 1),
      (lt, ":selected_food", 0),
      (assign, ":capacity", 0),
      (troop_inventory_slot_get_item_amount, ":cur_amount", "trp_player", ":cur_slot"),
      (val_sub, ":cur_amount", 1),
      (troop_inventory_slot_set_item_amount, "trp_player", ":cur_slot", ":cur_amount"),
    (try_end),
    ]),

  # script_calculate_troop_score_for_center
  # Input: arg1 = troop_no, arg2 = center_no
  # Output: reg0 = score
  ("calculate_troop_score_for_center",
   [(store_script_param, ":troop_no", 1),
    (store_script_param, ":center_no", 2),
    (assign, ":num_center_points", 1),
    (try_for_range, ":cur_center", centers_begin, centers_end),
      (assign, ":center_owned", 0),
      (try_begin),
        (eq, ":troop_no", "trp_player"),
        (party_slot_eq, ":cur_center", slot_town_lord, stl_reserved_for_player),
        (assign, ":center_owned", 1),
      (try_end),
      (this_or_next|party_slot_eq, ":cur_center", slot_town_lord, ":troop_no"),
      (eq, ":center_owned", 1),
      (try_begin),
        (party_slot_eq, ":cur_center", slot_party_type, spt_town),
        (val_add, ":num_center_points", 4),
      (else_try),
        (party_slot_eq, ":cur_center", slot_party_type, spt_castle),
        (val_add, ":num_center_points", 2),
      (else_try),
        (val_add, ":num_center_points", 1),
      (try_end),
    (try_end),
    (troop_get_slot, ":troop_renown", ":troop_no", slot_troop_renown),
    (store_add, ":score", 500, ":troop_renown"),
    (val_div, ":score", ":num_center_points"),
    (store_random_in_range, ":random", 50, 100),
    (val_mul, ":score", ":random"),
    (try_begin),
      (party_slot_eq, ":center_no", slot_center_last_taken_by_troop, ":troop_no"),
      (val_mul, ":score", 3),
      (val_div, ":score", 2),
    (try_end),
    (try_begin),
      (eq, ":troop_no", "trp_player"),
      (faction_get_slot, ":faction_leader", "$players_kingdom"),
      (troop_get_slot, ":leader_relation", ":faction_leader", slot_troop_player_relation),
      (val_mul, ":leader_relation", 2),
      (val_add, ":score", ":leader_relation"),
    (try_end),
    (assign, reg0, ":score"),
    ]),
  

  # script_assign_lords_to_empty_centers
  # Input: none
  # Output: none
  ("assign_lords_to_empty_centers",
   [(try_for_range, ":cur_center", centers_begin, centers_end),
      (party_get_slot, ":center_lord", ":cur_center", slot_town_lord),
      (this_or_next|eq, ":center_lord", stl_unassigned),
      (eq, ":center_lord", stl_rejected_by_player),
    
      (store_faction_of_party, ":center_faction", ":cur_center"),
      (is_between, ":center_faction", kingdoms_begin, kingdoms_end),
      (neg|faction_slot_eq, ":center_faction", slot_faction_leader, "trp_player"),

      (assign, ":best_lord", -1),
      (assign, ":best_lord_score", -1),
      (try_begin),
        (eq, ":center_lord", stl_unassigned),
        (try_begin),
          (eq, "$players_kingdom", ":center_faction"),
          (assign, ":best_lord", stl_reserved_for_player),
          (call_script, "script_calculate_troop_score_for_center", "trp_player", ":cur_center"),
          (assign, ":best_lord_score", reg0),
        (try_end),
      (try_end),
    
      (try_for_range, ":cur_troop", kingdom_heroes_begin, kingdom_heroes_end),
        (troop_slot_eq, ":cur_troop", slot_troop_occupation, slto_kingdom_hero),
        (store_troop_faction, ":troop_faction", ":cur_troop"),
        (eq, ":troop_faction", ":center_faction"),

        (call_script, "script_calculate_troop_score_for_center", ":cur_troop", ":cur_center"),
        (assign, ":score", reg0),

        (gt, ":score", ":best_lord_score"),
        (assign, ":best_lord_score", ":score"),
        (assign, ":best_lord", ":cur_troop"),
      (try_end),
      (try_begin),
        (ge, ":best_lord", 0),
        (str_store_party_name, s1, ":cur_center"),
        (str_store_troop_name, s2, ":best_lord"),
        (call_script, "script_give_center_to_lord", ":cur_center", ":best_lord"),
      (else_try),
        (eq, ":best_lord", stl_reserved_for_player),
        (party_set_slot, ":cur_center", slot_town_lord, stl_reserved_for_player),
      (try_end),
    (try_end),
    ]),


  # script_create_village_farmer_party
  # Input: arg1 = village_no
  # Output: reg0 = party_no
  ("create_village_farmer_party",
   [(store_script_param, ":village_no", 1),
    (party_get_slot, ":town_no", ":village_no", slot_village_market_town),
    
    (store_faction_of_party, ":party_faction_local", ":town_no"),
    (set_spawn_radius, 0),
    (spawn_around_party, ":village_no", "pt_village_farmers"),
    (assign, ":new_party", reg0),
      
    (party_set_faction, ":new_party", ":party_faction_local"),
    (party_set_slot, ":new_party", slot_party_home_center, ":village_no"),
    (party_set_slot, ":new_party", slot_party_type, spt_village_farmer),
    (party_set_slot, ":new_party", slot_party_ai_state, spai_trading_with_town),
    (party_set_slot, ":new_party", slot_party_ai_object, ":town_no"),
    (party_set_ai_behavior, ":new_party", ai_bhvr_travel_to_party),
    (party_set_ai_object, ":new_party", ":town_no"),
    (party_set_flags, ":new_party", pf_default_behavior, 0),
    (store_sub, ":item_to_price_slot", slot_town_trade_good_prices_begin, trade_goods_begin),
    (try_for_range, ":cur_goods", trade_goods_begin, trade_goods_end),
      (store_add, ":cur_good_price_slot", ":cur_goods", ":item_to_price_slot"),
      (party_get_slot, ":cur_village_price", ":village_no", ":cur_good_price_slot"),
      (party_set_slot, ":new_party", ":cur_good_price_slot", ":cur_village_price"),
    (try_end),
    (assign, reg0, ":new_party"),
    ]),

  #script_do_party_center_trade
  # INPUT: arg1 = party_no, arg2 = center_no, arg3 = percentage_change_in_center
  # OUTPUT: reg0 = total_change
  ("do_party_center_trade",
    [
      (store_script_param, ":party_no", 1),
      (store_script_param, ":center_no", 2),
      (store_script_param, ":percentage_change", 3),
      (assign, ":total_change", 0),
      (store_sub, ":item_to_price_slot", slot_town_trade_good_prices_begin, trade_goods_begin),
      (try_for_range, ":cur_good", trade_goods_begin, trade_goods_end),
        (store_add, ":cur_good_price_slot", ":cur_good", ":item_to_price_slot"),
        (party_get_slot, ":cur_merchant_price", ":party_no", ":cur_good_price_slot"),
        (party_get_slot, ":cur_center_price", ":center_no", ":cur_good_price_slot"),
        (store_sub, ":price_dif", ":cur_merchant_price", ":cur_center_price"),
        (assign, ":cur_change", ":price_dif"),
        (val_abs, ":cur_change"),
        (val_add, ":total_change", ":cur_change"),
        (val_mul, ":cur_change", ":percentage_change"),
        (val_div, ":cur_change", 100),
        (try_begin),
          (lt, ":price_dif", 0),
          (val_mul, ":cur_change", -1),
        (try_end),
        (val_add, ":cur_center_price", ":cur_change"),
        (party_set_slot, ":center_no", ":cur_good_price_slot", ":cur_center_price"),
        (party_set_slot, ":party_no", ":cur_good_price_slot", ":cur_center_price"),
      (try_end),
      (assign, reg0, ":total_change"),
  ]),

  #script_player_join_faction
  # INPUT: arg1 = faction_no
  # OUTPUT: none
  ("player_join_faction",
    [
      (store_script_param, ":faction_no", 1),
      (assign,"$players_kingdom",":faction_no"),
      (try_for_range,":other_kingdom",kingdoms_begin,kingdoms_end),
        (try_begin),
          (neq, ":other_kingdom", ":faction_no"),
          (store_relation, ":other_kingdom_reln", ":other_kingdom", ":faction_no"),
        (else_try),
          (store_relation, ":other_kingdom_reln", "fac_player_faction", ":other_kingdom"),
          (val_max, ":other_kingdom_reln", 12),
        (try_end),
        (set_relation,":other_kingdom","fac_player_faction", ":other_kingdom_reln"),
      (try_end),
      (try_for_range, ":cur_center", centers_begin, centers_end),
        #Give center to kingdom if player is the owner
        (party_slot_eq, ":cur_center", slot_town_lord, "trp_player"),
        (party_set_faction, ":cur_center", ":faction_no"),
      (try_end),
      (assign, "$g_player_banner_granted", 1),
      ]),

##  #script_player_leave_faction
##  # INPUT: none
##  # OUTPUT: none
##  ("player_leave_faction",
##    [
##      (try_for_range, ":cur_center", centers_begin, centers_end),
##        (try_begin),
##          (party_slot_eq, ":cur_center", slot_party_type, spt_village),
##          (try_begin),
##            (party_get_slot, ":bound_town", ":cur_center", slot_village_bound_center),
##            (try_begin),
##              #Give village to player if player is the owner of its bound town
##              (party_slot_eq, ":bound_town", slot_town_lord, "trp_player"),
##              (party_set_faction, ":cur_center", "fac_player_faction"),
##            (else_try),
##              #Give village to kingdom if player is not the owner of its bound town
##              (party_slot_eq, ":cur_center", slot_town_lord, "trp_player"),
##              (party_set_faction, ":cur_center", "$players_kingdom"),
##            (try_end),
##          (try_end),
##        (else_try),
##          #Give center to player if player is the owner
##          (party_slot_eq, ":cur_center", slot_town_lord, "trp_player"),
##          (party_set_faction, ":cur_center", "fac_player_faction"),
##        (try_end),
##      (try_end),
##      (assign,"$players_kingdom",0),
##      ]),

##  #script_agent_reassign_team
##  # INPUT: arg1 = agent_no
##  # OUTPUT: none
##  ("agent_reassign_team",
##    [(store_script_param, ":agent_no", 1),
##     (try_begin),
##       (agent_is_human, ":agent_no"),
##       (agent_get_party_id, ":party_no", ":agent_no"),
##       (agent_get_team, ":old_team_no", ":agent_no"),
##       (try_begin),
##         (eq, ":old_team_no", 0),
##         (neq, ":party_no", "p_main_party"),
##         (agent_set_team, ":agent_no", 2),
##       (try_end),
##     (try_end),
##      ]),

  #script_start_quest
  # INPUT: arg1 = quest_no, arg2 = giver_troop_no, s2 = description_text
  # OUTPUT: none
  ("start_quest",
    [(store_script_param, ":quest_no", 1),
     (store_script_param, ":giver_troop_no", 2),
     (try_begin),
       (is_between, ":giver_troop_no", kingdom_heroes_begin, kingdom_heroes_end),
       (str_store_troop_name_link, s4, ":giver_troop_no"),
     (else_try),
       (str_store_troop_name, s4, ":giver_troop_no"),
     (try_end),
     (str_store_string, s3, "@Given by: {s4}"),
     (str_store_date, s5, 0),
     (str_store_string, s4, "@Given on: {s5}"),
     (add_quest_note_from_sreg, ":quest_no", 1, s4, 0),
     (add_quest_note_from_sreg, ":quest_no", 2, s3, 0),
     (add_quest_note_from_sreg, ":quest_no", 3, s2, 0),
     (start_quest, ":quest_no"),
     (display_message, "str_quest_log_updated"),
      ]),

  #script_report_quest_troop_positions
  # INPUT: arg1 = quest_no, arg2 = troop_no
  # OUTPUT: none
  ("report_quest_troop_positions",
    [(store_script_param, ":quest_no", 1),
     (store_script_param, ":troop_no", 2),
     (try_begin),
       (call_script, "script_get_information_about_troops_position", ":troop_no", 1),
       (str_store_string, s5, "@At the time quest was given:^{s1}"),
       (add_quest_note_from_sreg, ":quest_no", 4, s5, 1),
     (try_end),
     ]),
   
  #script_end_quest
  # INPUT: arg1 = quest_no
  # OUTPUT: none
  ("end_quest",
    [(store_script_param, ":quest_no", 1),
     (str_clear, s1),
     (add_quest_note_from_sreg, ":quest_no", 1, s1, 0),
     (add_quest_note_from_sreg, ":quest_no", 2, s1, 0),
     (add_quest_note_from_sreg, ":quest_no", 3, s1, 0),
     (add_quest_note_from_sreg, ":quest_no", 4, s1, 0),
     (complete_quest, ":quest_no"),
      ]),

##  #script_get_available_mercenary_troop_and_amount_of_center
##  # INPUT: arg1 = center_no
##  # OUTPUT: reg0 = mercenary_troop_type, reg1 = amount
##  ("get_available_mercenary_troop_and_amount_of_center",
##    [(store_script_param, ":center_no", 1),
##     (party_get_slot, ":mercenary_troop", ":center_no", slot_center_mercenary_troop_type),
##     (party_get_slot, ":mercenary_amount", ":center_no", slot_center_mercenary_troop_amount),
##     (party_get_free_companions_capacity, ":free_capacity", "p_main_party"),
##     (val_min, ":mercenary_amount", ":free_capacity"),
##     (store_troop_gold, ":cur_gold", "trp_player"),
##     (call_script, "script_game_get_join_cost", ":mercenary_troop"),
##     (assign, ":join_cost", reg0),
##     (try_begin),
##       (gt, ":join_cost", 0),
##       (val_div, ":cur_gold", ":join_cost"),
##       (val_min, ":mercenary_amount", ":cur_gold"),
##     (try_end),
##     (assign, reg0, ":mercenary_troop"),
##     (assign, reg1, ":mercenary_amount"),
##     ]),
##

  #script_update_village_market_towns
  # INPUT: none
  # OUTPUT: none
  ("update_village_market_towns",
    [(try_for_range, ":cur_village", villages_begin, villages_end),
       (store_faction_of_party, ":village_faction", ":cur_village"),
       (assign, ":min_dist", 999999),
       (assign, ":min_dist_town", -1),
       (try_for_range, ":cur_town", towns_begin, towns_end),
         (store_faction_of_party, ":town_faction", ":cur_town"),
         (eq, ":town_faction", ":village_faction"),
         (store_distance_to_party_from_party, ":cur_dist", ":cur_village", ":cur_town"),
         (lt, ":cur_dist", ":min_dist"),
         (assign, ":min_dist", ":cur_dist"),
         (assign, ":min_dist_town", ":cur_town"),
       (try_end),
       (gt, ":min_dist_town", -1),
       (party_set_slot, ":cur_village", slot_village_market_town, ":min_dist_town"),
     (try_end),
     ]),

      

  #script_update_mercenary_units_of_towns
  # INPUT: none
  # OUTPUT: none
  ("update_mercenary_units_of_towns",
    [(try_for_range, ":town_no", towns_begin, towns_end),
      (store_random_in_range, ":troop_no", mercenary_troops_begin, mercenary_troops_end),
      (party_set_slot, ":town_no", slot_center_mercenary_troop_type, ":troop_no"),
      (store_random_in_range, ":amount", 3, 8),
      (party_set_slot, ":town_no", slot_center_mercenary_troop_amount, ":amount"),
    (try_end),
     ]),
     
  #script_update_volunteer_troops_in_village
  # INPUT: none
  # OUTPUT: none
  ("update_volunteer_troops_in_village",
    [
       (store_script_param, ":center_no", 1),
       (party_get_slot, ":player_relation", ":center_no", slot_center_player_relation),
       (party_get_slot, ":center_culture", ":center_no", slot_center_culture),
       (faction_get_slot, ":volunteer_troop", ":center_culture", slot_faction_tier_1_troop),
       (assign, ":volunteer_troop_tier", 1),
       (store_div, ":tier_upgrades", ":player_relation", 10),
       (try_for_range, ":unused", 0, ":tier_upgrades"),
         (store_random_in_range, ":random_no", 0, 100),
         (lt, ":random_no", 10),
         (store_random_in_range, ":random_no", 0, 2),
         (troop_get_upgrade_troop, ":upgrade_troop_no", ":volunteer_troop", ":random_no"),
         (try_begin),
           (lt, ":upgrade_troop_no", 0),
           (troop_get_upgrade_troop, ":upgrade_troop_no", ":volunteer_troop", 0),
         (try_end),
         (ge, ":upgrade_troop_no", 0),
         (val_add, ":volunteer_troop_tier"),
         (assign, ":volunteer_troop", ":upgrade_troop_no"),
       (try_end),
       
       (assign, ":upper_limit", 5),
       (try_begin),
         (ge, ":player_relation", 5),
         (val_add, ":upper_limit", 18),
         (val_add, ":upper_limit", ":player_relation"),
         (val_div, ":upper_limit", 2),
       (else_try),
         (lt, ":player_relation", 0),
         (assign, ":upper_limit", 0),
       (try_end),

       (val_mul, ":upper_limit", 3),   
       (store_add, ":amount_random_divider", 2, ":volunteer_troop_tier"),
       (val_div, ":upper_limit", ":amount_random_divider"),
       
       (store_random_in_range, ":amount", 0, ":upper_limit"),
       (party_set_slot, ":center_no", slot_center_volunteer_troop_type, ":volunteer_troop"),
       (party_set_slot, ":center_no", slot_center_volunteer_troop_amount, ":amount"),
     ]),

  #script_update_companion_candidates_in_taverns
  # INPUT: none
  # OUTPUT: none
  ("update_companion_candidates_in_taverns",
    [(try_for_range, ":town_no", towns_begin, towns_end),
       (party_set_slot, ":town_no", slot_center_companion_candidate, 0),
     (try_end),
     
     (try_for_range, ":troop_no", companions_begin, companions_end),
       (troop_slot_eq, ":troop_no", slot_troop_occupation, 0),
       (store_random_in_range, ":town_no", towns_begin, towns_end),
       (party_set_slot, ":town_no", slot_center_companion_candidate, ":troop_no"),
     (try_end),
     ]),

  #script_update_ransom_brokers
  # INPUT: none
  # OUTPUT: none
  ("update_ransom_brokers",
    [(try_for_range, ":town_no", towns_begin, towns_end),
       (party_set_slot, ":town_no", slot_center_ransom_broker, 0),
     (try_end),
     
     (try_for_range, ":troop_no", ransom_brokers_begin, ransom_brokers_end),
       (store_random_in_range, ":town_no", towns_begin, towns_end),
       (party_set_slot, ":town_no", slot_center_ransom_broker, ":troop_no"),
     (try_end),
     ]),

  #script_update_tavern_travelers
  # INPUT: none
  # OUTPUT: none
  ("update_tavern_travelers",
    [(try_for_range, ":town_no", towns_begin, towns_end),
       (party_set_slot, ":town_no", slot_center_tavern_traveler, 0),
     (try_end),
     
     (try_for_range, ":troop_no", tavern_travelers_begin, tavern_travelers_end),
       (store_random_in_range, ":town_no", towns_begin, towns_end),
       (party_set_slot, ":town_no", slot_center_tavern_traveler, ":troop_no"),
       (assign, ":done", 0),
       (try_for_range, ":unused", 0, 5),
         (eq, ":done", 0),
         (store_random_in_range, ":info_faction", kingdoms_begin, kingdoms_end),
         (neq, ":info_faction", "$players_kingdom"),
         (party_set_slot, ":town_no", slot_center_traveler_info_faction, ":info_faction"),
         (assign, ":done", 1),
       (try_end),
     (try_end),
     ]),
  
  #script_update_tavern_minstels
  # INPUT: none
  # OUTPUT: none
  ("update_tavern_minstels",
    [(try_for_range, ":town_no", towns_begin, towns_end),
       (party_set_slot, ":town_no", slot_center_tavern_minstrel, 0),
     (try_end),
     
     (try_for_range, ":troop_no", tavern_minstrels_begin, tavern_minstrels_end),
       (store_random_in_range, ":town_no", towns_begin, towns_end),
       (party_set_slot, ":town_no", slot_center_tavern_minstrel, ":troop_no"),
     (try_end),
     ]),
 
  #script_update_faction_notes
  # INPUT: faction_no
  # OUTPUT: none
  ("update_faction_notes",
    [(store_script_param, ":faction_no", 1),
     (try_begin),
       (is_between, ":faction_no", kingdoms_begin, kingdoms_end),
       (faction_get_slot, ":faction_leader", ":faction_no", slot_faction_leader),
       (str_store_faction_name, s5, ":faction_no"),
       (str_store_troop_name_link, s6, ":faction_leader"),
       (assign, ":num_centers", 0),
       (str_store_string, s8, "@none"),
       (try_for_range_backwards, ":cur_center", centers_begin, centers_end),
         (store_faction_of_party, ":center_faction", ":cur_center"),
         (eq, ":center_faction", ":faction_no"),
         (try_begin),
           (eq, ":num_centers", 0),
           (str_store_party_name_link, s8, ":cur_center"),
         (else_try),
           (eq, ":num_centers", 1),
           (str_store_party_name_link, s7, ":cur_center"),
           (str_store_string, s8, "@{s7} and {s8}"),
         (else_try),
           (str_store_party_name_link, s7, ":cur_center"),
           (str_store_string, s8, "@{s7}, {s8}"),
         (try_end),
         (val_add, ":num_centers", 1),
       (try_end),
       (assign, ":num_members", 0),
       (str_store_string, s10, "@noone"),
       (try_for_range_backwards, ":cur_troop", kingdom_heroes_begin, kingdom_heroes_end),
         (store_troop_faction, ":troop_faction", ":cur_troop"),
         (eq, ":troop_faction", ":faction_no"),
         (neq, ":cur_troop", ":faction_leader"),
         (try_begin),
           (eq, ":num_members", 0),
           (str_store_troop_name_link, s10, ":cur_troop"),
         (else_try),
           (eq, ":num_members", 1),
           (str_store_troop_name_link, s9, ":cur_troop"),
           (str_store_string, s10, "@{s9} and {s10}"),
         (else_try),
           (str_store_troop_name_link, s9, ":cur_troop"),
           (str_store_string, s10, "@{s9}, {s10}"),
         (try_end),
         (val_add, ":num_members", 1),
       (try_end),
       (str_store_string, s12, "@noone"),
       (assign, ":num_enemies", 0),
       (try_for_range_backwards, ":cur_faction", kingdoms_begin, kingdoms_end),
         (store_relation, ":cur_relation", ":cur_faction", ":faction_no"),
         (le, ":cur_relation", -10),
         (try_begin),
           (eq, ":num_enemies", 0),
           (str_store_faction_name_link, s12, ":cur_faction"),
         (else_try),
           (eq, ":num_enemies", 1),
           (str_store_faction_name_link, s11, ":cur_faction"),
           (str_store_string, s12, "@{s11} and {s12}"),
         (else_try),
           (str_store_faction_name_link, s11, ":cur_faction"),
           (str_store_string, s12, "@{s11}, {s12}"),
         (try_end),
         (val_add, ":num_enemies", 1),
       (try_end),
       (add_faction_note_from_sreg, ":faction_no", 0, "@{s5} is ruled by {s6}.^It occupies {s8}.^Its vassals are {s10}.{s5} is at war with {s12}.", 0),
     (try_end),
     ]),

  #script_update_faction_traveler_notes
  # INPUT: faction_no
  # OUTPUT: none
  ("update_faction_traveler_notes",
    [(store_script_param, ":faction_no", 1),
     (assign, ":total_men", 0),
     (try_for_parties, ":cur_party"),
       (store_faction_of_party, ":center_faction", ":cur_party"),
       (eq, ":center_faction", ":faction_no"),
       (party_get_num_companions, ":num_men", ":cur_party"),
       (val_add, ":total_men", ":num_men"),
     (try_end),
     (str_store_faction_name, s5, ":faction_no"),
     (assign, reg1, ":total_men"),
     (add_faction_note_from_sreg, ":faction_no", 1, "@{s5} has a strength of {reg1} men in total.", 1),
     ]),


  #script_update_troop_notes
  # INPUT: troop_no
  # OUTPUT: none
  ("update_troop_notes",
    [(store_script_param, ":troop_no", 1),
     (str_store_troop_name, s4, ":troop_no"),
     (store_troop_faction, ":troop_faction", ":troop_no"),
     (faction_get_slot, ":faction_leader", ":troop_faction", slot_faction_leader),
     (str_store_troop_name_link, s5, ":faction_leader"),
     (str_store_faction_name_link, s6, ":troop_faction"),
     (assign, reg4, 0),
     (assign, reg6, 0),
     (try_begin),
       (eq, ":troop_faction", "fac_player_faction"),
       (assign, reg6, 1),
     (else_try),
       (eq, ":faction_leader", ":troop_no"),
       (assign, reg4, 1),
     (try_end),
     (assign, ":num_centers", 0),
     (str_store_string, s8, "@nowhere"),
     (try_for_range_backwards, ":cur_center", centers_begin, centers_end),
       (party_slot_eq, ":cur_center", slot_town_lord, ":troop_no"),
       (try_begin),
         (eq, ":num_centers", 0),
         (str_store_party_name_link, s8, ":cur_center"),
       (else_try),
         (eq, ":num_centers", 1),
         (str_store_party_name_link, s7, ":cur_center"),
         (str_store_string, s8, "@{s7} and {s8}"),
       (else_try),
         (str_store_party_name_link, s7, ":cur_center"),
         (str_store_string, s8, "@{s7}, {s8}"),
       (try_end),
       (val_add, ":num_centers", 1),
     (try_end),
     (troop_get_type, reg3, ":troop_no"),
     (troop_get_slot, reg5, ":troop_no", slot_troop_renown),
     (add_troop_note_from_sreg, ":troop_no", 0, "@{reg6?:{reg4?{s4} is the leader of {s6}.^:{s4} is a vassal of {s5} of {s6}.^}}Renown: {reg5}.^{reg3?Her:His} fiefs are: {s8}.", 0),
     ]),


  #script_update_center_notes
  # INPUT: center_no
  # OUTPUT: none
  ("update_center_notes",
    [(store_script_param, ":center_no", 1),

     (party_get_slot, ":lord_troop", ":center_no", slot_town_lord),
     (store_troop_faction, ":lord_faction", ":lord_troop"),
     (str_store_troop_name_link, s1, ":lord_troop"),
     (try_begin),
       (eq, ":lord_troop", "trp_player"),
       (str_store_faction_name_link, s2, "$players_kingdom"),
     (else_try),
       (str_store_faction_name_link, s2, ":lord_faction"),
     (try_end),
     (add_party_note_from_sreg, ":center_no", 0, "@Owned by {s1} of {s2}.", 0),
     ]),
      

  #script_update_center_recon_notes
  # INPUT: center_no
  # OUTPUT: none
  ("update_center_recon_notes",
    [(store_script_param, ":center_no", 1),
     (assign, reg4, 0),
     (try_begin),
       #(this_or_next|is_between, ":center_no", towns_begin, towns_end),
       #(is_between, ":center_no", castles_begin, castles_end),
	   (is_between, ":center_no", towns_begin, towns_end),
       (party_get_slot, ":center_food_store", ":center_no", slot_party_food_store),
       (call_script, "script_center_get_food_consumption", ":center_no"),
       (assign, ":food_consumption", reg0),
       (store_div, reg6, ":center_food_store", ":food_consumption"),
       (assign, reg4, 1),
     (try_end),
     (party_collect_attachments_to_party, ":center_no", "p_collective_ally"),
     (party_get_num_companions, reg5, "p_collective_ally"),
     (add_party_note_from_sreg, ":center_no", 1, "@Current garrison consists of {reg5} men.{reg4?^Has food stock for {reg6} days.:}", 1),
     ]),

  #script_spawn_bandits
  # INPUT: none
  # OUTPUT: none
  ("spawn_bandits",
    [
#	(set_spawn_radius,1),
#     (try_begin),
#       (store_num_parties_of_template, ":num_parties", "pt_mountain_bandits"),
#       (lt,":num_parties",10),
#       (store_random,":spawn_point",num_mountain_bandit_spawn_points),
#       (val_add,":spawn_point","p_mountain_bandit_spawn_point"),
#       (spawn_around_party,":spawn_point","pt_mountain_bandits"),
#     (try_end),
#     (try_begin),
#       (store_num_parties_of_template, ":num_parties", "pt_forest_bandits"),
#       (lt,":num_parties",10),
#       (store_random,":spawn_point",num_mountain_bandit_spawn_points),
#       (val_add,":spawn_point","p_forest_bandit_spawn_point"),
#       (spawn_around_party,":spawn_point","pt_forest_bandits"),
#     (try_end),
#     (try_begin),
#       (store_num_parties_of_template, ":num_parties", "pt_sea_raiders"),
#       (lt,":num_parties",10),
#       (store_random,":spawn_point",num_sea_raider_spawn_points),
#       (val_add,":spawn_point","p_sea_raider_spawn_point_1"),
#       (spawn_around_party,":spawn_point","pt_sea_raiders"),
#     (try_end),
#     (try_begin),
#       (store_num_parties_of_template, ":num_parties", "pt_steppe_bandits"),
#       (lt,":num_parties",10),
#       (store_random,":spawn_point",num_steppe_bandit_spawn_points),
#       (val_add,":spawn_point","p_steppe_bandit_spawn_point"),
#       (spawn_around_party,":spawn_point","pt_steppe_bandits"),
#     (try_end),
     ]),

  #script_count_mission_casualties_from_agents
  # INPUT: none
  # OUTPUT: none
  ("count_mission_casualties_from_agents",
    [(party_clear, "p_player_casualties"),
     (party_clear, "p_enemy_casualties"),
     (party_clear, "p_ally_casualties"),
     (assign, "$any_allies_at_the_last_battle", 0),
     (try_for_agents, ":cur_agent"),
       (agent_is_human, ":cur_agent"),
       (agent_get_party_id, ":agent_party", ":cur_agent"),
       (try_begin),
         (neq, ":agent_party", "p_main_party"),
         (agent_is_ally, ":cur_agent"),
##SG qixi
         (try_begin),
           (ge,"$use_qixi",1),
           (agent_get_slot,":qixi_slot",":cur_agent",slot_agent_is_not_reinforcement),
           (eq,":qixi_slot",2),
         (else_try),
##SG qixi
           (assign, "$any_allies_at_the_last_battle", 1),
         (try_end),##SG qixi
       (try_end),
       (neg|agent_is_alive, ":cur_agent"),
       (agent_get_troop_id, ":agent_troop_id", ":cur_agent"),
       (try_begin),
         (eq, ":agent_party", "p_main_party"),
         (party_add_members, "p_player_casualties", ":agent_troop_id", 1),
         (try_begin),
           (agent_is_wounded, ":cur_agent"),
           (party_wound_members, "p_player_casualties", ":agent_troop_id", 1),
         (try_end),
       (else_try),
         (agent_is_ally, ":cur_agent"),
##SG qixi
         (try_begin),
           (ge,"$use_qixi",1),
           (agent_get_slot,":qixi_slot",":cur_agent",slot_agent_is_not_reinforcement),
           (eq,":qixi_slot",2),
         (else_try),
##SG qixi
           (party_add_members, "p_ally_casualties", ":agent_troop_id", 1),
           (try_begin),
             (agent_is_wounded, ":cur_agent"),
             (party_wound_members, "p_ally_casualties", ":agent_troop_id", 1),
           (try_end),
         (try_end),##SG qixi
       (else_try),
         (party_add_members, "p_enemy_casualties", ":agent_troop_id", 1),
         (try_begin),
           (agent_is_wounded, ":cur_agent"),
           (party_wound_members, "p_enemy_casualties", ":agent_troop_id", 1),
         (try_end),
       (try_end),
     (try_end),
     ]),

  #script_get_max_skill_of_player_party
  # INPUT: arg1 = skill_no
  # OUTPUT: reg0 = max_skill, reg1 = skill_owner_troop_no
  ("get_max_skill_of_player_party",
    [(store_script_param, ":skill_no", 1),
     (party_get_num_companion_stacks, ":num_stacks","p_main_party"),
     (store_skill_level, ":max_skill", ":skill_no", "trp_player"),
     (assign, ":skill_owner", "trp_player"),
     (try_for_range, ":i_stack", 0, ":num_stacks"),
       (party_stack_get_troop_id, ":stack_troop","p_main_party",":i_stack"),
       (troop_is_hero, ":stack_troop"),
       (neg|troop_is_wounded, ":stack_troop"),
       (store_skill_level, ":cur_skill", ":skill_no", ":stack_troop"),
       (gt, ":cur_skill", ":max_skill"),
       (assign, ":max_skill", ":cur_skill"),
       (assign, ":skill_owner", ":stack_troop"),
     (try_end),
     (assign, reg0, ":max_skill"),
     (assign, reg1, ":skill_owner"),
     ]),

  #script_upgrade_hero_party
  # INPUT: arg1 = skill_no
  # OUTPUT: reg0 = max_skill, reg1 = skill_owner_troop_no
  ("upgrade_hero_party",
    [(store_script_param, ":party_no", 1),
     (store_script_param, ":xp_amount", 2),
     (party_upgrade_with_xp, ":party_no",":xp_amount",0),
     ]),
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
# script_check_enemies_nearby
# Input: none
# Output: none, fails when enemies are nearby
  ("check_enemies_nearby",
   [
       (get_player_agent_no, ":player_agent"),
       (agent_is_alive, ":player_agent"),
       (try_begin),
         (agent_is_defender, ":player_agent"),
         (assign, ":player_defender", 1),
       (else_try),
         (assign, ":player_defender", 0),
       (try_end),
       (agent_get_position, 1, ":player_agent"),
       (assign, ":result", 0),
       (try_for_agents,":cur_agent"),
         (neq, ":cur_agent", ":player_agent"),
         (agent_is_alive, ":cur_agent"),
         (agent_is_human, ":cur_agent"),
         (try_begin),
           (agent_is_defender, ":cur_agent"),
           (assign, ":agent_defender", 1),
         (else_try),
           (assign, ":agent_defender", 0),
         (try_end),
         (neq, ":player_defender", ":agent_defender"),
         (agent_get_position, 2, ":cur_agent"),
         (get_distance_between_positions, ":cur_distance", 1, 2),
         (le, ":cur_distance", 1500),
         (assign, ":result", 1),
       (try_end),
       (eq, ":result", 0),
    ]),

  ###############################################################################################################
  # BoW: Reward extra XP and gold to heroes after successful battle is fought.
  # reg(10) is still used because str_hero_reward_gold requires it.
  ###############################################################################################################
  ("party_heroes_extra_gold_and_xp",
   [
      (store_script_param_1, ":player_party_xp_gain"),
      
      # Give extra gold to each hero.
      (assign, reg(10), ":player_party_xp_gain"),
      
      # Calculate how many Heroes are in the party.
      (assign, ":num_heroes", 0),
      (try_for_range, ":ThisRange", "trp_first_npc", "trp_last_npc"),
         (main_party_has_troop, ":ThisRange"),
         (val_add, ":num_heroes", 1),
      (end_try,0),

      # Divide the total party XP gain by the number of heroes. This is the amount of extra XP per hero, using reg(10).
      (val_div, reg(10), ":num_heroes"),

      # Give the extra XP to each hero.
      (try_for_range, ":this_hero", "trp_first_npc", "trp_last_npc"),
         (main_party_has_troop, ":this_hero"),
         (add_xp_to_troop, reg(10), ":this_hero"),
      (end_try,0),

      # If the party has heros, show a message stating that heroes got a reward.
      (try_begin),      
         (gt, ":num_heroes", 1),
         (display_message, "str_hero_reward_xp"), 
      (end_try),

	  # New in v0.808: disabling gold rewards since you got so much item-based loot which doesn't reduce if you have a jillion NPC heroes
	  
      # Calculate 1 gold per 2 XP points, reusing reg(10) for gold now.
      #(val_div, reg(10), 2),
      #(try_for_range, ":this_hero", "trp_first_npc", "trp_last_npc"),
      #   (main_party_has_troop, ":this_hero"),
      #   (troop_add_gold, ":this_hero", reg(10)),
      #(end_try,0),

      # If the party has heros, show a message stating that heroes got a reward.
      #(try_begin),      
      #   (gt, ":num_heroes", 1),
      #   (display_message, "str_hero_reward_gold"),       
	  #(end_try),
    ]),
###################################################################################################
# BoW: Penalties for defeat
# param 1: percent of wealth to lose (0-100)
#####################################################################################################
("defeat_lose_items",
   [
	(store_script_param_1, ":loot_prob"), #roughly how much wealth to extract from party, as a percentage
	(assign,":item_id",0),
	(call_script, "script_unequip_for_battle"),
    (party_get_num_companion_stacks, ":num_stacks","p_main_party"),
    (try_for_range, ":i_stack", 0, ":num_stacks"),
      (party_stack_get_troop_id, ":stack_troop","p_main_party",":i_stack"),
	  (troop_is_hero, ":stack_troop"), # only penalize hero troops
	  (store_troop_gold, reg1, ":stack_troop"),	  
      (val_mul, reg1, ":loot_prob"), #lose loot_prob % of all gold
	  (val_div, reg1, 100),
	  (troop_remove_gold, ":stack_troop", reg1),
      (troop_get_inventory_capacity, ":inv_cap", ":stack_troop"),
      (try_for_range, ":i_slot", 0, ":inv_cap"),
        (troop_get_inventory_slot, ":item_id", ":stack_troop", ":i_slot"),
        (ge, ":item_id", 0),
		(try_begin),
		  (call_script, "script_item_is_lootable", ":item_id"), # you won't lose special and quest items 
		  (eq, reg0, 1),
		  (store_random_in_range, reg0, 0, 100),
		  (lt, reg0, ":loot_prob"), # each item has loot_prob chance of disappearing
		  (troop_remove_item, ":stack_troop", ":item_id"),
		(try_end),
      (try_end),
    (try_end),
   ]
),
  
############
###################################################################################################
# BoW: Get current quantites of gold. Originally by fisheye, modified by Hardcode.
###############################################################################################################
# returns:
# reg1 = Total gold carried by the Player.
# reg2 = Total gold carried by the guy you're talking to.
# reg3 = Total gold carried by all Heroes.
("get_hero_gold_amounts", [
	(store_script_param_1, ":talk_hero"), # the character you're talking to 
	# Use the registers, as much of the following dialog structures do checks on these amounts.
	(assign, ":sum_party_gold", 0),
	(try_for_range,":this_hero","trp_first_npc","trp_last_npc"),
        (main_party_has_troop, ":this_hero"),
        (store_troop_gold, reg4, ":this_hero"),
		(val_add, ":sum_party_gold", reg4),
		(eq, ":this_hero", ":talk_hero"),
		(assign, reg2, reg4), # remember the gold of the guy I'm talking to
	(try_end),
	(store_troop_gold,reg1,0), #player gold
	(val_add, ":sum_party_gold", reg4),
	(assign, reg3, ":sum_party_gold"),
]),

###############################################################################################################
# BoW: Divide the party's gold among all the Heroes. Originally by fisheye, modified by Hardcode.
###############################################################################################################
# reg1 = Share of gold per Hero, used in the dialog text.
# reg(5) = Total party gold, used in the dialog text.
("divide_gold_among_heroes", [
	(assign, ":sum_party_gold", 0),
	# Start :num_heroes at 1 to include the Player.
	(assign, ":num_heroes", 1),
	
	# Total up the Heroes' gold.
	(try_for_range,":this_hero","trp_first_npc","trp_last_npc"),
		(main_party_has_troop, ":this_hero"),
		(store_troop_gold, ":num_hero_gold", ":this_hero"),
		(troop_remove_gold, ":this_hero", ":num_hero_gold"),
		(val_add, ":sum_party_gold", ":num_hero_gold"),
		(val_add, ":num_heroes", 1),
	(try_end),

	# Now, include the player's gold to the total.
	(store_troop_gold,":player_gold",0),
	(troop_remove_gold, 0, ":player_gold"),
	(val_add, ":sum_party_gold", ":player_gold"),

	# Assign the total gold to reg(5) for the dialog.
	(assign, reg5, ":sum_party_gold"),
	
	# Distribute the shares among the Heroes.
	(assign, ":num_share_of_gold", ":sum_party_gold"),
	(val_div, ":num_share_of_gold", ":num_heroes"),
	(try_for_range,":this_hero","trp_first_npc","trp_last_npc"),
		(main_party_has_troop, ":this_hero"),
		(troop_add_gold, ":this_hero", ":num_share_of_gold"),
	(try_end),
	
	# Distribute one share to the Player.
	(troop_add_gold, 0, ":num_share_of_gold"),

	# Assign the value of the share of gold to reg1 for the dialog.
	(assign, reg1, ":num_share_of_gold"),
]),

###############################################################################################################
# BoW: Collect all the Heroes' money and give it to the player. Originally by fisheye, modified by Hardcode.
###############################################################################################################
# reg1 = Total of all heroes' gold.
# reg4 = Player's final total gold.

("give_all_hero_gold_to_player", [
	(assign, ":sum_heroes_gold", 0),
	(try_for_heroes),
        (main_party_has_troop, ":this_hero"),
        (store_troop_gold, ":num_hero_gold", ":this_hero"),        
		(troop_remove_gold, ":this_hero", ":num_hero_gold"),
		(val_add, ":sum_heroes_gold", ":num_hero_gold"),
	(try_end),

	# Assign the total of all heroes' gold to reg1 for the dialog.
	(troop_add_gold, 0, ":sum_heroes_gold"),
	(assign, reg1, ":sum_heroes_gold"),

	# Assign the player's gold to reg4 for the dialog.
	(store_troop_gold, reg4, 0),	
]),

###############################################################################################################
# BoW: Main auto-upgrade script. By fisheye.
###############################################################################################################
# input: none
# uses registers: 1,2,3,4,5,6,7,8,9,10,11,12,13,14,20,21
("perform_hero_equipment_upgrades", [
    # make sure eveyone has unified inventories - analyze inventory will merge secondary and primary inventories
	(call_script, "script_unequip_for_battle"),
	# for all the new NPCs,
    (party_get_num_companion_stacks, ":num_stacks","p_main_party"),
    (try_for_range, ":i_stack", 0, ":num_stacks"),
        (party_stack_get_troop_id, ":this_hero","p_main_party",":i_stack"),
        (troop_is_hero, ":this_hero"), # if not hero, go on to the next
		(neq, ":this_hero", "trp_player"),
		(gt, ":this_hero", "trp_first_npc"),
		(lt, ":this_hero", "trp_last_npc"),
		      
		(assign, "$skip_upgrading", 0),
		# set global vars indicating max cost of each type of item in inventory
		(call_script, "script_analyze_inventory", ":this_hero",0),  
		(try_begin),
			(troop_get_slot, reg4,":this_hero",slot_upgrade_armor),
			(eq, reg4,1),
			(call_script, "script_troop_armor_upgrade", ":this_hero"),
			(call_script, "script_troop_helmet_upgrade", ":this_hero"),    
			(call_script, "script_troop_boots_upgrade", ":this_hero"),
			(call_script, "script_troop_gloves_upgrade", ":this_hero"),    
		(end_try),

		(troop_get_slot, reg4,":this_hero",slot_upgrade_melee),
		(try_begin),
			(eq, reg4,melee_upgrade_one_handed),
			(call_script, "script_troop_onehanded_upgrade", ":this_hero"),
			(call_script, "script_troop_shield_upgrade", ":this_hero"),    
		(else_try),
			(eq, reg4,melee_upgrade_two_handed),
			(call_script, "script_troop_twohanded_upgrade", ":this_hero"),
		(else_try),
			(eq, reg4,melee_upgrade_polearms),
			(call_script, "script_troop_polearm_upgrade", ":this_hero"),
		(else_try),
			(eq, reg4,melee_upgrade_lances),
			(call_script, "script_troop_lance_upgrade", ":this_hero"),
			(call_script, "script_troop_shield_upgrade", ":this_hero"),        
		(else_try),
			(eq, reg4,melee_upgrade_blunts),
			(call_script, "script_troop_onehanded_blunt_upgrade", ":this_hero"),
			(call_script, "script_troop_shield_upgrade", ":this_hero"),        
		(end_try),

		(troop_get_slot, reg4,":this_hero",slot_upgrade_ranged),
		(try_begin),
			(eq, reg4,ranged_upgrade_bows),
			(call_script, "script_troop_bows_upgrade", ":this_hero"),
		(else_try),
			(eq, reg4,ranged_upgrade_crossbows),
			(call_script, "script_troop_crossbows_upgrade", ":this_hero"),
		(else_try),
			(eq, reg4,ranged_upgrade_throwing),
			(call_script, "script_troop_throwing_upgrade", ":this_hero"),
		(end_try),

		(try_begin),
			(troop_get_slot, reg4,":this_hero",slot_upgrade_horse),
			(eq, reg4,1),
			(call_script, "script_troop_horse_upgrade", ":this_hero"),
		(end_try),

	(try_end),    
]),

###############################################################################################################
# BoW: Hero armor upgrade. By fisheye.
###############################################################################################################
# inputs:  param1: troop
# returns: reg(5): armor gold value
# uses registers: 2,3,4,5,6,7,8,9,10,11,12,13,14,20,21  
("troop_armor_upgrade",	[
	(store_script_param_1, ":hero"), # the hero to upgrade
	(try_begin),
		# reinforced versions of ultimate armor
		(call_script, "script_get_heavy_armor_pref", ":hero"),
		(assign, ":armor_pref", reg21),
		(assign, reg50, 0),
		(try_begin),
			(eq, ":armor_pref", 0),     
			(assign, reg8, "itm_ironarmor"),
			(assign, reg7,imod_reinforced),
			(assign, reg20, 10),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_armor_value"),
		(else_try),
			(eq, ":armor_pref", 1),
			(assign, reg8, "itm_tiezhajia"),
			(assign, reg7,imod_reinforced),
			(assign, reg20, 10),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_armor_value"),
		(else_try),
			(eq, ":armor_pref", 2),    
			(assign, reg8, "itm_mingarmora"),
			(assign, reg7,imod_reinforced),
			(assign, reg20, 10),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_armor_value"),
		(else_try),
			(eq, ":armor_pref", 3),    
			(assign, reg8, "itm_mingarmor"),
			(assign, reg7,imod_reinforced),
			(assign, reg20, 10),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_armor_value"),
		(end_try),
		(eq, reg50, 0), # didn't upgrade

		# regular versions of ultimate armor
		(try_begin),
			(eq, ":armor_pref", 0),     
			(assign, reg8, "itm_ironarmor"),
			(assign, reg7, imod_plain),
			(assign, reg20, 10),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_armor_value"),
		(else_try),
			(eq, ":armor_pref", 1),
			(assign, reg8, "itm_tiezhajia"),
			(assign, reg7, imod_plain),
			(assign, reg20, 10),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_armor_value"),
		(else_try),
			(eq, ":armor_pref", 2),    
			(assign, reg8, "itm_mingarmora"),
			(assign, reg7, imod_plain),
			(assign, reg20, 10),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_armor_value"),
		(else_try),
			(eq, ":armor_pref", 3),    
			(assign, reg8, "itm_mingarmor"),
			(assign, reg7, imod_plain),
			(assign, reg20, 10),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_armor_value"),
		(end_try),
		(eq, reg50, 0), # didn't upgrade
	
		# other armor
		(assign, reg8, 343),
		(assign, reg9, 7),
		(call_script, "script_get_troop_hash", ":hero"),
		(assign, ":armor_pref", reg21),	
		(assign, reg50, 0),		

# medium armor		
		(try_begin),
			(eq, ":armor_pref", 0),
			(assign, reg8, "itm_tongarmor"),
			(assign, reg7, imod_plain),
			(assign, reg20, 14),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_armor_value"),
		(else_try),
			(eq, ":armor_pref", 1),
			(assign, reg8, "itm_mingarmorb"),
			(assign, reg7, imod_plain),
			(assign, reg20, 14),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_armor_value"),
		(else_try),
			(eq, ":armor_pref", 2),
			(assign, reg8, "itm_wuwushen1"),
			(assign, reg7, imod_plain),
			(assign, reg20, 14),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_armor_value"),
		(else_try),
			(eq, ":armor_pref", 3),
			(assign, reg8, "itm_weiwushen1"),
			(assign, reg7, imod_plain),
			(assign, reg20, 14),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_armor_value"),
		(else_try),
			(eq, ":armor_pref", 4),
			(assign, reg8, "itm_shuwushen1"),
			(assign, reg7, imod_plain),
			(assign, reg20, 14),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_armor_value"),
		(else_try),
			(eq, ":armor_pref", 5),
			(assign, reg8, "itm_wuwushen2"),
			(assign, reg7, imod_plain),
			(assign, reg20, 14),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_armor_value"),
		(else_try),
			(eq, ":armor_pref", 6),
			(assign, reg8, "itm_weiwushen2"),
			(assign, reg7, imod_plain),
			(assign, reg20, 14),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_armor_value"),			
		(try_end),

		(eq, reg50, 0),
# light armor				
		(try_begin),
			(this_or_next|eq, ":armor_pref", 0),
			(eq, ":armor_pref", 1),
			(assign, reg8, "itm_zhongpijia"),
			(assign, reg7, imod_plain),
			(assign, reg20, 14),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_armor_value"),
		(else_try),
			(this_or_next|eq, ":armor_pref", 2),
			(eq, ":armor_pref", 3),     
			(assign, reg8, "itm_beastarmor"),
			(assign, reg7, imod_plain),
			(assign, reg20, 14),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_armor_value"),     
		(else_try),
			(this_or_next|eq, ":armor_pref", 4),
			(eq, ":armor_pref", 5),     
			(assign, reg8, "itm_huangarmor"),
			(assign, reg7, imod_plain),
			(assign, reg20, 14),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_armor_value"),     
		(else_try),
			(eq, ":armor_pref", 6),     
			(assign, reg8, "itm_leatherarmor"),
			(assign, reg7, imod_plain),
			(assign, reg20, 14),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_armor_value"),     
		(end_try),
	(end_try),
]),

###############################################################################################################
# BoW: Helmet upgrade. By fisheye.
###############################################################################################################
# inputs:  reg1: troop
# returns: reg(5): current (new) value
# uses registers: 2,3,4,5,6,7,8,9,10,11,12,13,14,20,21
("troop_helmet_upgrade", [
   (store_script_param_1, ":hero"), # the hero to upgrade
   (try_begin),
		# reinforced ultimate armor
		(assign,":strength",0),
		(call_script, "script_get_heavy_armor_pref", ":hero"),
		(assign, ":armor_pref", reg21),
		(assign, reg50, 0),		
		(try_begin),
			(eq, ":armor_pref", 0),     
			(assign, reg8, "itm_straw_hat"),
			(assign, reg7,imod_reinforced),     
			(assign, reg20, 10),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_helmet_value"),
		(else_try),
			(eq, ":armor_pref", 1),
			(assign, reg8, "itm_nomad_cap"),
			(assign, reg7,imod_reinforced),     
			(assign, reg20, 10),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_helmet_value"),
		(else_try),
			(this_or_next|eq, ":armor_pref", 2),    
			(eq, ":armor_pref", 3),    
			(assign, reg8, "itm_steppe_cap"),
			(assign, reg7,imod_reinforced),     
			(assign, reg20, 10),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_helmet_value"),
		(end_try),
		(eq, reg50, 0), # didn't upgrade

		# ordinary armors
		(try_begin),
			(eq, ":armor_pref", 0),     
			(assign, reg8, "itm_lutoujin"),
			(assign, reg7, imod_plain),
			(assign, reg20, 10),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_helmet_value"),
		(else_try),
			(eq, ":armor_pref", 1),
			(assign, reg8, "itm_leather_cap"),
			(assign, reg7, imod_plain),
			(assign, reg20, 10),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_helmet_value"),
		(else_try),
			(this_or_next|eq, ":armor_pref", 2),    
			(eq, ":armor_pref", 3),    
			(assign, reg8, "itm_leather_steppe_cap_a"),
			(assign, reg7, imod_plain),
			(assign, reg20, 10),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_helmet_value"),
		(end_try),
		(eq, reg50, 0), # didn't upgrade

		# medium helmets
		(assign, reg8, 83),
		(assign, reg9, 3),
		(call_script, "script_get_troop_hash", ":hero"),
		(assign, ":armor_pref", reg21),		
		(assign, reg50, 0),		
		(try_begin),
			(eq, ":armor_pref", 1),     
			(assign, reg8, "itm_felt_steppe_cap"),
			(assign, reg7, imod_plain),
			(assign, reg20, 20),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_helmet_value"),
		(else_try),
			(eq, ":armor_pref", 2),     
			(assign, reg8, "itm_yuling"),
			(assign, reg7, imod_plain),
			(assign, reg20, 20),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_helmet_value"),
		(else_try),
			(eq, ":armor_pref", 3),     
			(ge, ":strength", 8),
			(assign, reg8, "itm_tenghelmet"),
			(assign, reg7, imod_plain),
			(assign, reg20, 20),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_helmet_value"),
		(try_end),

		(eq, reg50, 0),
		
		(try_begin),
			(eq, ":armor_pref", 0),     
			(assign, reg8, "itm_tiekui"),
			(assign, reg7, imod_plain),
			(assign, reg20, 20),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_helmet_value"),
		(else_try),
			(eq, ":armor_pref", 1),
			(assign, reg8, "itm_tiekuia"),
			(assign, reg7, imod_plain),
			(assign, reg20, 20),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_helmet_value"),
		(else_try),
			(eq, ":armor_pref", 2),
			(assign, reg8, "itm_tiezhou"),
			(assign, reg7, imod_plain),
			(assign, reg20, 20),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_helmet_value"),
		(else_try),
			(eq, ":armor_pref", 3),     
			(assign, reg8, "itm_ptiekui"),
			(assign, reg7, imod_plain),
			(assign, reg20, 20),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_helmet_value"),
		(try_end),

		(eq, reg50, 0),
		
		(try_begin),
			(eq, ":armor_pref", 0),
			(assign, reg8, "itm_yanbiana"),
			(assign, reg7, imod_plain),
			(assign, reg20, 20),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_helmet_value"),
		(else_try),
			(eq, ":armor_pref", 1),
			(assign, reg8, "itm_yanbian"),
			(assign, reg7, imod_plain),
	        (assign, reg20, 20),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_helmet_value"),
		(else_try),
			(eq, ":armor_pref", 2),
			(assign, reg8, "itm_yanyitoukui"),
			(assign, reg7, imod_plain),
			(assign, reg20, 20),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_helmet_value"),
		(else_try),
			(eq, ":armor_pref", 3),
			(assign, reg8, "itm_yanbianc"),
			(assign, reg7, imod_plain),
			(assign, reg20, 20),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_helmet_value"),
		(end_try),

	(end_try),
]),

###############################################################################################################
# BoW: Boots upgrade. By fisheye.
###############################################################################################################
# inputs:  reg1: troop
# returns: reg(5): current (new) value
# uses registers: 2,3,4,5,6,7,8,9,10,11,12,13,14,20,21
("troop_boots_upgrade", [
	(store_script_param_1, ":hero"), # the hero to upgrade
	(try_begin),
		# reinforced versions of ultimate armor
		(call_script, "script_get_heavy_armor_pref", ":hero"),
		(assign, ":armor_pref", reg21),
		(assign, reg50, 0),		
		(try_begin),
			(eq, ":armor_pref", 0),    
			(assign, reg8, "itm_bushoes"),
			(assign, reg7,imod_reinforced),
			(assign, reg20, 10),           
			(call_script,"script_upgrade_if_possible", ":hero", "$best_boots_value"),
		(else_try),
			(eq, ":armor_pref", 1),    
			(assign, reg8, "itm_wenxie"),
			(assign, reg7,imod_reinforced),
			(assign, reg20, 10),           
			(call_script,"script_upgrade_if_possible", ":hero", "$best_boots_value"),
		(else_try),
			(eq, ":armor_pref", 2),    
			(assign, reg8, "itm_nomad_boots"),
			(assign, reg7,imod_reinforced),
			(assign, reg20, 10),           
			(call_script,"script_upgrade_if_possible", ":hero", "$best_boots_value"),     
		(else_try),
			(eq, ":armor_pref", 3),    
			(assign, reg8, "itm_hunter_boots"),
			(assign, reg7,imod_reinforced),
			(assign, reg20, 10),           
			(call_script,"script_upgrade_if_possible", ":hero", "$best_boots_value"),     
		(end_try),
		(eq, reg50, 0),
		
		# ordinary versions of armor		   
		(try_begin),
			(eq, ":armor_pref", 0),    
			(assign, reg8, "itm_leather_boots"),
			(assign, reg7, imod_plain),
			(assign, reg20, 10),           
			(call_script,"script_upgrade_if_possible", ":hero", "$best_boots_value"),
		(else_try),
			(eq, ":armor_pref", 1),    
			(assign, reg8, "itm_zhanxie"),
			(assign, reg7, imod_plain),
			(assign, reg20, 10),           
			(call_script,"script_upgrade_if_possible", ":hero", "$best_boots_value"),
		(else_try),
			(eq, ":armor_pref", 2),    
			(assign, reg8, "itm_wuxie"),
			(assign, reg7, imod_plain),
			(assign, reg20, 10),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_boots_value"),
		(end_try),
		(eq, reg50, 0),

		# medium boots
		(assign, reg8, 71),
		(assign, reg9, 2),
		(call_script, "script_get_troop_hash", ":hero"),
		(assign, ":armor_pref", reg21),
		(assign, reg50, 0),		
		(try_begin),
			(eq, ":armor_pref",1),     
			(assign, reg8, "itm_splinted_greaves"),
			(assign, reg7, imod_plain),
			(assign, reg20, 25),               
			(call_script,"script_upgrade_if_possible", ":hero", "$best_boots_value"),
		(else_try),
			(eq, ":armor_pref",0),     
			(assign, reg8, "itm_ironshoes"),
			(assign, reg7, imod_plain),			
			(assign, reg20, 20),               
			(call_script,"script_upgrade_if_possible", ":hero", "$best_boots_value"),
		(end_try),
     
	(end_try),
]),

###############################################################################################################
# BoW: Gloves upgrade. By fisheye.
###############################################################################################################
# inputs:  reg1: troop
# uses registers: 2,3,4,5,6,7,8,9,10,11,12,13,14,20
("troop_gloves_upgrade", [
	(store_script_param_1, ":hero"), # the hero to upgrade
	(try_begin),
		(assign, reg50, 0),	
		# reinforced versions of ultimate armor
		(try_begin),
			(assign, reg8, "itm_leather_gloves"),
			(assign, reg7,imod_reinforced),
			(assign, reg20, 10),          
			(call_script,"script_upgrade_if_possible", ":hero", "$best_gloves_value"),
		(end_try),
	(end_try),
]),

###############################################################################################################
# BoW: One-handed upgrade. By fisheye.
###############################################################################################################
# inputs:  reg1: troop
# returns: reg(5): current (new) value
# uses registers: 2,3,4,5,6,7,8,9,10,11,12,13,14,20,21
("troop_onehanded_upgrade", [
	(store_script_param_1, ":hero"), # the hero to upgrade
	(try_begin),
		(assign, reg50, 0),		
		(assign, reg2, ":hero"),
		(val_mod, reg2, 3),
		(try_begin),
			(this_or_next|eq, ":hero", "trp_wangxiaohu"),
			(eq, reg2, 0),
			(assign, reg8, "itm_handhalberd"),
			(assign, reg7, imod_plain),
			(assign, reg20, 10),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_one_handed_value"),
		(end_try),
		(eq, reg50, 0),
		(try_begin),
			(neq, ":hero", "trp_wangxiaohu"),
			(neq, reg2, 0),
			(assign, reg8, "itm_china_100longsword"),
			(assign, reg7, imod_plain),
			(assign, reg20, 10),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_one_handed_value"),
		(end_try),
		(eq, reg50, 0),
		(try_begin),
			(assign, reg8, "itm_handbronzesword"),
			(assign, reg7, imod_plain),
			(assign, reg20, 10),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_one_handed_value"),
		(end_try),

	(end_try),
]),

###############################################################################################################
# BoW: One-handed blunts upgrade. By fisheye.
###############################################################################################################
# inputs:  reg1: troop
# returns: reg(5): current (new) value
# uses registers: 2,3,4,5,6,7,8,9,10,11,12,13,14,20,21
("troop_onehanded_blunt_upgrade", [
	(store_script_param_1, ":hero"), # the hero to upgrade
	(try_begin),
		(assign, reg50, 0),		
#		(try_begin),     
#			(assign, reg8, "itm_wu"),
#			(assign, reg7, imod_plain),
#			(assign, reg20, 10),
#			(call_script,"script_upgrade_if_possible", ":hero", "$best_one_handed_blunt_value"),
#		(end_try),
		(eq, reg50, 0),
		(try_begin),     
			(assign, reg8, "itm_jian"),
			(assign, reg7, imod_plain),
			(assign, reg20, 10),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_one_handed_blunt_value"),
		(end_try),
		(eq, reg50, 0),
		(try_begin),
			(assign, reg8, "itm_dayue"),
			(assign, reg7, imod_plain),
			(assign, reg20, 10),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_one_handed_blunt_value"),
		(end_try),
	(end_try),
]),

###############################################################################################################
# BoW: Two-handed upgrade. By fisheye.
###############################################################################################################
# inputs:  reg1: troop
# returns: reg(5): current (new) value
# uses registers: 2,3,4,5,6,7,8,9,10,11,12,13,14,20
("troop_twohanded_upgrade", [
	(store_script_param_1, ":hero"), # the hero to upgrade
	(try_begin),
		(assign, reg50, 0),		
		(assign, reg2, ":hero"),
		(val_mod, reg2, 3),
		(try_begin),
			(this_or_next|eq, ":hero", "trp_wangxiaohu"),
			(eq, reg2, 0),
			(assign, reg8, "itm_yue"),
			(assign, reg7, imod_plain),
			(assign, reg20, 10),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_two_handed_value"),
		(end_try),
		(eq, reg50, 0),
		(try_begin),
			(neq, ":hero", "trp_wangxiaohu"),
			(neq, reg2, 0),
			(assign, reg8, "itm_dayue"),
			(assign, reg7, imod_plain),
			(assign, reg20, 10),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_two_handed_value"),
		(end_try),
		(eq, reg50, 0),
		(try_begin),
			(assign, reg8, "itm_zhongzhandao"),
			(assign, reg7, imod_plain),
			(assign, reg20, 10),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_two_handed_value"),
		(end_try),
		(eq, reg50, 0),
		(try_begin),
			(assign, reg8, "itm_zhanmabardiche"),
			(assign, reg7, imod_plain),
			(assign, reg20, 10),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_two_handed_value"),
		(end_try),
	(end_try),
]),

###############################################################################################################
# BoW: Polearms upgrade. By fisheye.
###############################################################################################################
# inputs:  reg1: troop
# returns: reg(5): current (new) value
# uses registers: 2,3,4,5,6,7,8,9,10,11,12,13,14,20
("troop_polearm_upgrade", [
	(store_script_param_1, ":hero"), # the hero to upgrade
	(try_begin),
		(assign, reg50, 0),		
		(try_begin),
			(assign, reg7, imod_plain),
			(assign, reg20, 10),          
			(assign, reg8, "itm_china_pike"),			
			(call_script,"script_upgrade_if_possible", ":hero", "$best_polearm_value"),
		(end_try),
		(eq, reg50, 0),
		(try_begin),
			(assign, reg8, "itm_dbspear"),
			(assign, reg7, imod_plain),
			(assign, reg20, 10),          
			(call_script,"script_upgrade_if_possible", ":hero", "$best_polearm_value"),
		(end_try),
		(eq, reg50, 0),
		(try_begin),
			(assign, reg8, "itm_mapick"),
			(assign, reg7, imod_plain),
			(assign, reg20, 10),          
			(call_script,"script_upgrade_if_possible", ":hero", "$best_polearm_value"),
		(end_try),

	(end_try),
]),

###############################################################################################################
# BoW: Lance upgrade. By fisheye.
###############################################################################################################
# inputs:  reg1: troop
# returns: reg(5): current (new) value
# uses registers: 2,3,4,5,6,7,8,9,10,11,12,13,14,20
("troop_lance_upgrade", [
	(store_script_param_1, ":hero"), # the hero to upgrade
	(try_begin),
		(assign, reg50, 0),	
		(assign, reg7, imod_plain),
		(assign, reg20, 10),
		(assign, reg8, "itm_bupick"),
		(call_script,"script_upgrade_if_possible", ":hero", "$best_polearm_value"),
		(eq, reg50, 0),
		(assign, reg7, imod_plain),
		(assign, reg20, 10),
		(assign, reg8, "itm_pick"),
		(call_script,"script_upgrade_if_possible", ":hero", "$best_polearm_value"),
		(eq, reg50, 0),
		(assign, reg7, imod_plain),
		(assign, reg20, 10),
		(assign, reg8, "itm_geb"),
		(call_script,"script_upgrade_if_possible", ":hero", "$best_polearm_value"),
		(eq, reg50, 0),
	(end_try),
]),

###############################################################################################################
# BoW: Shield upgrade. By fisheye.
###############################################################################################################
# inputs:  reg1: troop
# uses registers: 2,3,4,5,6,7,8,9,10,11,12,13,14,20
("troop_shield_upgrade", [
	(store_script_param_1, ":hero"), # the hero to upgrade
	(try_begin),	
		(store_free_inventory_capacity,reg4,":hero"),
		(assign, reg50, 0),		
		(ge, reg4, 1),      
		(assign, reg7, imod_plain),
		(assign, reg20, 10),
		(assign, reg8, "itm_xishield"),
		(call_script,"script_upgrade_if_possible", ":hero", "$best_shield_value"),
		(eq, reg50, 0),
		(assign, reg7, imod_plain),
		(assign, reg20, 10),
		(assign, reg8, "itm_weishield"),
		(call_script,"script_upgrade_if_possible", ":hero", "$best_shield_value"),
	(end_try),
]),

###############################################################################################################
# BoW: Throwing weapon upgrade. By fisheye.
###############################################################################################################
# inputs:  reg1: troop
# uses registers: 2,3,4,5,6,7,8,9,10,11,12,13,14,20
("troop_throwing_upgrade", [
	(store_script_param_1, ":hero"), # the hero to upgrade
	(try_begin),
		(assign, reg50, 0),

		(try_begin),
			(assign, reg8, "itm_jarid"),
			(assign, reg7,imod_large_bag),
			(assign, reg20, 10),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_throwing_value"),
		(end_try),
		
		(eq, reg50, 0),
		(try_begin),
			(assign, reg8, "itm_javelin"),
			(assign, reg7,imod_large_bag),
			(assign, reg20, 10),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_throwing_value"),
		(end_try),

	(end_try),
]),

###############################################################################################################
# BoW: Bows upgrade. By fisheye.
###############################################################################################################
# inputs:  reg1: troop
# uses registers: 2,3,4,5,6,7,8,9,10,11,12,13,14,20
("troop_bows_upgrade", [
	(store_script_param_1, ":hero"), # the hero to upgrade
	(try_begin),
		(assign, reg50, 0),

		(try_begin),
			(assign, reg8, "itm_short_bow"),
			(assign, reg7, imod_plain),
			(assign, reg20, 10),     
			(call_script,"script_upgrade_if_possible", ":hero", "$best_bow_value"),
		(end_try),

		(eq, reg50, 0),
		(try_begin),
			(assign, reg8, "itm_nomad_bow"),
			(assign, reg7, imod_plain),
			(assign, reg20, 10),     
			(call_script,"script_upgrade_if_possible", ":hero", "$best_bow_value"),
		(end_try),

		(eq, reg50, 0),
		(try_begin),
			(assign, reg8, "itm_strong_bow"),
			(assign, reg7, imod_plain),
			(assign, reg20, 10),     
			(call_script,"script_upgrade_if_possible", ":hero", "$best_bow_value"),
		(end_try),

		(eq, reg50, 0),
		(try_begin),
			(assign, reg8, "itm_strong_bow"),
			(assign, reg7, imod_plain),
			(assign, reg20, 10),     
			(call_script,"script_upgrade_if_possible", ":hero", "$best_bow_value"),
		(end_try),

		(eq, reg50, 0),
		(try_begin),
			(assign, reg8, "itm_war_bow"),
			(assign, reg7, imod_plain),
			(assign, reg20, 10),     
			(call_script,"script_upgrade_if_possible", ":hero", "$best_bow_value"),
		(end_try),

		# get some ammo    
		(store_item_kind_count, reg2, "itm_arrows", ":hero"),
		(lt, reg2, 1),
		(assign, reg7,imod_large_bag),
		(assign, reg8, "itm_arrows"),
		(call_script,"script_upgrade_if_possible", ":hero",0),
		(eq, reg50, 0),
		(assign, reg2,0),
		(try_for_range, reg4, "itm_bodkin_arrows", "itm_bolts"),
			(store_item_kind_count, reg3, reg4, ":hero"),
			(val_add, reg2, reg3),
		(end_try),
		(lt, reg2, 1),
		(assign, reg8, "itm_bodkin_arrows"),
		(call_script,"script_upgrade_if_possible", ":hero",0),

	(end_try),
]),

###############################################################################################################
# BoW: Crossbows upgrade. By fisheye.
###############################################################################################################
# inputs:  reg1: troop
# uses registers: 2,3,4,5,6,7,8,9,10,11,12,13,14,20
("troop_crossbows_upgrade", [
	(store_script_param_1, ":hero"), # the hero to upgrade
	(try_begin),
	(assign, reg50, 0),
	
	(try_begin),
		(assign, reg8, "itm_china_cross"),
		(assign, reg7, imod_plain),
		(assign, reg20,10),
		(call_script,"script_upgrade_if_possible", ":hero", "$best_crossbow_value"),
	(end_try),

	(eq, reg50, 0),
	(try_begin),
		(assign, reg8, "itm_sniper_crossbow"),
		(assign, reg7, imod_plain),
		(assign, reg20,10),
		(call_script,"script_upgrade_if_possible", ":hero", "$best_crossbow_value"),
	(end_try),

	(eq, reg50, 0),
	(try_begin),
		(assign, reg8, "itm_heavy_crossbow"),
		(assign, reg7, imod_plain),
		(assign, reg20,10),
		(call_script,"script_upgrade_if_possible", ":hero", "$best_crossbow_value"),
	(end_try),

	(eq, reg50, 0),
	(try_begin),
		(assign, reg8, "itm_crossbow"),
		(assign, reg7, imod_plain),
		(assign, reg20,10),
		(call_script,"script_upgrade_if_possible", ":hero", "$best_crossbow_value"),
	(end_try),

	# get some ammo 
	(assign, reg7,imod_large_bag),
	(store_item_kind_count, reg2, "itm_iron_bolts", ":hero"),
	(lt, reg2, 1),
	(assign, reg8, "itm_iron_bolts"),
	(call_script,"script_upgrade_if_possible", ":hero", 0),
	(eq, reg50, 0),
	(store_item_kind_count, reg2, "itm_bolts", ":hero"),
	(store_item_kind_count, reg3, "itm_iron_bolts", ":hero"),
	(val_add, reg2, reg3),
	(lt, reg2, 1),
	(assign, reg8, "itm_bolts"),
	(call_script,"script_upgrade_if_possible", ":hero", 0),

	(end_try),
]),

###############################################################################################################
# BoW: Hero horse upgrade. By fisheye.
###############################################################################################################
# inputs:  reg1: troop
# uses registers: 2,3,4,5,6,7,8,9,10,11,12,13,14,20
("troop_horse_upgrade", [
	(store_script_param_1, ":hero"), # the hero to upgrade
	(assign, reg50, 0),
	(try_begin),
		(try_begin),
			(assign, reg8, "itm_dihorse"),
			(assign, reg7, imod_plain),
			(assign, reg20,10),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_horse_value"),
		(end_try),
		(eq, reg50, 0),
		(try_begin),
			(assign, reg8, "itm_zhanhorse"),
			(assign, reg7, imod_plain),
			(assign, reg20,10),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_horse_value"),
		(end_try),
		(eq, reg50, 0),
		(try_begin),
			(assign, reg8, "itm_hunter"),
			(assign, reg7, imod_plain),
			(assign, reg20,10),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_horse_value"),
		(end_try),
		(eq, reg50, 0),
		(try_begin),
			(assign, reg8, "itm_dianhorse"),
			(assign, reg7, imod_plain),
			(assign, reg20,10),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_horse_value"),
		(end_try),
		(eq, reg50, 0),
		(try_begin),
			(assign, reg8, "itm_saddle_horse"),
			(assign, reg7, imod_plain),
			(assign, reg20,10),
			(call_script,"script_upgrade_if_possible", ":hero", "$best_horse_value"),
		(end_try),

	(end_try),
]),

####################################################################################################
# BoW: Main buying script. By fisheye.
#####################################################################################################
#inputs:
#  param 1:troop,
#  param2:value of best item of same type (e.g. 1-H, 2-H, armor, etc) owned by troop,
#  reg8 :item to upgrade to,
#  reg7:item modifier,
#  reg20:only upgrade if bought item is more expensive than 0.1 x reg20 x current value.
#          e.g. 10: always upgrade if better.
#               20: upgrade only to equipment that is more than twice as valuable as the current gear, etc.
#
#uses registers: 4,6,9,10,12,13,14 
#output: reg50: 0 : didn't upgrade, 1: upgraded
("upgrade_if_possible", [
	(store_script_param_1, ":hero"), # the hero to upgrade
	(store_script_param_2, ":current_value"), # the value of my current stuff
	(assign, ":item", reg8),
	(assign, ":item_imod", reg7),
	(assign, ":item_improvement_requirement", reg20),
	(assign, reg50, 0),

	(try_begin),
		(call_script, "script_check_hero_avail_inventory", ":hero"), # set skip_upgrading to 1 if no more room
		(eq, "$skip_upgrading",0),
		
		(assign, reg7, ":item_imod"),
		(call_script, "script_troop_can_use_item_well", ":hero", ":item"), # check if usable 
		(eq, reg0, 1), #yes, it's usable
		
		(str_store_troop_name, 1, ":hero"),    
		(str_store_item_name, 2, ":item"),

		# check if the new item is sufficiently better than the one we've got
		(store_item_value, ":buy_price", ":item"),
		(try_begin),
			# large bags cost 1.9 times
			(eq, ":item_imod", imod_large_bag),
			(val_mul, ":buy_price", 19),
			(val_div, ":buy_price", 10),
		(else_try),
			# reinforced cost 7.2 times    
			(eq, ":item_imod", imod_reinforced),
			(val_mul, ":buy_price", 72),
			(val_div, ":buy_price", 10),
		(end_try),

		(assign, reg6, ":current_value"),
		(val_mul, reg6, ":item_improvement_requirement"),
		(val_div, reg6, 10),    
		# only continue if the new item is much better.
		(lt, reg6, ":buy_price"),
			
		# check if we have a store of sufficient funds to afford the item
		# adjust for party's haggling skill
		(call_script, "script_adjust_buy_price", ":buy_price"),
		# reg10 contains the buy price adjusted for trading skill
		(assign, ":buy_price", reg10),
		# check if we have enough funds    
		(store_troop_gold, ":avail_gold", ":hero"),
		(try_begin),
			# armor: buy whenever you've got the cash
			(is_between, ":item", items_armor_start, items_armor_end),
		(else_try),
			# not armor: require double reserve funds,
			# e.g a shield costing $100 is bought when you have $200 or more.
			(val_div, ":avail_gold",2),
		(end_try),
		(ge, ":avail_gold", ":buy_price"),
			
		# make the purchase
		(troop_remove_gold, ":hero", ":buy_price"),
		(troop_add_item, ":hero", ":item", ":item_imod"),
		(str_store_item_name, 2, ":item"),      
		(display_message, "str_hero_gear_upgrade"),
		(assign, reg50, 1),
	(end_try),
]),

#####################################################################################################
# BoW: Get heavy armor preference. By fisheye.
#####################################################################################################
# inputs:  reg1: troop
# outputs: reg(21): 0 - black, 1 - japanese, 2 - steel, 3 - standard plate
# uses registers: 8,9
("get_heavy_armor_pref", [
	(store_script_param_1, ":hero"), # the hero to upgrade
	(assign, reg8, 53), # random hash seed for heavy armor - just an aribtirary prime number
	(assign, reg9, 4), # select random values between 0 and 3
	(call_script, "script_get_troop_hash", ":hero"),
	#reg(21) now contains a fixed random value
	(try_begin),
		(eq, ":hero", "trp_shahongbing"),
		(assign, reg21, 2),
	(else_try),
		(eq, ":hero", "trp_diaochan"),
		(assign, reg21, 0),
	(end_try),
]),

###################################################################################################
# BoW: Get troop hash. By fisheye.
##################################################################################################
# inputs:  1: troop, reg8, reg9: hash parameters
# outputs: reg21: random value in 0..reg9 but fixed for each input tuple
("get_troop_hash", [
	(store_script_param_1, ":hero"), # the hero to upgrade
	(troop_get_slot, reg21, ":hero", slot_random_hash),
	(val_mod, reg21, reg8),
	(val_mod, reg21, reg9),
]),

#####################################################################################################
# BoW: Check if hero inventory has enough space for auto-upgrading. By fisheye.
#####################################################################################################
# input: param 1: troop
# uses registers: 4,10.
("check_hero_avail_inventory", [
	(try_begin),
		# no need to check if already skipping upgrades
		(eq, "$skip_upgrading",0),
		(store_script_param_1, ":hero"), # the hero to upgrade
		(store_free_inventory_capacity,":capacity",":hero"),
		(try_begin),
			(lt, ":capacity", 1),
			(str_store_troop_name, 20, ":hero"),
			(display_message, "str_hero_inv_full"),
			(assign, "$skip_upgrading", 1),    
		(end_try),
	(end_try),
]),


####################################################################################################
# BoW: Returns the buy price of a given item, corrected for party trade skill. By fisheye.
#####################################################################################################
# inputs:param 1: base price
# outputs: reg(10): inflated buy price
# uses: reg 14,12,13
("adjust_buy_price", [
	(store_script_param_1, ":base_price"), # the price to adjust
	# first get highest trade skill in party
	# get highest NPC skill in party
	(assign, ":max_skill",0),
	(try_for_range,":this_hero","trp_first_npc","trp_last_npc"),
		(main_party_has_troop, ":this_hero"),   
		(store_skill_level,reg13,skl_trade,":this_hero"),
		(val_max, ":max_skill",reg13),
	(try_end),
		
	# get player trade skill
	(store_skill_level, ":player_skill",skl_trade, "trp_player"),
	(val_max, ":max_skill", ":player_skill"),
	
	#adjust for v0.8+ NPC party skill penalty
	(store_sub, ":skill_diff", ":max_skill", ":player_skill"),
	(try_begin),
	  (le, ":skill_diff", 2),
	  # no penalty
	(else_try),
	  (le, ":skill_diff", 5),
	  (val_sub, ":max_skill", 1),
	(else_try),
	  (le, ":skill_diff", 8),
	  (val_sub, ":max_skill", 2),
	(else_try),
	  (val_sub, ":max_skill", 3),
	(try_end),
	
    # perform trade calculations: price = ( 2.2 - 0.08xTrade ) * base
	(val_mul, ":max_skill", 8),
	(assign, ":price_factor", 220),
	(val_sub, ":price_factor", ":max_skill"),
	(store_mul, reg10, ":price_factor", ":base_price"),
	(val_div, reg10, 100),
]),


("access_inventory", [
	(store_script_param_1, ":target_troop"),
	# unwield all items.
	(call_script, "script_unequip_inventory", ":target_troop"),	
	# open the loot screen.
	(change_screen_loot, ":target_troop"),
]),

##########################################################################################
# BoW: Transfers inventory from troop to itself, thus unequipping everything
##########################################################################################
# Param1:  troop
##########################################################################################
("unequip_inventory", [
	(store_script_param_1, ":troop"),
	(assign,":item_id",0),
	(troop_get_inventory_capacity, ":inv_cap", ":troop"),
	(assign, ":num_items", 0),
	(try_for_range, ":i_slot", 0, ":inv_cap"),
		(troop_get_inventory_slot, ":item_id", ":troop", ":i_slot"),
	    (ge, ":item_id", 0),
		(troop_set_slot, "trp_temp_array_a", ":num_items", ":item_id"),
		(val_add, ":num_items", 1),
	(try_end),
	(try_for_range, ":i_slot", 0, ":num_items"),
		(troop_get_slot, ":item_id", "trp_temp_array_a", ":i_slot"),
		(troop_remove_items, ":troop", ":item_id", 1),
		# reg0 = cost
		(call_script, "script_get_item_imod", ":item_id", reg0),
		# reg0 = imod
		(troop_set_slot, "trp_temp_array_b", ":i_slot", reg0),
	(try_end),
	(try_for_range, ":i_slot", 0, ":num_items"),
		(troop_get_slot, ":item_id", "trp_temp_array_a", ":i_slot"),
		(troop_get_slot, ":item_imod", "trp_temp_array_b", ":i_slot"),
		(troop_add_item, ":troop", ":item_id", ":item_imod"),
	(try_end),
]),



##########################################################################################
# BoW; Copy inventory of one troop to another
# Note: Be careful not to copy lots of items into a troop with low inventory management
##########################################################################################
# Param1: source troop
# Param2: target troop  -- MUST NOT BE trp_temp_troop_for_copy
##########################################################################################
("copy_inventory", [
	(store_script_param_1, ":source_troop"),
	(store_script_param_2, ":target_troop"),	
	(assign,":item_id",0),
	(troop_clear_inventory, ":target_troop"),	
    (troop_clear_inventory, "trp_temp_troop_for_copy"),	
	(troop_get_inventory_capacity, ":inv_cap", ":source_troop"),
	(assign, ":num_items", 0),
	(try_for_range, ":i_slot", 0, ":inv_cap"),
		(troop_get_inventory_slot, ":item_id", ":source_troop", ":i_slot"),
	    (ge, ":item_id", 0),
		(troop_set_slot, "trp_temp_array_a", ":num_items", ":item_id"),
		(val_add, ":num_items", 1),
	(try_end),
	(try_for_range, ":i_slot", 0, ":num_items"),
		(troop_get_slot, ":item_id", "trp_temp_array_a", ":i_slot"),
		(troop_remove_items, ":source_troop", ":item_id", 1),
		(assign, ":item_cost", reg0),
		(call_script, "script_get_item_imod", ":item_id", ":item_cost"),
		(assign, ":item_imod", reg0),
		(troop_add_item, ":target_troop", ":item_id", ":item_imod"),
		(troop_add_item, "trp_temp_troop_for_copy", ":item_id", ":item_imod"),	
	(try_end),
	# restore the original's inventory
	(call_script, "script_transfer_inventory", "trp_temp_troop_for_copy", ":source_troop"),
]),

##########################################################################################
# BoW: Transfers inventory from one troop to another
# Note: Be careful not to copy lots of items into a troop with low inventory management
##########################################################################################
# Param1: source troop
# Param2: target troop  
##########################################################################################
("transfer_inventory", [
	(store_script_param_1, ":source_troop"),
	(store_script_param_2, ":target_troop"),	
	(assign,":item_id",0),
	(troop_clear_inventory, ":target_troop"),	
	(troop_get_inventory_capacity, ":inv_cap", ":source_troop"),
	(assign, ":num_items", 0),
	(try_for_range, ":i_slot", 0, ":inv_cap"),
		(troop_get_inventory_slot, ":item_id", ":source_troop", ":i_slot"),
	    (ge, ":item_id", 0),
		(troop_set_slot, "trp_temp_array_a", ":num_items", ":item_id"),
		(val_add, ":num_items", 1),
	(try_end),
	(try_for_range, ":i_slot", 0, ":num_items"),
		(troop_get_slot, ":item_id", "trp_temp_array_a", ":i_slot"),
		(troop_remove_items, ":source_troop", ":item_id", 1),
		(assign, ":item_cost", reg0),
		(call_script, "script_get_item_imod", ":item_id", ":item_cost"),
		(assign, ":item_imod", reg0),
		(troop_add_item, ":target_troop", ":item_id", ":item_imod"),
	(try_end),
]),


##########################################################################################
# BoW: splits inventory into equippable and non-equippable inventories
##########################################################################################
# Param1: source troop
##########################################################################################
("split_inventory", [
	(store_script_param_1, ":source_troop"),
	(store_add, ":nonequipped_stuff", ":source_troop", npc_ine_op),
	(assign,":item_id",0),
	(assign, ":has_shield", 0),
	(assign, ":has_horse", 0),
	(assign, ":num_items", 0),	
	(troop_get_inventory_capacity, ":inv_cap", ":source_troop"),
	# record the item IDs
	(try_for_range, ":i_slot", 0, ":inv_cap"),
		(troop_get_inventory_slot, ":item_id", ":source_troop", ":i_slot"),
	    (ge, ":item_id", 0),
		(troop_set_slot, "trp_temp_array_a", ":num_items", ":item_id"),
		(val_add, ":num_items", 1),
	(try_end),

	# remove items and record the costs and imods, 
	(try_for_range, ":i_slot", 0, ":num_items"),
		(troop_get_slot, ":item_id", "trp_temp_array_a", ":i_slot"),
		(troop_remove_items, ":source_troop", ":item_id", 1),
		(assign, ":item_cost", reg0),
		(troop_set_slot, "trp_temp_array_b", ":i_slot", ":item_cost"),		
		(call_script, "script_get_item_imod", ":item_id", ":item_cost"),
		(assign, ":item_imod", reg0),		
		(troop_set_slot, "trp_temp_array_c", ":i_slot", ":item_imod"),
		(try_begin),
	       (is_between, ":item_id", items_shields_start, items_shields_end),
		   (assign, reg7, ":item_imod"),
		   (call_script, "script_troop_can_use_item", ":source_troop", ":item_id"),
		   (eq, reg0, 1),
		   (assign, ":has_shield", 1),
		(else_try),
	       (is_between, ":item_id", items_horses_start, items_horses_end),
		   (assign, reg7, ":item_imod"),
		   (call_script, "script_troop_can_use_item", ":source_troop", ":item_id"),
		   (eq, reg0, 1),
		   (assign, ":has_horse", 1),
		(try_end),
	(try_end),
	
	# melee weapon selection for heroes
	(try_begin),
		(troop_is_hero, ":source_troop"), # only need to do detailed weapon selection for heroes
		(assign, ":best_melee_weapon_score", 0),
		(assign, ":best_melee_weapon", 0),
		(try_for_range, ":i_slot", 0, ":num_items"),
			(troop_get_slot, ":item_id", "trp_temp_array_a", ":i_slot"),
			(troop_get_slot, ":item_cost", "trp_temp_array_b", ":i_slot"),
			(troop_get_slot, ":item_imod", "trp_temp_array_c", ":i_slot"),
			
			# initial score = cost + 1000
			(store_add, ":item_score", ":item_cost", 1000),
			(try_begin),
				(is_between, ":item_id", items_melee_weapons_start, items_melee_weapons_end),
				# select just one favored melee weapon
				# selection based on troop proficiency level : score = item cost + 2*troop proficiency level
				(try_begin),
				  (is_between, ":item_id", items_one_handed_start, items_one_handed_end),
		  		  (store_proficiency_level, ":skill", ":source_troop", proficiency_one_handed),
				  (val_mul, ":skill", 2),
				  (val_add, ":item_score", ":skill"),
				  (eq, "$battle_profile", battle_profile_shields_preferred),
				  (eq, ":has_shield", 1),
				  (val_add, ":item_score", 10000), # strongly prefer one-handed
				(try_end),

				(try_begin),
				  (is_between, ":item_id", items_two_handed_start, items_two_handed_end),
		  		  (store_proficiency_level, ":skill", ":source_troop", proficiency_two_handed),
				  (val_mul, ":skill", 2),
				  (val_add, ":item_score", ":skill"),
				(try_end),
						
				(try_begin),
				  (is_between, ":item_id", items_polearms_start, items_polearms_end),
		  		  (store_proficiency_level, ":skill", ":source_troop", proficiency_polearm),
				  (val_mul, ":skill", 2),
				  (val_add, ":item_score", ":skill"),
				  (try_begin),
				    (eq, "$battle_profile", battle_profile_polearms_preferred),
				    (val_add, ":item_score", 10000), # strongly prefer polearms
				  (else_try),
				    (eq, "$battle_profile", battle_profile_shields_preferred),
		  		    (is_between, ":item_id", items_one_handed_polearms_start, items_one_handed_polearms_end),
		  		    (eq, ":has_shield", 1),
				    (try_begin),
					  (eq, ":has_horse", 1),
					  (eq, "$start_charge_unmounted", 0), # got a horse can is using it = lance!
				      (val_add, ":item_score", 10000), # strongly prefer one-handed
				    (else_try),
				      (val_add, ":item_score", 9500), # one-handed polearms with shield, on foot: not as good (500 point penalty)
					(try_end),
				  (try_end),
				(try_end),		  

				(try_begin),
				  (is_between, ":item_id", items_melee_weapons_start, items_melee_weapons_end),
				  (neg|is_between, ":item_id", items_one_handed_cutting_start, items_one_handed_cutting_end),
				  (eq, "$battle_profile", battle_profile_armor_piercing_preferred),
				  (val_mul, ":item_score", 2), # double the score for non-1-handed cutting weapons since they're doubly effective vs armor
				(try_end),	

				(try_begin),
					# If it's a jousting or great lance...
					(this_or_next|eq, ":item_id", "itm_lianhalberd"),
					(this_or_next|eq, ":item_id", "itm_halberd"),
					(eq, ":item_id", "itm_bibardiche"),
					#...on foot...
					(this_or_next|eq, ":has_horse", 0), 
					(neq, "$start_charge_unmounted", 1),
					# then it's really utterly useless, I don't care how good your polearm skill is
					(assign, ":item_score", 1),
				(try_end),
				
				(try_begin),
					# update current favourite
					(assign, reg7, ":item_imod"),
	  			    (call_script, "script_troop_can_use_item", ":source_troop", ":item_id"),
					(eq, reg0, 1),				
					(ge, ":item_score", ":best_melee_weapon_score"),
					(assign, ":best_melee_weapon", ":i_slot"),
					(assign, ":best_melee_weapon_score", ":item_score"),
				(try_end),
			(try_end),
		(end_try),
	(try_end),
		
	# replace the items on the relevant troops		
	(try_for_range, ":i_slot", 0, ":num_items"),				
	    (troop_get_slot, ":item_id", "trp_temp_array_a", ":i_slot"),
	    (troop_get_slot, ":item_cost", "trp_temp_array_b", ":i_slot"),
		(troop_get_slot, ":item_imod", "trp_temp_array_c", ":i_slot"),		
		(assign, ":target_troop", ":source_troop"), # equip by default

		# if not using ranged, put all ranged weapons on nonequipped carrier
		(try_begin),
		  (eq, "$unready_ranged", 1),		  
		  (is_between, ":item_id", items_ranged_start, items_ranged_end),
		  (assign, ":target_troop", ":nonequipped_stuff"),
		(try_end),

		# if not using horses in combat, put them aside
		(try_begin),
		  (eq, "$start_charge_unmounted", 1),
		  (is_between, ":item_id", items_horses_start, items_horses_end),
		  (assign, ":target_troop", ":nonequipped_stuff"),
		(try_end),		

		(try_begin),
  		  # Not using sharps, put all nonblunt weapons on nonequipped carrier
		  (eq, "$battle_profile", battle_profile_blunts_only),
		  (is_between, ":item_id", items_weapons_start, items_weapons_end),
		  (neg| is_between, ":item_id", items_shields_start, items_shields_end),
		  # if it's a weapon, unequip it
		  (assign, ":target_troop", ":nonequipped_stuff"),
		  (this_or_next|is_between, ":item_id", items_one_handed_blunts_start, items_one_handed_blunts_end),
		  (this_or_next|is_between, ":item_id", items_two_handed_blunts_start, items_two_handed_blunts_end),
		  (this_or_next|is_between, ":item_id", items_polearms_blunts_start, items_polearms_blunts_end),
		  (this_or_next|eq, ":item_id", "itm_hammer"),
		  (this_or_next|eq, ":item_id", "itm_sledgehammer"),
		  (eq, ":item_id", "itm_stones"), # this is the only blunt ranged weapon
		  # if it's blunt, allow equipping
          (assign, ":target_troop", ":source_troop"),
		(try_end),

		(try_begin),
			(troop_is_hero, ":source_troop"),
			(try_begin),
			  # select favourite melee weapon
			  (neq, "$battle_profile", battle_profile_blunts_only),
			  (is_between, ":item_id", items_melee_weapons_start, items_melee_weapons_end),
			  (neq, ":i_slot", ":best_melee_weapon"), # unequip if not the best
			  (assign, ":target_troop", ":nonequipped_stuff"),
			(try_end),
		(else_try), #nonhero troops - assumed to have all weapon types (1-H melee, polearm) available
			(try_begin),
				(eq, "$battle_profile", battle_profile_polearms_preferred),
			    (is_between, ":item_id", items_melee_weapons_start, items_melee_weapons_end), # it's a melee weapon
				(neg|is_between, ":item_id", items_polearms_start, items_polearms_end), # but not a polearm
				(assign, ":target_troop", ":nonequipped_stuff"), # don't equip it.
			(else_try),			
				(eq, "$battle_profile", battle_profile_shields_preferred),		
			    (is_between, ":item_id", items_melee_weapons_start, items_melee_weapons_end), # it's a melee weapon
				(try_begin),
					#if it's 1-handed
					(this_or_next|is_between, ":item_id", items_one_handed_start, items_one_handed_end), 
					(is_between, ":item_id", items_one_handed_polearms_start, items_one_handed_polearms_end), 
					(assign, ":target_troop", ":source_troop"), # equip it.
				(else_try), # if it's 2-handed
					(assign, ":target_troop", ":nonequipped_stuff"), # don't equip it.
				(try_end),
			(try_end),
		(try_end),

		(troop_add_item, ":target_troop", ":item_id", ":item_imod"),
	(try_end),
]),

##########################################################################################
# BoW: Merge equippable and non-equippable inventories
##########################################################################################
# Param1: source troop
##########################################################################################
("merge_inventory", [
	(store_script_param_1, ":target_troop"),
	(store_add, ":source_troop", ":target_troop", npc_ine_op),
	(assign,":item_id",0),
	(troop_get_inventory_capacity, ":inv_cap", ":source_troop"),
	(assign, ":num_items", 0),
	(try_for_range, ":i_slot", 0, ":inv_cap"),
		(troop_get_inventory_slot, ":item_id", ":source_troop", ":i_slot"),
	    (ge, ":item_id", 0),
		(troop_set_slot, "trp_temp_array_a", ":num_items", ":item_id"),
		(val_add, ":num_items", 1),
	(try_end),
	(try_for_range, ":i_slot", 0, ":num_items"),
		(troop_get_slot, ":item_id", "trp_temp_array_a", ":i_slot"),
		(troop_remove_items, ":source_troop", ":item_id", 1),
		(assign, ":item_cost", reg0),
		(call_script, "script_get_item_imod", ":item_id", ":item_cost"),
		(assign, ":item_imod", reg0),
		(troop_add_item, ":target_troop", ":item_id", ":item_imod"),
	(try_end),
]),

##########################################################################################
# BoW: Split equippable and non-equippable inventories for all NPCs (and special troops) in party
##########################################################################################
("equip_for_battle", [
	(try_begin),
		(eq, "$battle_equipped", 0),
		# for all the NPCs,
	    (party_get_num_companion_stacks, ":num_stacks","p_main_party"),
	    (try_for_range, ":i_stack", 0, ":num_stacks"),
	        (party_stack_get_troop_id, ":this_hero","p_main_party",":i_stack"),
	        (this_or_next|is_between, ":this_hero", "trp_first_npc", "trp_last_npc"),
	        (is_between, ":this_hero", "trp_diaochan", "trp_wangxiaohu"),
			(call_script, "script_split_inventory", ":this_hero"),
		(try_end),
		(assign, "$battle_equipped", 1),
		(assign, "$reequip_needed", 1),		
	(end_try),
]),

##########################################################################################
# BoW: Reverse the above and restore full inventories for all
##########################################################################################
("unequip_for_battle", [
	(try_begin),
		(eq, "$battle_equipped", 1),
		# for all the NPCs,
	    (party_get_num_companion_stacks, ":num_stacks","p_main_party"),
	    (try_for_range, ":i_stack", 0, ":num_stacks"),
	        (party_stack_get_troop_id, ":this_hero","p_main_party",":i_stack"),
	        (this_or_next|is_between, ":this_hero", "trp_first_npc", "trp_last_npc"),
	        (is_between, ":this_hero", "trp_diaochan", "trp_wangxiaohu"),
			(call_script, "script_merge_inventory", ":this_hero"),
		(try_end),
		(assign, "$battle_equipped", 0),
		(assign, "$reequip_needed", 1),		
	(end_try),
]),

##########################################################################################
# BoW: sorts a troops inventory by price
##########################################################################################
# Param1: source troop
##########################################################################################
("sort_inventory", [
	(store_script_param_1, ":source_troop"),
	(assign,":item_id",0),
	(troop_get_inventory_capacity, ":inv_cap", ":source_troop"),
	(assign, ":num_items", 0),
	# record the item IDs
	(try_for_range, ":i_slot", 0, ":inv_cap"),
		(troop_get_inventory_slot, ":item_id", ":source_troop", ":i_slot"),
		(ge, ":item_id", 0),
		(troop_set_slot, "trp_temp_array_a", ":num_items", ":item_id"),
		(val_add, ":num_items", 1),
	(try_end),
	(assign, ":total_cost", 0),
	# remove items and record the costs
	(try_for_range, ":i_slot", 0, ":num_items"),
		(troop_get_slot, ":item_id", "trp_temp_array_a", ":i_slot"),
		(troop_remove_items, ":source_troop", ":item_id", 1),
		(assign, ":item_cost", reg0),
		(val_add, ":total_cost", ":item_cost"),
		(troop_set_slot, "trp_temp_array_b", ":i_slot", ":item_cost"),
	(end_try),
	# bubble-sort by cost
	(try_for_range, ":i_slot", 1, ":num_items"),
		(try_for_range_backwards, ":j_slot", ":i_slot",":num_items"),
			(try_begin),
				(store_sub, ":prev_slot", ":j_slot", 1),
				(troop_get_slot, ":item_cost_j", "trp_temp_array_b", ":j_slot"),
				(troop_get_slot, ":item_cost_prev", "trp_temp_array_b", ":prev_slot"),
				(lt, ":item_cost_prev", ":item_cost_j"),
				# out of order; do the swap
				(troop_set_slot, "trp_temp_array_b", ":j_slot", ":item_cost_prev", ),
				(troop_set_slot, "trp_temp_array_b", ":prev_slot", ":item_cost_j"),
				(troop_get_slot, ":item_id_j", "trp_temp_array_a", ":j_slot"),
				(troop_get_slot, ":item_id_prev", "trp_temp_array_a", ":prev_slot"),
				(troop_set_slot, "trp_temp_array_a", ":j_slot", ":item_id_prev", ),
				(troop_set_slot, "trp_temp_array_a", ":prev_slot", ":item_id_j"),
			(try_end),
		(try_end),
	(try_end),
	# replace them on the troop, most expensive first		
	(try_for_range, ":i_slot", 0, ":num_items"),				
		(troop_get_slot, ":item_id", "trp_temp_array_a", ":i_slot"),
		(troop_get_slot, ":item_cost", "trp_temp_array_b", ":i_slot"),
		(call_script, "script_get_item_imod", ":item_id", ":item_cost"),
		# reg0 is imod
		(troop_add_item, ":source_troop", ":item_id", reg0),
	(try_end),
	(assign, reg0, ":total_cost"),
]),


##########################################################################################
# Bow: Makes each hero grab stuff from trp_temp_troop and dump stuff that they no longer need, in stack order
##########################################################################################
("auto_loot_all", [
	# make sure inventories are unified
    (call_script, "script_unequip_for_battle"),
	# for all the NPCs,
	(party_get_num_companion_stacks, ":num_stacks","p_main_party"),
	(try_for_range, ":i_stack", 0, ":num_stacks"),
		(party_stack_get_troop_id, ":this_hero","p_main_party",":i_stack"),
		(is_between, ":this_hero", "trp_first_npc", "trp_last_npc"),
		(call_script, "script_auto_loot_merge", ":this_hero", 0), #grab essentials first
		(call_script, "script_analyze_inventory", ":this_hero", 1), #dump extraneous equipment		
	(try_end),
	(try_for_range, ":i_stack", 0, ":num_stacks"),
		(party_stack_get_troop_id, ":this_hero","p_main_party",":i_stack"),
		(is_between, ":this_hero", "trp_first_npc", "trp_last_npc"),
		(troop_get_slot,":skip_second_round",":this_hero",slot_no_pickup_backup_equipment),
		(neq, ":skip_second_round",1),		
		(call_script, "script_auto_loot_merge", ":this_hero", 1), #grab non essentials
		(call_script, "script_analyze_inventory", ":this_hero", 1), #dump extraneous equipment		
	(try_end),
]),

##########################################################################################
# Bow: Goes through a troop's inventories to find out the value of the best kind of each kind of item that they own.
##########################################################################################
# Param1: troop
# Param2: 0: don't discard items that are not best 1: throw items that are not best into trp_temp_troop's inventory
##########################################################################################
("analyze_inventory", [
	(store_script_param_1, ":source_troop"),
	(store_script_param_2, ":do_discard"),
	(store_add, ":source_troop_2nd_inventory", ":source_troop", npc_ine_op),#reedit mov.
	
	(try_begin),
	  (eq, ":do_discard", 1),
	  (assign, ":discard_troop", "trp_temp_troop"), #discard into trp_temp_troop
	(else_try),
	  (assign, ":discard_troop", ":source_troop"),  #discard into own inventory = no discard
	(try_end),
	
	(assign, ":best_one_handed_slot",0),
	(assign, "$best_horse_value",0),
	(assign, ":best_horse_slot",200),
	(assign, "$best_gloves_value",0),
	(assign, ":best_gloves_slot",200),
	(assign, "$best_boots_value",0),
	(assign, ":best_boots_slot",200),
	(assign, "$best_armor_value",0),
	(assign, ":best_armor_slot",200),
	(assign, "$best_helmet_value",0),
	(assign, ":best_helmet_slot",200),
	(assign, "$best_one_handed_value",0),
	(assign, ":best_one_handed_slot",200),
	(assign, "$best_one_handed_blunt_value",0),
	(assign, ":best_one_handed_blunts_slot",200),
	(assign, "$best_two_handed_value",0),
	(assign, ":best_two_handed_slot",200),
	(assign, "$best_polearm_value",0),
	(assign, ":best_polearm_slot",200),
	(assign, "$best_shield_value",0),
	(assign, ":best_shield_slot",200),
	(assign, "$best_throwing_value",0),
	(assign, ":best_throwing_slot",200),
	(assign, "$best_bow_value",0),
	(assign, ":best_bow_slot",200),
	(assign, ":best_arrows_value",0),
	(assign, ":best_arrows_slot",200),
	(assign, "$best_crossbow_value",0),
	(assign, ":best_crossbow_slot",200),
	(assign, ":best_bolts_value",0),
	(assign, ":best_bolts_slot",200),
	(assign, ":best_one_handed_blunts_slot", 0), 

	# If upgrading one kind of ranged weapons, don't keep the other kinds of ranged items
	(troop_get_slot, ":ranged_choice",":source_troop",slot_upgrade_ranged),
	(try_begin),
		(eq, ":ranged_choice", ranged_upgrade_bows),
		(assign, "$best_crossbow_value", 99999),
		(assign, ":best_bolts_value", 99999),
		(assign, "$best_throwing_value", 99999),
	(else_try),
		(eq, ":ranged_choice", ranged_upgrade_crossbows),
		(assign, "$best_bow_value", 99999),
		(assign, ":best_arrows_value", 99999),
		(assign, "$best_throwing_value", 99999),
	(else_try),
		(eq, ":ranged_choice", ranged_upgrade_throwing),
		(assign, "$best_crossbow_value", 99999),
		(assign, ":best_bolts_value", 99999),
		(assign, "$best_bow_value", 99999),
		(assign, ":best_arrows_value", 99999),
	(try_end),
		
	(assign, ":num_items", 0),
	# process main inventory
	(troop_get_inventory_capacity, ":inv_cap", ":source_troop"),
	# get the item IDs
	(try_for_range, ":i_slot", 0, ":inv_cap"),
		(troop_get_inventory_slot, ":item_id", ":source_troop", ":i_slot"),
	    (ge, ":item_id", 0),
		(troop_set_slot, "trp_temp_array_a", ":num_items", ":item_id"),
		(val_add, ":num_items", 1),
	(try_end),
	(assign, ":num_main_inventory_items", ":num_items"),
	# process secondary inventory
	(troop_get_inventory_capacity, ":inv_cap", ":source_troop_2nd_inventory"),
	# get the item IDs
	(try_for_range, ":i_slot", 0, ":inv_cap"),
		(troop_get_inventory_slot, ":item_id", ":source_troop_2nd_inventory", ":i_slot"),
	    (ge, ":item_id", 0),
		(troop_set_slot, "trp_temp_array_a", ":num_items", ":item_id"),
		(val_add, ":num_items", 1),
	(try_end),
	# remove items and record the costs
	(try_for_range, ":i_slot", 0, ":num_items"),
		(troop_get_slot, ":item_id", "trp_temp_array_a", ":i_slot"),
		(try_begin),
			(lt, ":i_slot", ":num_main_inventory_items"),
			(troop_remove_items, ":source_troop", ":item_id", 1),
		(else_try),
			(troop_remove_items, ":source_troop_2nd_inventory", ":item_id", 1),
		(try_end),
		(assign, ":item_cost", reg0),
		(call_script, "script_get_item_imod", ":item_id", ":item_cost"),
		(assign, ":item_imod", reg0),		
		(troop_set_slot, "trp_temp_array_b", ":i_slot", ":item_cost"),
		(troop_set_slot, "trp_temp_array_c", ":i_slot", ":item_imod"),		
		(troop_set_slot, "trp_temp_troop", ":i_slot", ":source_troop"),  #flag to keep by default
	(try_end),
				
	# analyze "goodness" of the items
	(try_for_range, ":i_slot", 0, ":num_items"),
		(troop_get_slot, ":item_id", "trp_temp_array_a", ":i_slot"),
		(troop_get_slot, ":item_cost", "trp_temp_array_b", ":i_slot"),
		(troop_get_slot, ":item_imod", "trp_temp_array_c", ":i_slot"),
		(try_begin),
		  (is_between, ":item_id", items_horses_start, items_horses_end),
		  (assign, "$reequip_needed", 1),
		  (assign, reg7, ":item_imod"),
		  (call_script, "script_troop_can_use_item", ":source_troop", ":item_id"),
		  (try_begin),
		    (eq, reg0, 1), # can use item
		    (gt, ":item_cost", "$best_horse_value"), # and it's the best (ridable) horse
			(try_begin),
			  (neq, ":best_horse_slot", 200), 
			  (troop_set_slot, "trp_temp_troop", ":best_horse_slot", ":discard_troop"), # flag previous best for discard
			(try_end),
			(assign, ":best_horse_slot", ":i_slot"), #update current best
		    (assign, "$best_horse_value", ":item_cost"),
		  (else_try),
		    # either can't use the item or it wasn't the best
			(troop_set_slot, "trp_temp_troop", ":i_slot", ":discard_troop"), # flag for discard
		  (try_end),
		(else_try),
		  (is_between, ":item_id", items_gloves_start, items_gloves_end),
		  (assign, reg7, ":item_imod"),
		  (call_script, "script_troop_can_use_item", ":source_troop", ":item_id"),
		  (try_begin),
		    (eq, reg0, 1), # can use item
		    (gt, ":item_cost", "$best_gloves_value"), # it's the best
			(try_begin),
			  (neq, ":best_gloves_slot", 200), 
			  (troop_set_slot, "trp_temp_troop", ":best_gloves_slot", ":discard_troop"), # flag previous best for discard
			(try_end),
			(assign, ":best_gloves_slot", ":i_slot"), #update current best
		    (assign, "$best_gloves_value", ":item_cost"),
		  (else_try),
		    # either can't use the item or it wasn't the best
			(troop_set_slot, "trp_temp_troop", ":i_slot", ":discard_troop"), # flag for discard
		  (try_end),
		(else_try),
		  (is_between, ":item_id", items_boots_start, items_boots_end),
		  (assign, reg7, ":item_imod"),
		  (call_script, "script_troop_can_use_item", ":source_troop", ":item_id"),
		  (try_begin),
		    (eq, reg0, 1), # can use item
		    (gt, ":item_cost", "$best_boots_value"), # it's the best
			(try_begin),
			  (neq, ":best_boots_slot", 200), 
			  (troop_set_slot, "trp_temp_troop", ":best_boots_slot", ":discard_troop"), # flag previous best for discard
			(try_end),
			(assign, ":best_boots_slot", ":i_slot"), #update current best
		    (assign, "$best_boots_value", ":item_cost"),
		  (else_try),
		    # either can't use the item or it wasn't the best
			(troop_set_slot, "trp_temp_troop", ":i_slot", ":discard_troop"), # flag for discard
		  (try_end),		  
		(else_try),
		  (is_between, ":item_id", items_armor_start, items_armor_end),
		  (assign, reg7, ":item_imod"),
		  (call_script, "script_troop_can_use_item", ":source_troop", ":item_id"),
		  (try_begin),
		    (eq, reg0, 1), # can use item
		    (gt, ":item_cost", "$best_armor_value"), # it's the best
			(try_begin),
			  (neq, ":best_armor_slot", 200), 
			  (troop_set_slot, "trp_temp_troop", ":best_armor_slot", ":discard_troop"), # flag previous best for discard
			(try_end),
			(assign, ":best_armor_slot", ":i_slot"), #update current best
		    (assign, "$best_armor_value", ":item_cost"),
		  (else_try),
		    # either can't use the item or it wasn't the best
			(troop_set_slot, "trp_temp_troop", ":i_slot", ":discard_troop"), # flag for discard
		  (try_end),
		(else_try),
		  (is_between, ":item_id", items_helmets_start, items_helmets_end),
		  (assign, reg7, ":item_imod"),
		  (call_script, "script_troop_can_use_item", ":source_troop", ":item_id"),
		  (try_begin),
		    (eq, reg0, 1), # can use item
		    (gt, ":item_cost", "$best_helmet_value"), # it's the best
			(try_begin),
			  (neq, ":best_helmet_slot", 200), 
			  (troop_set_slot, "trp_temp_troop", ":best_helmet_slot", ":discard_troop"), # flag previous best for discard
			(try_end),
			(assign, ":best_helmet_slot", ":i_slot"), #update current best
		    (assign, "$best_helmet_value", ":item_cost"),
		  (else_try),
		    # either can't use the item or it wasn't the best
			(troop_set_slot, "trp_temp_troop", ":i_slot", ":discard_troop"), # flag for discard
		  (try_end),
		(else_try),
		  (is_between, ":item_id", items_one_handed_start, items_one_handed_end),
		  (assign, reg7, ":item_imod"),
		  (call_script, "script_troop_can_use_item", ":source_troop", ":item_id"),
		  (try_begin),
		    (eq, reg0, 1), # can use item
		    (gt, ":item_cost", "$best_one_handed_value"), # it's the best
			(try_begin),
			  (neq, ":best_one_handed_slot", 200), 
			  (neq, ":best_one_handed_slot", ":best_one_handed_blunts_slot"), #don't discard your best blunt
			  (troop_set_slot, "trp_temp_troop", ":best_one_handed_slot", ":discard_troop"), # flag previous best for discard
			(try_end),
			(assign, ":best_one_handed_slot", ":i_slot"), #update current best
		    (assign, "$best_one_handed_value", ":item_cost"),
		  (else_try),
		    # either can't use the item or it wasn't the best
			(troop_set_slot, "trp_temp_troop", ":i_slot", ":discard_troop"), # flag for discard
		  (try_end),
    	  # check for blunts
		  (try_begin), 
			  (this_or_next|eq, ":item_id", "itm_hammer"),
#			  (this_or_next|eq, ":item_id", "itm_wu"),
		      (is_between, ":item_id", items_one_handed_blunts_start, items_one_handed_blunts_end),
			  (assign, reg7, ":item_imod"),
			  (call_script, "script_troop_can_use_item", ":source_troop", ":item_id"),
			  (try_begin),
				(eq, reg0, 1), # can use item
				(gt, ":item_cost", "$best_one_handed_blunt_value"), # it's the best
				(troop_set_slot, "trp_temp_troop", ":i_slot", ":source_troop"),  #re-flag to keep this one
				(try_begin),
				  (neq, ":best_one_handed_blunts_slot", 200), 
				  (troop_set_slot, "trp_temp_troop", ":best_one_handed_blunts_slot", ":discard_troop"), # flag previous best for discard
				(try_end),
				(assign, ":best_one_handed_blunts_slot", ":i_slot"), #update current best
				(assign, "$best_one_handed_blunt_value", ":item_cost"),
			  (else_try),
				# either can't use the item or it wasn't the best
				(troop_set_slot, "trp_temp_troop", ":i_slot", ":discard_troop"), # flag for discard
			  (try_end),
		  (end_try),
		(else_try),
		  (is_between, ":item_id", items_two_handed_start, items_two_handed_end),
		  (assign, reg7, ":item_imod"),
		  (call_script, "script_troop_can_use_item", ":source_troop", ":item_id"),
		  (try_begin),
		    (eq, reg0, 1), # can use item
		    (gt, ":item_cost", "$best_two_handed_value"), # it's the best
			(try_begin),
			  (neq, ":best_two_handed_slot", 200), 
			  (troop_set_slot, "trp_temp_troop", ":best_two_handed_slot", ":discard_troop"), # flag previous best for discard
			(try_end),
			(assign, ":best_two_handed_slot", ":i_slot"), #update current best
		    (assign, "$best_two_handed_value", ":item_cost"),
		  (else_try),
		    # either can't use the item or it wasn't the best
			(troop_set_slot, "trp_temp_troop", ":i_slot", ":discard_troop"), # flag for discard
		  (try_end),
		(else_try),
		  (is_between, ":item_id", items_polearms_start, items_polearms_end),
		  (assign, reg7, ":item_imod"),
		  (call_script, "script_troop_can_use_item", ":source_troop", ":item_id"),
		  (try_begin),
		    (eq, reg0, 1), # can use item
		    (gt, ":item_cost", "$best_polearm_value"), # it's the best
			(try_begin),
			  (neq, ":best_polearm_slot", 200), 
			  (troop_set_slot, "trp_temp_troop", ":best_polearm_slot", ":discard_troop"), # flag previous best for discard
			(try_end),
			(assign, ":best_polearm_slot", ":i_slot"), #update current best
		    (assign, "$best_polearm_value", ":item_cost"),
		  (else_try),
		    # either can't use the item or it wasn't the best
			(troop_set_slot, "trp_temp_troop", ":i_slot", ":discard_troop"), # flag for discard
		  (try_end),
		(else_try),
		  (is_between, ":item_id", items_shields_start, items_shields_end),
		  (assign, reg7, ":item_imod"),
		  (call_script, "script_troop_can_use_item", ":source_troop", ":item_id"),
		  (try_begin),
		    (eq, reg0, 1), # can use item
		    (gt, ":item_cost", "$best_shield_value"), # it's the best
			(try_begin),
			  (neq, ":best_shield_slot", 200), 
			  (troop_set_slot, "trp_temp_troop", ":best_shield_slot", ":discard_troop"), # flag previous best for discard
			(try_end),
			(assign, ":best_shield_slot", ":i_slot"), #update current best
		    (assign, "$best_shield_value", ":item_cost"),
		  (else_try),
		    # either can't use the item or it wasn't the best
			(troop_set_slot, "trp_temp_troop", ":i_slot", ":discard_troop"), # flag for discard
		  (try_end),
		(else_try),
		  (is_between, ":item_id", items_throwing_start, items_throwing_end),
		  (assign, reg7, ":item_imod"),
		  (call_script, "script_troop_can_use_item", ":source_troop", ":item_id"),
		  (try_begin),
		    (eq, reg0, 1), # can use item
		    (gt, ":item_cost", "$best_throwing_value"), # it's the best
			(try_begin),
			  (neq, ":best_throwing_slot", 200), 
			  (troop_set_slot, "trp_temp_troop", ":best_throwing_slot", ":discard_troop"), # flag previous best for discard
			(try_end),
			(assign, ":best_throwing_slot", ":i_slot"), #update current best
		    (assign, "$best_throwing_value", ":item_cost"),
		  (else_try),
		    # either can't use the item or it wasn't the best
			(troop_set_slot, "trp_temp_troop", ":i_slot", ":discard_troop"), # flag for discard
		  (try_end),
		(else_try),
		  (is_between, ":item_id", items_bows_start, items_bows_end),
		  (assign, reg7, ":item_imod"),
		  (call_script, "script_troop_can_use_item", ":source_troop", ":item_id"),
		  (try_begin),
		    (eq, reg0, 1), # can use item
		    (gt, ":item_cost", "$best_bow_value"), # it's the best
			(try_begin),
			  (neq, ":best_bow_slot", 200), 
			  (troop_set_slot, "trp_temp_troop", ":best_bow_slot", ":discard_troop"), # flag previous best for discard
			(try_end),
			(assign, ":best_bow_slot", ":i_slot"), #update current best
		    (assign, "$best_bow_value", ":item_cost"),
		  (else_try),
		    # either can't use the item or it wasn't the best
			(troop_set_slot, "trp_temp_troop", ":i_slot", ":discard_troop"), # flag for discard
		  (try_end),
		(else_try),
		  (is_between, ":item_id", items_crossbows_start, items_crossbows_end),
		  (assign, reg7, ":item_imod"),
		  (call_script, "script_troop_can_use_item", ":source_troop", ":item_id"),
		  (try_begin),
		    (eq, reg0, 1), # can use item
		    (gt, ":item_cost", "$best_crossbow_value"), # it's the best
			(try_begin),
			  (neq, ":best_crossbow_slot", 200), 
			  (troop_set_slot, "trp_temp_troop", ":best_crossbow_slot", ":discard_troop"), # flag previous best for discard
			(try_end),
			(assign, ":best_crossbow_slot", ":i_slot"), #update current best
		    (assign, "$best_crossbow_value", ":item_cost"),
		  (else_try),
		    # either can't use the item or it wasn't the best
			(troop_set_slot, "trp_temp_troop", ":i_slot", ":discard_troop"), # flag for discard
		  (try_end),
		(else_try),
		  (is_between, ":item_id", "itm_bodkin_arrows", "itm_bolts"),
		  (try_begin),
		    (gt, ":item_cost", ":best_arrows_value"), # it's the best
			(try_begin),
			  (neq, ":best_arrows_slot", 200), 
			  (troop_set_slot, "trp_temp_troop", ":best_arrows_slot", ":discard_troop"), # flag previous best for discard
			(try_end),
			(assign, ":best_arrows_slot", ":i_slot"), #update current best
		    (assign, ":best_arrows_value", ":item_cost"),
		  (else_try),
		    # either can't use the item or it wasn't the best
			(troop_set_slot, "trp_temp_troop", ":i_slot", ":discard_troop"), # flag for discard
		  (try_end),
		(else_try),
		  (this_or_next|eq, ":item_id", "itm_bolts"),
		  (eq, ":item_id", "itm_iron_bolts"),
		  (try_begin),
		    (gt, ":item_cost", ":best_bolts_value"), # it's the best
			(try_begin),
			  (neq, ":best_bolts_slot", 200), 
			  (troop_set_slot, "trp_temp_troop", ":best_bolts_slot", ":discard_troop"), # flag previous best for discard
			(try_end),
			(assign, ":best_bolts_slot", ":i_slot"), #update current best
		    (assign, ":best_bolts_value", ":item_cost"),
		  (else_try),
		    # either can't use the item or it wasn't the best
			(troop_set_slot, "trp_temp_troop", ":i_slot", ":discard_troop"), # flag for discard
		  (try_end),
		(try_end),				
	(end_try),
		
	(troop_get_slot, ":keep_inventory", ":source_troop", slot_no_discard_in_auto_loot),
	(try_for_range, ":i_slot", 0, ":num_items"),
		(troop_get_slot, ":item_id", "trp_temp_array_a", ":i_slot"),
		(troop_get_slot, ":item_cost", "trp_temp_array_b", ":i_slot"),
		(troop_get_slot, ":item_imod", "trp_temp_array_c", ":i_slot"),
		(troop_get_slot, ":target_troop", "trp_temp_troop", ":i_slot"),
		
		(try_begin),
			(eq, ":keep_inventory", 1),
			(lt, ":i_slot", ":num_main_inventory_items"),
			# item was in original equipment, not item pool. Don't discard.
			(assign, ":target_troop", ":source_troop"),
		(try_end),
		
		(try_begin),
			(store_free_inventory_capacity, ":capacity", ":target_troop"),
			(gt, ":capacity", 0),
			(troop_add_item, ":target_troop", ":item_id", ":item_imod"),
		(else_try),
			# target troop had insufficient space
			(eq, ":do_discard", 0), # not due to auto-loot
			# Error!: total items more than main inventory size (just discard the item)
			(str_store_troop_name, 1, ":source_troop"),
			(display_message, "str_item_error_remerge_toobig"),			
		(else_try),
			# try chucking it in the item pool
			(store_free_inventory_capacity, ":capacity", "trp_temp_troop"),
			(gt, ":capacity", 0),
			(troop_add_item, "trp_temp_troop", ":item_id", ":item_imod"),
		(else_try),
			# item pool full, try keeping it
			(store_free_inventory_capacity, ":capacity", ":source_troop"),
			(gt, ":capacity", 0),
			(troop_add_item, ":source_troop", ":item_id", ":item_imod"),			
		(else_try),
			# both item pool and personal inventory is full, should not happen
			(str_store_troop_name, 1, ":source_troop"),
			(display_message, "str_item_error_everything_full"),				
		(end_try),
	(try_end),
]),

########################################################################################
# BoW : Loads equipment items (horses, armor, weapons) from trp_temp_troop into hero troop's auxiliary inventory
# Can specify to load everything or just the stuff they would be interested in buying.
########################################################################################
# Param1: target troop
# Param2: 0: just load the stuff that the troop would buy, 1: load everything
########################################################################################

("auto_loot_merge", [
	(store_script_param_1, ":troop"),
	(store_script_param_2, ":merge_everything"),
	(assign, ":source_troop", "trp_temp_troop"),
	# merge it to the auxiliary inventory, not to the main inventory
	(store_add, ":troop_2nd_inventory", ":troop", npc_ine_op),
	# make sure it is clear first so everything can fit
	(troop_clear_inventory, ":troop_2nd_inventory"),
	(assign,":item_id",0),
	(troop_get_slot, ":armor_choice",":troop",slot_upgrade_armor),
	(troop_get_slot, ":ranged_choice",":troop",slot_upgrade_ranged),
	(troop_get_slot, ":melee_choice",":troop",slot_upgrade_melee),
	(troop_get_slot, ":horse_choice",":troop",slot_upgrade_horse),
		
	(troop_get_inventory_capacity, ":inv_cap", ":source_troop"),
	(assign, ":num_items", 0),
	# get list of item IDs that are to be added
	(try_for_range, ":i_slot", 0, ":inv_cap"),
		(troop_get_inventory_slot, ":item_id", ":source_troop", ":i_slot"),
	    (ge, ":item_id", 0),
		(assign, ":do_add", 0),
		
		# horses
		(try_begin),
		  (is_between, ":item_id", items_horses_start, items_horses_end),
		  #(this_or_next|eq, ":merge_everything", 1),
		  (eq, ":horse_choice",1),
		  (assign, ":do_add", 1),		  
		(try_end),
		# wearables
		(try_begin),
		  (is_between, ":item_id", items_wearables_start, items_wearables_end),
		  (this_or_next|eq, ":merge_everything", 1),
		  (eq, ":armor_choice",1),
		  (assign, ":do_add", 1),		  
		(try_end),
		# 1-h melee
		(try_begin),
		  (is_between, ":item_id", items_one_handed_start, items_one_handed_end),
		  (eq, ":melee_choice",melee_upgrade_one_handed),
		  (assign, ":do_add", 1),		  
		(try_end),
		# 2-h melee
		(try_begin),
		  (is_between, ":item_id", items_two_handed_start, items_two_handed_end),
		  (eq, ":melee_choice",melee_upgrade_two_handed),
		  (assign, ":do_add", 1),		  
		(try_end),
		# polearms
		(try_begin),
		  (is_between, ":item_id", items_polearms_start, items_polearms_end),
		  (this_or_next|eq, ":merge_everything", 1),
		  (eq, ":melee_choice",melee_upgrade_polearms),
		  (assign, ":do_add", 1),		  
		(try_end),	
		# 1-h polearms aka lances
		(try_begin),
		  (is_between, ":item_id", items_one_handed_polearms_start, items_one_handed_polearms_end),
		  (eq, ":melee_choice",melee_upgrade_lances),
		  (assign, ":do_add", 1),		  
		(try_end),
		# 1-h blunts
		(try_begin),
		  (this_or_next|eq, ":item_id", "itm_hammer"), 
#		  (this_or_next|eq, ":item_id", "itm_wu"), 
		  (is_between, ":item_id", items_one_handed_blunts_start, items_one_handed_blunts_end),
		  (this_or_next|eq, ":merge_everything", 1),
		  (eq, ":melee_choice",melee_upgrade_blunts),
		  (assign, ":do_add", 1),		  
		(try_end),		
		# shields
		(try_begin),
		  (is_between, ":item_id", items_shields_start, items_shields_end),
		  (this_or_next|eq, ":merge_everything", 1),
		  (this_or_next|eq, ":melee_choice",melee_upgrade_one_handed),
		  (this_or_next|eq, ":melee_choice",melee_upgrade_lances),
		  (eq, ":melee_choice",melee_upgrade_blunts),
		  (assign, ":do_add", 1),		  
		(try_end),		
		# bows
		(try_begin),
		  (this_or_next|is_between, ":item_id", items_bows_start, items_bows_end),
		  (is_between, ":item_id", "itm_bodkin_arrows", "itm_bolts"),
		  (eq, ":ranged_choice",ranged_upgrade_bows),
		  (assign, ":do_add", 1),		  
		(try_end),		
		# crossbows
		(try_begin),
		  (this_or_next|eq, ":item_id", "itm_bolts"),
		  (this_or_next|eq, ":item_id", "itm_iron_bolts"),
		  (is_between, ":item_id", items_crossbows_start, items_crossbows_end),
		  (eq, ":ranged_choice",ranged_upgrade_crossbows),
		  (assign, ":do_add", 1),		  
		(try_end),		
		# throwing
		(try_begin),
		  (is_between, ":item_id", items_throwing_start, items_throwing_end),
		  (eq, ":ranged_choice",ranged_upgrade_throwing),
		  (assign, ":do_add", 1),		  
		(try_end),		
		
		(eq, ":do_add", 1),
		(troop_set_slot, "trp_temp_array_a", ":num_items", ":item_id"),
		(val_add, ":num_items", 1),
	(try_end),
	# remove them from the source troop and extract imods
	(try_for_range, ":i_slot", 0, ":num_items"),
		(troop_get_slot, ":item_id", "trp_temp_array_a", ":i_slot"),
		(troop_remove_items, ":source_troop", ":item_id", 1),
		(assign, ":item_cost", reg0),
		(call_script, "script_get_item_imod", ":item_id", ":item_cost"),
		(assign, ":item_imod", reg0),
		(troop_set_slot, "trp_temp_array_b", ":i_slot", ":item_imod"),
	(try_end),
	# insert items onto the target troop if target troop can use it; otherwise replace on source troop
	(try_for_range, ":i_slot", 0, ":num_items"),
		(troop_get_slot, ":item_id", "trp_temp_array_a", ":i_slot"),
		(troop_get_slot, ":item_imod", "trp_temp_array_b", ":i_slot"),
		(assign, reg7, ":item_imod"),
		(call_script, "script_troop_can_use_item_well", ":troop", ":item_id"),
		(try_begin),
			(eq, reg0, 1), # can use
			(troop_add_item, ":troop_2nd_inventory", ":item_id", ":item_imod"),
		(else_try), # can't use
			(troop_add_item, ":source_troop", ":item_id", ":item_imod"),
		(try_end),
	(try_end),	
]),


##########################################################################################
# BoW : Determine the imod of a given item by price
##########################################################################################
# Param1: item ID
# Param2: item cost
##########################################################################################
("get_item_imod", [
	(assign, reg0, 0),
	(store_script_param_1, ":item"),
	(store_script_param_2, reg1),	
    (store_item_value, reg2, ":item"), 
	(val_mul, reg1, 100),  
	(val_div, reg1, reg2),   #reg1 = (actual cost / base cost)*100
	
	(val_sub, reg1, 3), # correct for rounding errors
	
	(try_begin),
	  (le, reg1, 30),
	  (assign, reg0, imod_lame),
	(else_try),
	  (le, reg1, 40),
	  (try_begin),

		(this_or_next|is_between, ":item", items_cloth_boots_start, items_cloth_boots_end),
		(this_or_next|is_between, ":item", items_cloth_armor_start, items_cloth_armor_end),
		            (is_between, ":item", items_cloth_helmets_start, items_cloth_helmets_end),
		(assign, reg0, imod_tattered),
	  (else_try),
		(assign, reg0, imod_cracked),
	  (try_end),	  
	(else_try),
	  (le, reg1, 50),
	  (try_begin),
        (is_between, ":item", items_horses_start, items_horses_end),
        (assign, reg0, imod_swaybacked),
      (else_try),
	    (assign, reg0, imod_rusty),
	  (try_end),		
	(else_try),
	  (le, reg1, 60),
	  (try_begin),
	    (this_or_next| is_between, ":item", items_ammo_start, items_ammo_end),
        (is_between, ":item", items_weapons_start, items_weapons_end),
		(assign, reg0, imod_bent),
      (else_try),
        (assign, reg0, imod_ragged),
	  (try_end),		
	(else_try),
	  (le, reg1, 65),
	  (try_begin),
        (is_between, ":item", items_weapons_start, items_weapons_end),
		(assign, reg0, imod_chipped),
      (else_try),
        (assign, reg0, imod_battered),
	  (try_end),		
	(else_try),
	  (le, reg1, 80),
	  (assign, reg0, imod_crude),
	(else_try),
	  (le, reg1, 90),
	  (assign, reg0, imod_stubborn),
	(else_try),
	  (le, reg1, 100),
	  (assign, reg0, imod_plain),
	(else_try),
	  (le, reg1, 135),
	  (assign, reg0, imod_heavy),
	(else_try),
	  (le, reg1, 190),
	  (assign, reg0, imod_large_bag),
	(else_try),
	  (le, reg1, 240),
	  (assign, reg0, imod_temperate),
	(else_try),
	  (le, reg1, 270),
	  (assign, reg0, imod_sturdy),
	(else_try),
	  (le, reg1, 410),
	  (assign, reg0, imod_thick),
	(else_try),
	  (le, reg1, 470),
	  (assign, reg0, imod_spirited),
	(else_try),
	  (le, reg1, 560),
	  (assign, reg0, imod_balanced),
	(else_try),
	  (le, reg1, 580),
	  (assign, reg0, imod_hardened),
	(else_try),
	  (le, reg1, 690),
	  (assign, reg0, imod_watered_steel),
	(else_try),
	  (le, reg1, 720),
	  (assign, reg0, imod_reinforced),
	(else_try),
	  (assign, reg40, reg1),
	  (str_store_item_name, 40, ":item"),
	  (tutorial_box, "str_item_debug"),	  
	(try_end),
	
]),

########################################################################################
# BoW : Check if a troop can use an item
# param1: troop
# param2: item
# reg7: item imod
########################################################################################
("troop_can_use_item", [
	(store_script_param_1, ":troop"),
	(store_script_param_2, ":item"),
	(assign, ":item_imod", reg7),
	
	(assign, ":stat_needed", 0),
	(assign, ":troop_stat", 0),
	(assign, ":automatic_fail", 0),
	
	(try_begin),
		# HORSES
		(is_between, ":item", items_horses_start, items_horses_end),
		(store_skill_level, ":troop_stat", skl_riding, ":troop"),
		(try_begin),
		  (this_or_next|eq, ":item", "itm_saddle_horse"),
		  (eq, ":item", "itm_sumpter_horse"),
		  (assign, ":stat_needed", 1),
		(else_try),
		  (this_or_next|eq, ":item", "itm_steppe_horse"),
		  (eq, ":item", "itm_saddle_horse"),
		  (assign, ":stat_needed", 2),
		(else_try),
		  (this_or_next|eq, ":item", "itm_zhanhorse"),
		  (this_or_next|eq, ":item", "itm_xuehorse"),
		  (this_or_next|eq, ":item", "itm_dragonhorse"),
		  (eq, ":item", "itm_hunter"),
		  (assign, ":stat_needed", 3),
		(else_try),
		  (this_or_next|eq, ":item", "itm_xuehorse"),
		  (this_or_next|eq, ":item", "itm_wushunhorse"),
		  (eq, ":item", "itm_dahorse"),
		  (assign, ":stat_needed", 4),
		(else_try),
		  (this_or_next|eq, ":item", "itm_chihorse"),
		  (this_or_next|eq, ":item", "itm_dihorse"),
		  (eq, ":item", "itm_zhuahorse"),
		  (assign, ":stat_needed", 5),
		(try_end),
		(try_begin),
			(eq, ":item_imod", imod_stubborn),
			(val_add, ":stat_needed", 1),
		(else_try),
			(eq, ":item_imod", imod_temperate),
			(val_sub, ":stat_needed", 1),
		(else_try),
			(eq, ":item_imod", imod_lame),
			(assign, ":automatic_fail", 1),
		(try_end),		
	(else_try),
		# STRENGTH items
		(this_or_next|is_between, ":item", items_armor_start, items_armor_end),
		(this_or_next|is_between, ":item", items_helmets_start, items_helmets_end),
		(this_or_next|is_between, ":item", items_one_handed_start, items_polearms_end),
		(is_between, ":item", items_crossbows_start, items_crossbows_end),
		
		(store_attribute_level, ":troop_stat", ":troop", ca_strength),
						  		
		# female armors
		(try_begin),
		  (this_or_next|eq, ":item", "itm_womancloth2"),
		  (this_or_next|eq, ":item", "itm_womancloth1"),
		  (eq, ":item", "itm_diaochan"),
		  (assign, ":automatic_fail", 1), #disallow wearing
		  (this_or_next|eq, ":troop", "trp_diaochan"),
		  (this_or_next|eq, ":troop", "trp_shahongbing"),
		  (is_between, ":troop", "trp_diaochan", "trp_wangxiaohu"),
		  (assign, ":automatic_fail", 0), # unless you're a woman 
		(try_end),
		
		(try_begin),
		  (eq, ":item", "itm_zhanxie"),
		  (assign, ":stat_needed", 6),
		(else_try),
		  (this_or_next|eq, ":item", "itm_wuxie"),
		  (this_or_next|eq, ":item", "itm_ironarmor"),
		  (this_or_next|eq, ":item", "itm_tiezhou"),
		  (this_or_next|eq, ":item", "itm_ptiekui"),		  
		  (this_or_next|eq, ":item", "itm_tiezhajia"),		  
		  (this_or_next|eq, ":item", "itm_ironarmora"),		  
		  (this_or_next|eq, ":item", "itm_bupick"),
		  (this_or_next|eq, ":item", "itm_geb"),
		  (this_or_next|eq, ":item", "itm_zhanmabardiche"),
		 (eq, ":item", "itm_china_100huanshou"),		  
		  (assign, ":stat_needed", 7),
		(else_try),
		  (this_or_next|eq, ":item", "itm_jian"),
		  (this_or_next|eq, ":item", "itm_dayue"),
		  (this_or_next|eq, ":item", "itm_yue"),
		  (this_or_next|eq, ":item", "itm_pick"),
		  (this_or_next|eq, ":item", "itm_china_pike"),
		  (this_or_next|eq, ":item", "itm_mingarmora"),
		  (this_or_next|eq, ":item", "itm_mingarmor"),
		  (this_or_next|eq, ":item", "itm_yanbiana"),
		  (this_or_next|eq, ":item", "itm_yanbian"),
		  (eq, ":item", "itm_splinted_greaves"),
		  (assign, ":stat_needed", 8),
		(else_try),
		  (this_or_next|eq, ":item", "itm_dayue"),
		  (this_or_next|eq, ":item", "itm_ironshoes"),
		  (this_or_next|eq, ":item", "itm_yanbianc"),
		  (this_or_next|eq, ":item", "itm_yanyitoukui"),
		  (this_or_next|eq, ":item", "itm_tongarmor"),
		  (this_or_next|eq, ":item", "itm_mingarmorb"),
		  (this_or_next|eq, ":item", "itm_dbspear"),
		  (this_or_next|eq, ":item", "itm_mapick"),
		  (this_or_next|eq, ":item", "itm_zhanmabardiche"),
		  (eq, ":item", "itm_zhongzhandao"),
		  (assign, ":stat_needed", 9),
		(else_try),
                (this_or_next|eq, ":item", "itm_wuwushen2"),
		  (this_or_next|eq, ":item", "itm_weiwushen2"),
		  (this_or_next|eq, ":item", "itm_shuwushen2"),
		  (this_or_next|eq, ":item", "itm_wuwushen1"),
		  (this_or_next|eq, ":item", "itm_weiwushen1"),
		  (this_or_next|eq, ":item", "itm_shuwushen1"),
		  (this_or_next|eq, ":item", "itm_smyshen"),
		  (this_or_next|eq, ":item", "itm_wugousword"),
		  (this_or_next|eq, ":item", "itm_diaochan"),
		  (this_or_next|eq, ":item", "itm_zglshen"),
		  (eq, ":item", "itm_lxshen"),
		  (assign, ":stat_needed", 10),
		(else_try),
		  (this_or_next|eq, ":item", "itm_shuangci"),
		  (this_or_next|eq, ":item", "itm_shuangxi"),
		  (this_or_next|eq, ":item", "itm_yinxie"),
		  (this_or_next|eq, ":item", "itm_goulian"),
		  (this_or_next|eq, ":item", "itm_sanjiandao"),
		  (eq, ":item", "itm_zyshen"),
		  (assign, ":stat_needed", 11),
		(else_try),
		  (this_or_next|eq, ":item", "itm_lbeishen"),
		  (eq, ":item", "itm_ccshen"),
		  (assign, ":stat_needed", 12),
		(else_try),
		  (this_or_next|eq, ":item", "itm_gyshen"),
		  (eq, ":item", "itm_mcshen"),
		  (assign, ":stat_needed", 13),
		(else_try),
		  (eq, ":item", "itm_tiejispear"),
		  (assign, ":stat_needed", 14),		  
		(else_try),
		  (this_or_next|eq, ":item", "itm_yinjia"),
		  (this_or_next|eq, ":item", "itm_lbshen"),
		  (this_or_next|eq, ":item", "itm_steelspear"),
		  (this_or_next|eq, ":item", "itm_silverlance"),
		  (this_or_next|eq, ":item", "itm_fangtianhalberd"),
		  (this_or_next|eq, ":item", "itm_qinglongbardiche"),
		  (this_or_next|eq, ":item", "itm_yitiansword"),
		  (this_or_next|eq, ":item", "itm_yuitian"),
		  (this_or_next|eq, ":item", "itm_jinxie"),
		  (eq, ":item", "itm_hutou"),
		  (assign, ":stat_needed", 15),		  
		(try_end),
	(else_try),
		# THROWN items
		(is_between, ":item", items_throwing_start, items_throwing_end),		
		(store_skill_level, ":troop_stat", skl_power_throw, ":troop"),
		
		(try_begin),
		  (this_or_next|eq, ":item", "itm_throwing_daggers"),
		  (eq, ":item", "itm_jarid"),
		  (assign, ":stat_needed", 1),
		(try_end),
	(else_try),
		# BOW items
		(is_between, ":item", items_bows_start, items_bows_end),		
		(store_skill_level, ":troop_stat", skl_power_draw, ":troop"),
		(try_begin),
		  (eq, ":item", "itm_hunting_bow"),
		  (assign, ":stat_needed", 0),		  
		(else_try),
		  (eq, ":item", "itm_short_bow"),
		  (assign, ":stat_needed", 1),		  
		(else_try),
		  (eq, ":item", "itm_nomad_bow"),
		  (assign, ":stat_needed", 2),
		(else_try),
		  (this_or_next|eq, ":item", "itm_long_bow"),
		  (this_or_next|eq, ":item", "itm_strong_bow"),
		  (eq, ":item", "itm_cavalry_bow"),
		  (assign, ":stat_needed", 3),
		(else_try),
		  (eq, ":item", "itm_war_bow"),
		  (assign, ":stat_needed", 4),
		(try_end),
	(try_end),

	(try_begin),
		(ge, ":troop_stat", ":stat_needed"),
		(neq, ":automatic_fail", 1),
		(assign, reg0, 1),
	(else_try),
		(assign, reg0, 0),
	(try_end),
]),

# Stricter version of troop_can_use_item
# higher power draw requirements for bows + weapon proficiency check
# param 1: troop
# param 2: item ID
# reg7: item modifier
("troop_can_use_item_well", [
	(store_script_param_1, ":troop"),
	(store_script_param_2, ":item"),
	(assign, ":item_imod", reg7),

	(try_begin),
		# BOW items
		(is_between, ":item", items_bows_start, items_bows_end),		
		(store_skill_level, ":troop_stat", skl_power_draw, ":troop"),
		(try_begin),
		  (eq, ":item", "itm_hunting_bow"),
		  (assign, ":stat_needed", 2),		  
		(else_try),
		  (eq, ":item", "itm_short_bow"),
		  (assign, ":stat_needed", 3),		  
		(else_try),
		  (eq, ":item", "itm_nomad_bow"),
		  (assign, ":stat_needed", 4),
		(else_try),
		  (this_or_next|eq, ":item", "itm_long_bow"),
		  (this_or_next|eq, ":item", "itm_cavalry_bow"),
		  (eq, ":item", "itm_strong_bow"),
		  (assign, ":stat_needed", 5),
		(else_try),
		  (eq, ":item", "itm_war_bow"),
		  (assign, ":stat_needed", 6),
		(try_end),
		# also check weapon proficiency
		(store_sub, ":skill_needed", ":stat_needed", 2),
		(val_mul, ":skill_needed", 60),
		(store_proficiency_level, ":archery_skill", ":troop", proficiency_archery),		
		(store_skill_level, ":power_draw", skl_power_draw, ":troop"),
		(try_begin),
			(ge, ":power_draw", ":stat_needed"),
			(ge, ":archery_skill", ":skill_needed"),
			(assign, reg0, 1),
		(else_try),
			(assign, reg0, 0),
		(try_end),		
	(else_try),
		(call_script, "script_troop_can_use_item", ":troop", ":item"),
	(try_end),
]),

("give_special_loot", [
    (store_script_param_1, ":party"), #Party_id
    (store_script_param_2, ":allied_party"), #Party_id

    (call_script, "script_calculate_party_shares", ":allied_party"),
    (assign, ":num_player_party_shares", reg0),
    (assign, ":num_ally_shares", reg1),
    (store_add, ":num_total_shares",  ":num_player_party_shares", ":num_ally_shares"),

    (assign, ":total_gain", 0),
    (party_get_num_companion_stacks, ":num_stacks",":party"),
    (try_for_range, ":i_stack", 0, ":num_stacks"),
      (party_stack_get_troop_id,     ":stack_troop",":party",":i_stack"),
      (neg|troop_is_hero, ":stack_troop"),
      (party_stack_get_size, ":stack_size",":party",":i_stack"),
      (store_character_level, ":level", ":stack_troop"),
      (store_mul, ":gain", ":level", ":level"),
      (store_mul, ":stack_gain", ":gain", ":stack_size"),
      (val_add, ":total_gain", ":stack_gain"),
    (try_end),
    (val_mul, ":total_gain", ":num_player_party_shares"),
    (val_div, ":total_gain", ":num_total_shares"),
	
	(val_div, ":total_gain", 100),
	
	(val_max, ":total_gain", 20),
	(val_sub, ":total_gain", 20),
	(assign, ":special_item_in_loot", 0),
	(store_mul, ":upper_range", "$num_unique_items_given", 250),
	(val_add, ":upper_range", 2000),
	(store_random_in_range, ":r", 0, ":upper_range"),
#	(assign, reg40, ":r"),
#	(assign, reg41, ":total_gain"),
#	(display_message, "str_debug_string_1"),
	(try_begin),
		(lt, ":r", ":total_gain"),
		(store_random_in_range, ":r", 0, 17),

		# First special item is always the one you can use the best
		(try_begin),
			(eq, "$num_unique_items_given", 0),
			(store_proficiency_level, ":one_handed_skill", "trp_player", proficiency_one_handed),
	  		(store_proficiency_level, ":two_handed_skill", "trp_player", proficiency_two_handed),
	  		(store_proficiency_level, ":polearm_skill", "trp_player", proficiency_polearm),
			(try_begin),
			  (ge, ":polearm_skill", ":one_handed_skill"),
			  (ge, ":polearm_skill", ":two_handed_skill"),
			  (assign, ":r", 2), #kushana
			(else_try),
			  (ge, ":two_handed_skill", ":one_handed_skill"),
			  (assign, ":r", 8), #durendal
			(else_try),
			  (assign, ":r", 9), #caliburn
			(try_end),
		(try_end),
		
		(try_begin),
		  (eq, ":r", 0),
		  (eq, "$given_quicksilver", 0),
		  (assign, "$given_quicksilver", 1),
		  (assign, ":special_item_in_loot", "itm_shuangci"),
		(else_try),
		  (eq, ":r", 1),
		  (eq, "$given_avencior", 0),
		  (assign, "$given_avencior", 1),
		  (assign, ":special_item_in_loot", "itm_shuangxi"),
		(else_try),
		  (eq, ":r", 2),
		  (eq, "$given_kushana", 0),
		  (assign, "$given_kushana", 1),
		  (assign, ":special_item_in_loot", "itm_tiejispear"),
		(else_try),
		  (eq, ":r", 3),
		  (eq, "$given_midnight", 0),
		  (assign, "$given_midnight", 1),
		  (assign, ":special_item_in_loot", "itm_zyshen"),
		(else_try),
		  (eq, ":r", 4),
		  (eq, "$given_curtana", 0),
		  (assign, "$given_curtana", 1),
		  (assign, ":special_item_in_loot", "itm_mcshen"),
		(else_try),
		  (eq, ":r", 5),
		  (eq, "$given_tannhauser", 0),
		  (assign, "$given_tannshauser", 1),
		  (assign, ":special_item_in_loot", "itm_gyshen"),
		(else_try),
		  (eq, ":r", 6),
		  (eq, "$given_talhoffer", 0),
		  (assign, "$given_talhoffer", 1),
		  (assign, ":special_item_in_loot", "itm_yuitian"),
		(else_try),
		  (eq, ":r", 7),
		  (eq, "$given_joyeux", 0),
		  (assign, "$given_joyeux", 1),
		  (assign, ":special_item_in_loot", "itm_yitiansword"),
		(else_try),
		  (eq, ":r", 8),
		  (eq, "$given_durendal", 0),
		  (assign, "$given_durendal", 1),
		  (assign, ":special_item_in_loot", "itm_qinglongbardiche"),
		(else_try),
		  (eq, ":r", 9),
		  (eq, "$given_caliburn", 0),
		  (assign, "$given_caliburn", 1),
		  (assign, ":special_item_in_loot", "itm_fangtianhalberd"),
		(else_try),
		  (eq, ":r", 10),
		  (eq, "$given_jarl", 0),
		  (assign, "$given_jarl", 1),
		  (assign, ":special_item_in_loot", "itm_silverlance"),
		(else_try),
		  (eq, ":r", 11),
		  (eq, "$given_ducalis", 0),
		  (assign, "$given_ducalis", 1),
		  (assign, ":special_item_in_loot", "itm_steelspear"),
		(else_try),
		  (eq, ":r", 12),
		  (eq, "$given_clontarf", 0),
		  (assign, "$given_clontarf", 1),
		  (assign, ":special_item_in_loot", "itm_yinjia"),
		(else_try),
		  (eq, ":r", 13),
		  (eq, "$given_caithness", 0),
		  (assign, "$given_caithness", 1),
		  (assign, ":special_item_in_loot", "itm_yinxie"),
		(else_try),
		  (eq, ":r", 14),
		  (eq, "$given_griffin_sallet", 0),
		  (assign, "$given_griffin_sallet", 1),
		  (assign, ":special_item_in_loot", "itm_jinxie"),
		(else_try),
		  (eq, ":r", 15),
		  (eq, "$given_antlered_helm", 0),
		  (assign, "$given_antlered_helm", 1),
		  (assign, ":special_item_in_loot", "itm_jinbian"),
		(else_try),
		  (eq, ":r", 16),
		  (eq, "$given_black_dragon_helm", 0),
		  (assign, "$given_black_dragon_helm", 1),
		  (assign, ":special_item_in_loot", "itm_hutou"),
		(try_end),	
	(try_end),
	
	(try_begin),
	  (neq, ":special_item_in_loot", 0),
	  (val_add, "$num_unique_items_given", 1),
	  (troop_ensure_inventory_space, "trp_temp_troop", 5),
	  (troop_add_item, "trp_temp_troop", ":special_item_in_loot", 0),
	  (assign, reg0, 1),
	(else_try),
	  (assign, reg0, 0),
	(try_end),
]),


("item_is_lootable", [
	(store_script_param_1, ":item"),
	
	(try_begin),
		(this_or_next|eq, ":item", "itm_knife"),
		(this_or_next|eq, ":item", "itm_dagger"),
		(this_or_next|eq, ":item", "itm_padded_leather"),
		(this_or_next|eq, ":item", "itm_nomad_vest"),
		(this_or_next|eq, ":item", "itm_baotou"),
		(this_or_next|eq, ":item", "itm_guanjin"),
		(this_or_next|eq, ":item", "itm_fur_hat"),
		(this_or_next|eq, ":item", "itm_caoshoes"),
		(this_or_next|eq, ":item", "itm_bushoes"),
		(this_or_next|eq, ":item", "itm_wrapping_boots"),
		(this_or_next|eq, ":item", "itm_wooden_shield"),
		(this_or_next|eq, ":item", "itm_stones"),
		(this_or_next|eq, ":item", "itm_sumpter_horse"),
		(is_between, ":item", "itm_quest_items_start", "itm_quest_items_end"), # don't rob quest items
		(assign, reg0, 0),
	(else_try),
		(assign, reg0, 1),
	(try_end),	
]),
#ji suan cheng chi
("chengchi",[
(try_begin),
(try_for_range,reg(9),towns_begin,towns_end),
(store_faction_of_party,reg(10),reg(9)), 
(eq,reg(10),"fac_kingdom_caowei"), 
(val_add,"$wei_chengchi",1), 
(else_try),
(eq,reg(10),"fac_kingdom_shuhan"), 
(val_add,"$shu_chengchi",1), 
(else_try),
(eq,reg(10),"fac_kingdom_wu"), 
(val_add,"$wu_chengchi",1), 
(try_end),
(val_mul,"$wei_guoli_raise", "$wei_chengchi"),
(val_mul,"$wu_guoli_raise", "$wu_chengchi"),
(val_mul,"$shu_guoli_raise", "$shu_chengchi")]),	

("wounded",
   [
      (store_script_param_1, ":party"), 
      (party_get_num_companion_stacks, ":num_stacks",":party"),
      (assign, reg0, 0),
      (try_for_range, ":i_stack", 0, ":num_stacks"),
        (party_stack_get_troop_id,     ":stack_troop",":party",":i_stack"),
        (neg|troop_is_hero, ":stack_troop"),
        (party_stack_get_size,         ":stack_size",":party",":i_stack"),
        (party_stack_get_num_wounded, ":num_wounded",":party",":i_stack"),
        (val_sub, ":stack_size", ":num_wounded"),
        (val_add, reg0, ":stack_size"),
      (try_end),
    ]),
("remove_war_party",
  [
   (try_for_parties,":party_no"),
     (party_get_template_id,":temp_id",":party_no"),
     (try_begin),
       (this_or_next|eq,":temp_id","pt_wei_war_party"),
       (this_or_next|eq,":temp_id","pt_shu_war_party"),
       (eq,":temp_id","pt_wu_war_party"),
       (remove_party,":party_no"),##
     (try_end),   
   (try_end),   
  ]
),

("move_party",[
(try_for_parties,reg11),
(party_get_template_id,reg12,reg11),
(store_faction_of_party,"$party_faction",reg11),
(try_begin),
(eq,"$party_faction","fac_kingdom_caowei"),
(neq,reg12,"pt_wei_war_party"),
(neq,reg12,"pt_wei_caravan"),
(neq,reg12,"pt_wei_gongcheng"),
(assign,"$move_party",reg12),
(else_try),
(eq,"$party_faction","fac_kingdom_shuhan"),
(neq,reg12,"pt_shu_war_party"),
(neq,reg12,"pt_shu_caravan"),
(neq,reg12,"pt_shu_gongcheng"),
(assign,"$move_party",reg12),
(else_try),
(eq,"$party_faction","fac_kingdom_wu"),
(neq,reg12,"pt_wu_war_party"),
(neq,reg12,"pt_wu_caravan"),
(neq,reg12,"pt_wu_gongcheng"),
(assign,"$move_party",reg12),
(try_end),
(party_set_ai_behavior,"$move_party",ai_bhvr_patrol_party),        
(party_set_ai_object,"$move_party","p_castle_4")]),



  #script_spawn_party_at_random_town_if_below_limit:
  # This script checks if number of parties 
  # of specified template is less than limit,
  # If so, it selects a random town in range [towns_begin, towns_end)
  # and spawns a new party there.
  # INPUT: 
  # $pin_party_template: given_party_template
  # $pin_limit: limit value

  #OUTPUT:
  # $pout_party: id of the spawned party
  # $pout_town: id of the selected faction town
  # Note:
  # This script may return false if number of parties 
  # of specified template is greater or equal to limit,
  # or if party can not be spawned.
  ("spawn_party_at_random_town_if_below_limit",
   [
       (store_num_parties_of_template, reg(22), "$pin_party_template"),
       (lt,reg(22),"$pin_limit"), #check if we are below limit.
       (call_script,"script_select_random_spawn_point"),
       (set_spawn_radius,1),
       (spawn_around_party,"$pout_town","$pin_party_template"),
       (assign, "$pout_party", reg(0)),
    ]),

  #script_spawn_party_at_faction_town_if_below_limit:
  # This script checks if number of parties 
  # of specified template is less than limit,
  # If so, it selects a random town in range [towns_begin, towns_end)
  # such that faction of the town is equal to given_faction
  # and spawns a new party there.
  # INPUT: 
  # $pin_faction: given_faction
  # $pin_party_template: given_party_template
  # $pin_limit: limit value

  #OUTPUT:
  # $pout_party: id of the spawned party
  # $pout_town: id of the selected faction town
  # Note:
  # This script may return false if number of parties 
  # of specified template is greater or equal to limit,
  # or if party can not be spawned.
  ("spawn_party_at_faction_town_if_below_limit",
   [
       (store_num_parties_of_template, reg(22), "$pin_party_template"),
       (lt,reg(22),"$pin_limit"), #check if we are below limit.
       (call_script,"script_select_faction_spawn_point"),
       (set_spawn_radius,1),
       (spawn_around_party,"$pout_town","$pin_party_template"),
       (assign, "$pout_party", reg(0)),
    ]),

	  #script_calculate_party_shares:
  # INPUT: 
  # param1: Allied Party-id
  # Returns number of player party shares in reg0
  # Returns number of allied party shares in reg1

  ("calculate_party_shares",
   [
      (store_script_param_1, ":allied_party"), #Party_id
      
      (assign, ":num_player_party_shares",10),
      # Add shares for player's party
      (party_get_num_companion_stacks, ":num_stacks","p_main_party"),
      (try_for_range, ":i_stack", 1, ":num_stacks"),
        (party_stack_get_troop_id,     ":stack_troop","p_main_party",":i_stack"),
        (try_begin),
          (neg|troop_is_hero, ":stack_troop"),
          (party_stack_get_size, ":stack_size","p_main_party",":i_stack"),
          (val_add, ":num_player_party_shares", ":stack_size"),
        (else_try),
          (val_add, ":num_player_party_shares", 10),
        (try_end),
      (try_end),

      (assign, ":num_ally_shares",0),
      # Now add shares for the allied party
      (try_begin),
        (gt, ":allied_party", 0),
        (assign, ":num_ally_shares", 10),
        (party_get_num_companion_stacks, ":num_stacks",":allied_party"),
        (try_for_range, ":i_stack", 1, ":num_stacks"),
          (party_stack_get_troop_id,     ":stack_troop",":allied_party",":i_stack"),
          (try_begin),
            (neg|troop_is_hero, ":stack_troop"),
            (party_stack_get_size, ":stack_size",":allied_party",":i_stack"),
            (val_add, ":num_ally_shares", ":stack_size"),
          (else_try),
            (val_add, ":num_ally_shares", 10),
          (try_end),
        (try_end),
      (try_end),

      (assign, reg0, ":num_player_party_shares"),
      (assign, reg1, ":num_ally_shares"),
      
    ]),
  ("select_random_spawn_point",
   [
      (assign, reg20, spawn_points_end),
      (val_sub,reg20, spawn_points_begin),
      (store_random, reg(21), reg20),
      (val_add,reg(21), spawn_points_begin),
      (assign, "$pout_town", reg(21)),
    ]),
  ("select_faction_spawn_point",
   [
      # First count num matching spawn points 
      (assign, reg(24), 0),
      (try_for_range,reg(25), spawn_points_begin, spawn_points_end),
        (store_faction_of_party, reg(23), reg(25)),
        (eq, reg(23), "$pin_faction"),
        (val_add, reg(24), 1),
      (end_try,0),
       # reg4 now holds num towns of this faction.
      (gt, reg(24), 0), #Fail if there are no towns
      (store_random, reg(26), reg(24)),
      
      (assign, reg(24), 0), # reg24 = num points of this faction.
      (try_for_range,reg(25), spawn_points_begin, spawn_points_end),
        (store_faction_of_party, reg(23), reg(25)),
        (eq, reg(23), "$pin_faction"),
        (try_begin,0),
          (eq, reg(24), reg(26)),
          (assign, "$pout_town", reg(25)), # result is this town
        (end_try,0),
        (val_add, reg(24), 1),
      (end_try,0),
    ]),
  #script_select_faction_town:
  # This script selects a random town in range [towns_begin, towns_end)
  # such that faction of the town is equal to given_faction
  # INPUT: 
  # $pin_faction: given_faction

  #OUTPUT:
  # This script may return false if there is no matching town.
  # $pout_town: id of the selected random town
  ("select_faction_town",
   [
      # First count num matching spawn points 
      (assign, reg(24), 0),
      (try_for_range,reg(25), towns_begin, towns_end),
        (store_faction_of_party, reg(23), reg(25)),
        (eq, reg(23), "$pin_faction"),
        (val_add, reg(24), 1),
      (end_try,0),
       # reg4 now holds num towns of this faction.
      (gt, reg(24), 0), #Fail if there are no towns
      (store_random, reg(26), reg(24)),
      
      (assign, reg(24), 0), # reg24 = num points of this faction.
      (try_for_range,reg(25), towns_begin, towns_end),
        (store_faction_of_party, reg(23), reg(25)),
        (eq, reg(23), "$pin_faction"),
        (try_begin,0),
          (eq, reg(24), reg(26)),
          (assign, "$pout_town", reg(25)), # result is this town
        (end_try,0),
        (val_add, reg(24), 1),
      (end_try,0),
    ]),

	
#sango 894 scripts
	("cf_is_troop_same_faction",[
		(store_script_param,":trp_id",1),
		(store_script_param,":fac_id",2),
		(store_troop_faction,":trp_fac",":trp_id"),
		(eq,":trp_fac",":fac_id"),
	]),
	
# change from 901	
  #script_start_quest
  # INPUT: arg1 = quest_no, arg2 = giver_troop_no, s2 = description_text
  # OUTPUT: none
  ("start_quest",
    [(store_script_param, ":quest_no", 1),
     (store_script_param, ":giver_troop_no", 2),
     (try_begin),
       (is_between, ":giver_troop_no", kingdom_heroes_begin, kingdom_heroes_end),
       (str_store_troop_name_link, s62, ":giver_troop_no"),
     (else_try),
       (str_store_troop_name, s62, ":giver_troop_no"),
     (try_end),
     (str_store_string, s63, "@Given by: {s62}"),
     (str_store_date, s60, 0),
     (str_store_string, s60, "@Given on: {s60}"),
     (add_quest_note_from_sreg, ":quest_no", 1, s60, 0),
     (add_quest_note_from_sreg, ":quest_no", 2, s63, 0),
     (add_quest_note_from_sreg, ":quest_no", 3, s2, 0),

     (try_begin),
       (quest_slot_ge, ":quest_no", slot_quest_expiration_days, 1),
       (quest_get_slot, reg0, ":quest_no", slot_quest_expiration_days),
       (add_quest_note_from_sreg, ":quest_no", 5, "@You have {reg0} days to finish this quest.", 0),
     (try_end),

     #Adding dont_give_again_for_days value
     (try_begin),
       (quest_slot_ge, ":quest_no", slot_quest_dont_give_again_period, 1),
       (quest_get_slot, ":dont_give_again_period", ":quest_no", slot_quest_dont_give_again_period),
       (quest_set_slot, ":quest_no", slot_quest_dont_give_again_remaining_days, ":dont_give_again_period"),
     (try_end),
     (start_quest, ":quest_no"),
     (display_message, "str_quest_log_updated"),
     ]),

  #script_complete_quest
  # INPUT: arg1 = quest_no
  # OUTPUT: none
  ("complete_quest",
    [(store_script_param, ":quest_no", 1),
     (complete_quest, ":quest_no"),
     (quest_get_slot, ":quest_giver_troop", ":quest_no", slot_quest_giver_troop),
     (str_store_troop_name, s59, ":quest_giver_troop"),
     (add_quest_note_from_sreg, ":quest_no", 5, "@This quest has been concluded. Talk to {s59} to finish it.", 0),
     ]),

  #script_succeed_quest
  # INPUT: arg1 = quest_no
  # OUTPUT: none
  ("succeed_quest",
    [(store_script_param, ":quest_no", 1),
     (succeed_quest, ":quest_no"),
     (quest_get_slot, ":quest_giver_troop", ":quest_no", slot_quest_giver_troop),
     (str_store_troop_name, s59, ":quest_giver_troop"),
     (add_quest_note_from_sreg, ":quest_no", 5, "@This quest has been successfully completed. Talk to {s59} to claim your reward.", 0),
     ]),

  #script_fail_quest
  # INPUT: arg1 = quest_no
  # OUTPUT: none
  ("fail_quest",
    [(store_script_param, ":quest_no", 1),
     (fail_quest, ":quest_no"),
     (quest_get_slot, ":quest_giver_troop", ":quest_no", slot_quest_giver_troop),
     (str_store_troop_name, s59, ":quest_giver_troop"),
     (add_quest_note_from_sreg, ":quest_no", 5, "@This quest has failed. Talk to {s59} to explain the situation.", 0),
     ]),

  #script_report_quest_troop_positions
  # INPUT: arg1 = quest_no, arg2 = troop_no
  # OUTPUT: none
  ("report_quest_troop_positions",
    [(store_script_param, ":quest_no", 1),
     (store_script_param, ":troop_no", 2),
     (try_begin),
       (call_script, "script_get_information_about_troops_position", ":troop_no", 1),
       (str_store_string, s5, "@At the time quest was given:^{s1}"),
       (add_quest_note_from_sreg, ":quest_no", 4, s5, 1),
     (try_end),
     ]),
   
  #script_end_quest
  # INPUT: arg1 = quest_no
  # OUTPUT: none
  ("end_quest",
    [(store_script_param, ":quest_no", 1),
     (str_clear, s1),
     (add_quest_note_from_sreg, ":quest_no", 1, s1, 0),
     (add_quest_note_from_sreg, ":quest_no", 2, s1, 0),
     (add_quest_note_from_sreg, ":quest_no", 3, s1, 0),
     (add_quest_note_from_sreg, ":quest_no", 4, s1, 0),
     (add_quest_note_from_sreg, ":quest_no", 5, s1, 0),
     (complete_quest, ":quest_no"),
#     (try_begin),
#       (is_between, ":quest_no", mayor_quests_begin, mayor_quests_end),
#       (assign, "$merchant_quest_last_offerer", -1),
#       (assign, "$merchant_offered_quest", -1),
     (try_end),
      ]),
	  
  # script_get_random_quest
  # Input: arg1 = troop_no (of the troop in conversation), arg2 = min_importance (of the quest)
  # Output: reg0 = quest_no (the slots of the quest will be filled after calling this script)
  ("get_random_quest",
    [
      (store_script_param_1, ":giver_troop"),
      
      (store_character_level, ":player_level", "trp_player"),
      (store_troop_faction, ":giver_faction_no", ":giver_troop"),
      
      (troop_get_slot, ":giver_party_no", ":giver_troop", slot_troop_leaded_party),
      (assign, ":giver_center_no", -1),
      (try_begin),
        (gt, ":giver_party_no", 0),
        (party_get_attached_to, ":giver_center_no", ":giver_party_no"),
      (else_try),
        (is_between, "$g_encountered_party", centers_begin, centers_end),
        (assign, ":giver_center_no", "$g_encountered_party"),
      (try_end),
      
      (try_begin),
        (troop_slot_eq, ":giver_troop", slot_troop_occupation, slto_kingdom_hero),
        (try_begin),
          (ge, "$g_talk_troop_faction_relation", 0),
          (assign, ":quests_begin", lord_quests_begin),
          (assign, ":quests_end", lord_quests_end),
#        (else_try),
#          (assign, ":quests_begin", enemy_lord_quests_begin),
#          (assign, ":quests_end", enemy_lord_quests_end),
        (try_end),
#      (else_try),
#        (is_between, ":giver_troop", village_elders_begin, village_elders_end),
#        (assign, ":quests_begin", village_elder_quests_begin),
#        (assign, ":quests_end", village_elder_quests_end),
#      (else_try),
#        (is_between, ":giver_troop", mayors_begin, mayors_end),
#        (assign, ":quests_begin", mayor_quests_begin),
#        (assign, ":quests_end", mayor_quests_end),

      (try_end),
      
      (assign, ":result", -1),
      (try_for_range, ":unused", 0, 20), #Repeat trial twenty times
        (eq, ":result", -1),
        (assign, ":quest_target_troop", -1),
        (assign, ":quest_target_center", -1),
        (assign, ":quest_target_faction", -1),
        (assign, ":quest_object_troop", -1),
        (assign, ":quest_target_troop_is_prisoner", -1),
        (assign, ":quest_object_center", -1),
        (assign, ":quest_target_party", -1),
        (assign, ":quest_target_party_template", -1),
        (assign, ":quest_target_amount", -1),
        (assign, ":quest_target_dna", -1),
        (assign, ":quest_target_item", -1),
        (assign, ":quest_importance", 1),
        (assign, ":quest_xp_reward", 0),
        (assign, ":quest_gold_reward", 0),
        (assign, ":quest_convince_value", 0),
        (assign, ":quest_expiration_days", 0),
        (assign, ":quest_dont_give_again_period", 0),

        (store_random_in_range,":quest_no",":quests_begin",":quests_end"),
#TODO: Remove this when test is done
#        (assign, ":quest_no", "qst_lend_companion"),
#TODO: Remove this when test is done end
        (neg|check_quest_active,":quest_no"),
        (neg|quest_slot_ge, ":quest_no", slot_quest_dont_give_again_remaining_days, 1),
        (try_begin),
          # Village Elder quests
#          (eq, ":quest_no", "qst_deliver_grain"),
#          (try_begin),
#            (is_between, ":giver_center_no", villages_begin, villages_end),
#            #The quest giver is the village elder
#            (call_script, "script_get_troop_item_amount", ":giver_troop", "itm_grain"),
#            (eq, reg0, 0),
#            (neg|party_slot_ge, ":giver_center_no", slot_town_prosperity, 40),
#            (assign, ":quest_target_center", ":giver_center_no"),
#            (store_random_in_range, ":quest_target_amount", 4, 8),
#            (assign, ":quest_expiration_days", 30),
#            (assign, ":quest_dont_give_again_period", 20),
#            (assign, ":result", ":quest_no"),
#          (try_end),
#        (else_try),
#          (eq, ":quest_no", "qst_deliver_cattle"),
#          (try_begin),
#            (is_between, ":giver_center_no", villages_begin, villages_end),
#            #The quest giver is the village elder
#            (party_get_slot, ":num_cattle", ":giver_center_no", slot_village_number_of_cattle),
#            (lt, ":num_cattle", 50),
#            (assign, ":quest_target_center", ":giver_center_no"),
#            (store_random_in_range, ":quest_target_amount", 5, 10),
#            (assign, ":quest_expiration_days", 30),
#            (assign, ":quest_dont_give_again_period", 20),
#            (assign, ":result", ":quest_no"),
#          (try_end),
#        (else_try),
#          # Mayor quests
#          (eq, ":quest_no", "qst_escort_merchant_caravan"),
#          (is_between, ":giver_center_no", centers_begin, centers_end),
#          (store_random_party_in_range, ":quest_target_center", towns_begin, towns_end),
#          (store_distance_to_party_from_party, ":dist", ":giver_center_no",":quest_target_center"),
#          (assign, ":quest_gold_reward", ":dist"),
#          (val_add, ":quest_gold_reward", 25),
#          (val_mul, ":quest_gold_reward", 25),
#          (val_div, ":quest_gold_reward", 20),
#          (store_random_in_range, ":quest_target_amount", 6, 12),
#          (assign, "$escort_merchant_caravan_mode", 0),
#          (assign, ":result", ":quest_no"),
#        (else_try),
          (eq, ":quest_no", "qst_deliver_wine"),
          (is_between, ":giver_center_no", centers_begin, centers_end),
          (store_random_party_in_range, ":quest_target_center", towns_begin, towns_end),
          (store_random_in_range, ":random_no", 0, 2),
          (try_begin),
            (eq, ":random_no", 0),
            (assign, ":quest_target_item", "itm_quest_wine"),
          (else_try),
            (assign, ":quest_target_item", "itm_quest_ale"),
          (try_end),
          (store_random_in_range, ":quest_target_amount", 6, 12),
          (store_distance_to_party_from_party, ":dist", ":giver_center_no",":quest_target_center"),
          (assign, ":quest_gold_reward", ":dist"),
          (val_add, ":quest_gold_reward", 2),
          (assign, ":multiplier", 5),
          (val_add, ":multiplier", ":quest_target_amount"),
          (val_mul, ":quest_gold_reward", ":multiplier"),
          (val_div, ":quest_gold_reward", 100),
          (val_mul, ":quest_gold_reward", 10),
          (store_item_value,"$qst_deliver_wine_debt",":quest_target_item"),
          (val_mul,"$qst_deliver_wine_debt",":quest_target_amount"),
          (val_mul,"$qst_deliver_wine_debt", 6),
          (val_div,"$qst_deliver_wine_debt",5),
          (assign, ":quest_expiration_days", 7),
          (assign, ":quest_dont_give_again_period", 20),
          (assign, ":result", ":quest_no"),
        (else_try),
          (eq, ":quest_no", "qst_troublesome_bandits"),
          (is_between, ":giver_center_no", centers_begin, centers_end),
          (store_character_level, ":quest_gold_reward", "trp_player"),
          (val_add, ":quest_gold_reward", 20),
          (val_mul, ":quest_gold_reward", 35),
          (val_div, ":quest_gold_reward",100),
          (val_mul, ":quest_gold_reward", 10),
          (assign, ":quest_expiration_days", 30),
          (assign, ":quest_dont_give_again_period", 30),
          (assign, ":result", ":quest_no"),
        (else_try),
          (eq, ":quest_no", "qst_kidnapped_girl"),
          (is_between, ":giver_center_no", centers_begin, centers_end),
          (store_random_in_range, ":quest_target_center", villages_begin, villages_end),
          (store_character_level, ":quest_target_amount"),
          (val_add, ":quest_target_amount", 15),
          (store_distance_to_party_from_party, ":dist", ":giver_center_no", ":quest_target_center"),
          (val_add, ":dist", 15),
          (val_mul, ":dist", 2),
          (val_mul, ":quest_target_amount", ":dist"),
          (val_div, ":quest_target_amount",100),
          (val_mul, ":quest_target_amount",10),
          (assign, ":quest_gold_reward", ":quest_target_amount"),
          (val_div, ":quest_gold_reward", 40),
          (val_mul, ":quest_gold_reward", 10),
          (assign, ":quest_dont_give_again_period", 30),
          (assign, ":result", ":quest_no"),
#        (else_try),
#          (eq, ":quest_no", "qst_move_cattle_herd"),
#          (is_between, ":giver_center_no", centers_begin, centers_end),
#          (call_script, "script_cf_select_random_town_at_peace_with_faction", ":giver_faction_no"),
#          (assign, ":quest_target_center", reg0),
#          (store_distance_to_party_from_party, ":dist",":giver_center_no",":quest_target_center"),
#          (assign, ":quest_gold_reward", ":dist"),
#          (val_add, ":quest_gold_reward", 25),
#          (val_mul, ":quest_gold_reward", 50),
#          (val_div, ":quest_gold_reward", 20),
#          (assign, ":quest_expiration_days", 20),
#          (assign, ":quest_dont_give_again_period", 20),
#          (assign, ":result", ":quest_no"),
#        (else_try),
#          (eq, ":quest_no", "qst_lend_surgeon"),
#          (try_begin),
#            (eq, "$g_defending_against_siege", 0),#Skip if the center is under siege (because of resting)
#            (assign, ":max_surgery_level", 0),
#            (assign, ":best_surgeon", -1),
#            (party_get_num_companion_stacks, ":num_stacks","p_main_party"),
#            (try_for_range, ":i_stack", 1, ":num_stacks"),
#              (party_stack_get_troop_id, ":stack_troop","p_main_party",":i_stack"),
#              (troop_is_hero, ":stack_troop"),
#              (store_skill_level, ":cur_surgery_skill", skl_surgery, ":stack_troop"),
#              (gt, ":cur_surgery_skill", ":max_surgery_level"),
#              (assign, ":max_surgery_level", ":cur_surgery_skill"),
#              (assign, ":best_surgeon", ":stack_troop"),
#            (try_end),
#            
#            (store_character_level, ":cur_level", "trp_player"),
#            (assign, ":required_skill", 5),
#            (val_div, ":cur_level", 10),
#            (val_add, ":required_skill", ":cur_level"),
#            (ge, ":max_surgery_level", ":required_skill"), #Skip if party skill level is less than the required value
#            
#            (assign, ":quest_object_troop", ":best_surgeon"),
#            (assign, ":quest_importance", 1),
#            (assign, ":quest_xp_reward", 10),
#            (assign, ":quest_gold_reward", 10),
#            (assign, ":quest_dont_give_again_period", 50),
#            (assign, ":result", ":quest_no"),
#          (try_end),
          # Lord Quests
        (else_try),
          (eq, ":quest_no", "qst_deliver_message"),
          (try_begin),
            (lt, ":player_level", 20),
            (call_script, "script_cf_get_random_lord_in_a_center_with_faction", ":giver_faction_no"),#Can fail
            (assign, ":cur_target_troop", reg0),
            (neq, ":cur_target_troop", ":giver_troop"),#Skip himself
            (call_script, "script_get_troop_attached_party", ":cur_target_troop"),
            (assign, ":cur_target_center", reg0),#cur_target_center will definitely be a valid center
            (neq,":giver_center_no", ":cur_target_center"),#Skip current center

            (assign, ":quest_target_center", ":cur_target_center"),
            (assign, ":quest_target_troop", ":cur_target_troop"),
            (assign, ":quest_xp_reward", 30),
            (assign, ":quest_gold_reward", 40),
            (assign, ":result", ":quest_no"),
      
            (assign, ":quest_expiration_days", 30),
          (try_end),
#        (else_try),
#          (eq, ":quest_no", "qst_deliver_message_to_enemy_lord"),
#          (try_begin),
#            (is_between, ":player_level", 5,25),
#            (call_script, "script_cf_get_random_lord_from_another_faction_in_a_center", ":giver_faction_no"),#Can fail
#            (assign, ":cur_target_troop", reg0),
#            (call_script, "script_get_troop_attached_party", ":cur_target_troop"),
#            (assign, ":quest_target_center", reg0),#quest_target_center will definitely be a valid center
#            (assign, ":quest_target_troop", ":cur_target_troop"),
#            (assign, ":quest_importance", 1),
#            (assign, ":quest_xp_reward", 200),
#            (assign, ":quest_gold_reward", 0),
#            (assign, ":result", ":quest_no"),
#            (assign, ":quest_expiration_days", 40),
#          (try_end),
#        (else_try),
#          (eq, ":quest_no", "qst_deal_with_bandits_at_lords_village"),
#          (try_begin),
#            (assign, ":end_cond", villages_end),
#            (assign, ":cur_target_center", -1),
#            (try_for_range, ":cur_village", villages_begin, ":end_cond"),
#              (party_slot_eq, ":cur_village", slot_town_lord, ":giver_troop"),
#              (party_slot_eq, ":cur_village", slot_village_infested_by_bandits, 1),
#              (assign, ":cur_target_center", ":cur_village"),
#              (assign, ":end_cond", 0),
#            (try_end),
#            (ge, ":cur_target_center", 0),
#            (neg|check_quest_active, "qst_eliminate_bandits_infesting_village"),
#            (assign, ":quest_target_center", ":cur_target_center"),
#            (assign, ":result", ":quest_no"),
#            (assign, ":quest_expiration_days", 30),
#          (try_end),
        (else_try),
          (eq, ":quest_no", "qst_raise_troops"),
          (try_begin),
            (store_random_in_range, ":quest_target_amount", 5, 8),

            (party_get_free_companions_capacity, ":free_capacity", "p_main_party"),
            (le, ":quest_target_amount", ":free_capacity"),
            (store_character_level, ":cur_level"),
            (faction_get_slot, ":quest_object_troop", ":giver_faction_no", slot_faction_tier_1_troop),
            (store_random_in_range, ":level_up", 20, 40),
            (val_add, ":level_up", ":cur_level"),
            (val_div, ":level_up", 10),

            (store_mul, ":quest_gold_reward", ":quest_target_amount", 10),

            (assign, ":quest_target_troop", ":quest_object_troop"),
            (try_for_range, ":unused", 0, ":level_up"),
              (troop_get_upgrade_troop, ":level_up_troop", ":quest_target_troop", 0),
              (gt, ":level_up_troop", 0),
              (assign, ":quest_target_troop", ":level_up_troop"),
              (val_mul, ":quest_gold_reward", ":quest_gold_reward", 7),
              (val_div, ":quest_gold_reward", ":quest_gold_reward", 4),
            (try_end),
            (assign, ":quest_xp_reward", ":quest_gold_reward"),
            (val_mul, ":quest_xp_reward", 3),
            (val_div, ":quest_xp_reward", 10),
            (assign, ":result", ":quest_no"),
            (assign, ":quest_expiration_days", 120),
            (assign, ":quest_dont_give_again_period", 15),
          (try_end),
 #       (else_try),
 #         (eq, ":quest_no", "qst_collect_taxes"),
 #         (try_begin),
 #           (call_script, "script_cf_troop_get_random_leaded_town_or_village_except_center", ":giver_troop", ":giver_center_no"),
 #           (assign, ":quest_target_center", reg0),
 #           (assign, ":quest_importance", 1),
 #           (assign, ":quest_gold_reward", 0),
 #           (assign, ":quest_xp_reward", 100),
 #           (assign, ":result", ":quest_no"),
 #           (assign, ":quest_expiration_days", 50),
 #           (assign, ":quest_dont_give_again_period", 20),
 #         (try_end),
 #       (else_try),
 #         (eq, ":quest_no", "qst_hunt_down_fugitive"),
 #         (try_begin),
 #           (call_script, "script_cf_select_random_village_with_faction", ":giver_faction_no"),
 #           (assign, ":quest_target_center", reg0),
 #           (store_random_in_range, ":quest_target_dna", 0, 1000000),
 #           #TODO: Change importance and xp reward. leave gold reward as zero (used within quest)
 #           (assign, ":quest_importance", 1),
 #           (val_mul, ":quest_gold_reward", 0),
 #           (assign, ":quest_xp_reward", 100),
 #           (assign, ":result", ":quest_no"),
 #           (assign, ":quest_expiration_days", 30),
 #           (assign, ":quest_dont_give_again_period", 3),
 #         (try_end),

 #       (else_try),
 #         (eq, ":quest_no", "qst_kill_local_merchant"),
 #         (try_begin),
 #           (gt, ":player_level", 5),
 #           (party_slot_eq, ":giver_center_no", slot_party_type, spt_town),
 #           (assign, ":quest_importance", 1),
 #           (assign, ":quest_xp_reward", 300),
 #           (assign, ":quest_gold_reward", 1000),
 #           (assign, ":result", ":quest_no"),
 #           (assign, ":quest_expiration_days", 10),
 #           (assign, ":quest_dont_give_again_period", 30),
 #         (try_end),
 #       (else_try),
 #         (eq, ":quest_no", "qst_bring_back_runaway_serfs"),
 #         (try_begin),
 #           (ge, ":player_level", 5),
 #           (gt, ":giver_center_no", 0),#Skip if lord is outside the center
 #           (eq, "$g_defending_against_siege", 0),#Skip if the center is under siege (because of resting)      
 #           (assign, ":cur_object_center", -1),
 #           (try_for_range, ":cur_village", villages_begin, villages_end),
 #             (party_slot_eq, ":cur_village", slot_town_lord, ":giver_troop"),
 #             (store_distance_to_party_from_party, ":dist", ":cur_village", ":giver_center_no"),
 #             (lt, ":dist", 25),
 #             (assign, ":cur_object_center", ":cur_village"),
 #           (try_end),
 #           (ge, ":cur_object_center", 0),#Skip if the quest giver is not the owner of any villages around the center
 #           (call_script, "script_cf_select_random_town_with_faction", ":giver_faction_no"),
 #           (assign, ":cur_target_center", reg0),
 #           (neq, ":cur_target_center", ":giver_center_no"),#Skip current center
 #           (store_distance_to_party_from_party, ":dist", ":cur_target_center", ":giver_center_no"),
 #           (ge, ":dist", 20),
 #           (assign, ":quest_target_party_template", "pt_runaway_serfs"),
 #           (assign, ":quest_object_center", ":cur_object_center"),
 #           (assign, ":quest_target_center", ":cur_target_center"),
 #           (assign, ":quest_importance", 1),
 #           (assign, ":quest_xp_reward", 200),
 #           (assign, ":quest_gold_reward", 150),
 #           (assign, ":result", ":quest_no"),
#            (assign, ":quest_expiration_days", 30),
#            (assign, ":quest_dont_give_again_period", 20),
#            (assign, "$qst_bring_back_runaway_serfs_num_parties_returned", 0),
#            (assign, "$qst_bring_back_runaway_serfs_num_parties_fleed", 0),
#          (try_end),
#        (else_try),
#          (eq, ":quest_no", "qst_lend_companion"),
#          (try_begin),
#            (assign, ":total_heroes", 0),
#            (party_get_num_companion_stacks, ":num_stacks","p_main_party"),
#            (try_for_range, ":i_stack", 0, ":num_stacks"),
#              (party_stack_get_troop_id, ":stack_troop","p_main_party",":i_stack"),
#              (troop_is_hero, ":stack_troop"),
#              (neq, ":stack_troop", "trp_player"),
#              (store_character_level, ":stack_level", ":stack_troop"),
#              (ge, ":stack_level", 15),
#              (assign, ":is_quest_hero", 0),
#              (try_for_range, ":i_quest", 0, all_quests_end),
#                (check_quest_active, ":i_quest"),
#                (this_or_next|quest_slot_eq, ":i_quest", slot_quest_target_troop, ":stack_troop"),
#                (quest_slot_eq, ":i_quest", slot_quest_object_troop, ":stack_troop"),
#                (assign, ":is_quest_hero", 1),
#              (try_end),
#              (eq, ":is_quest_hero", 0),
#              (val_add, ":total_heroes", 1),
#            (try_end),
#            (gt, ":total_heroes", 0),#Skip if party has no eligible heroes
#            (store_random_in_range, ":random_hero", 0, ":total_heroes"),
#            (assign, ":total_heroes", 0),
#            (assign, ":cur_target_troop", -1),
#            (try_for_range, ":i_stack", 0, ":num_stacks"),
#              (eq, ":cur_target_troop", -1),
#              (party_stack_get_troop_id, ":stack_troop","p_main_party",":i_stack"),
#              (troop_is_hero, ":stack_troop"),
#              (neq, ":stack_troop", "trp_player"),
#              (store_character_level, ":stack_level", ":stack_troop"),
#              (ge, ":stack_level", 15),
#              (assign, ":is_quest_hero", 0),
#              (try_for_range, ":i_quest", 0, all_quests_end),
#                (check_quest_active, ":i_quest"),
#                (this_or_next|quest_slot_eq, ":i_quest", slot_quest_target_troop, ":stack_troop"),
#                (quest_slot_eq, ":i_quest", slot_quest_object_troop, ":stack_troop"),
#                (assign, ":is_quest_hero", 1),
#              (try_end),
#              (eq, ":is_quest_hero", 0),
#              (val_add, ":total_heroes", 1),
#              (gt, ":total_heroes", ":random_hero"),
#              (assign, ":cur_target_troop", ":stack_troop"),
#            (try_end),
#            (assign, ":quest_target_troop", ":cur_target_troop"),
#            (store_current_day, ":quest_target_amount"),
#            (val_add, ":quest_target_amount", 8),#
#
 #           (assign, ":quest_importance", 1),
#            (assign, ":quest_xp_reward", 300),
#            (assign, ":quest_gold_reward", 400),
#            (assign, ":result", ":quest_no"),
#            (assign, ":quest_dont_give_again_period", 30),
#          (try_end),
#        (else_try),
#          (eq, ":quest_no", "qst_collect_debt"),
#          (try_begin),
 #         # Find a vassal (within the same kingdom?) 
#            (call_script, "script_cf_get_random_lord_in_a_center_with_faction", ":giver_faction_no"),#Can fail
#            (assign, ":quest_target_troop", reg0),
#            (neq, ":quest_target_troop", ":giver_troop"),#Skip himself
#            (call_script, "script_get_troop_attached_party", ":quest_target_troop"),
#            (assign, ":quest_target_center", reg0),#cur_target_center will definitely be a valid center
#            (neq,":giver_center_no", ":quest_target_center"),#Skip current center
#
#            (assign, ":quest_xp_reward", 30),
#            (assign, ":quest_gold_reward", 40),
#            (assign, ":result", ":quest_no"),
#            (store_random_in_range, ":quest_target_amount", 6, 9),
#            (val_mul, ":quest_target_amount", 500),
#            (store_div, ":quest_convince_value", ":quest_target_amount", 5),
#            (assign, ":quest_expiration_days", 90),
#            (assign, ":quest_dont_give_again_period", 20),
#          (try_end),
        (else_try),
          (eq, ":quest_no", "qst_capture_prisoners"),
          (try_begin),
            (call_script, "script_cf_faction_get_random_enemy_faction", ":giver_faction_no"),#Can fail
            (assign, ":cur_target_faction", reg0),
            (store_add, ":max_tier_no", slot_faction_tier_5_troop, 1),
            (store_random_in_range, ":random_tier_no", slot_faction_tier_1_troop, ":max_tier_no"),
            (faction_get_slot, ":cur_target_troop", ":cur_target_faction", ":random_tier_no"),
            (gt, ":cur_target_troop", 0),
            (store_random_in_range, ":quest_target_amount", 3, 7),
            (assign, ":quest_target_troop", ":cur_target_troop"),
            (assign, ":quest_target_faction", ":cur_target_faction"),
            (assign, ":quest_importance", 1),
            (store_character_level, ":quest_gold_reward", ":cur_target_troop"),
            (val_add, ":quest_gold_reward", 5),
            (val_mul, ":quest_gold_reward", ":quest_gold_reward"),
            (val_div, ":quest_gold_reward", 5),
            (val_mul, ":quest_gold_reward", ":quest_target_amount"),
            (assign, ":quest_xp_reward", ":quest_gold_reward"),
            (assign, ":result", ":quest_no"),
            (assign, ":quest_expiration_days", 90),
            (assign, ":quest_dont_give_again_period", 20),
          (try_end),
        (try_end),
      (try_end),
      (try_begin),
        (neq, ":result", -1),
        
        (try_begin),
          (ge, ":quest_target_center", 0),
          (store_faction_of_party, ":quest_target_faction", ":quest_target_center"),
        (try_end),
        (try_begin),
          (ge, ":quest_target_troop", 0),
          (troop_get_slot, ":quest_target_troop_is_prisoner", ":quest_target_troop", slot_troop_is_prisoner),
        (try_end),
        
        (quest_set_slot, ":result", slot_quest_target_troop, ":quest_target_troop"),
        (quest_set_slot, ":result", slot_quest_target_center, ":quest_target_center"),
        (quest_set_slot, ":result", slot_quest_object_troop, ":quest_object_troop"),
        (quest_set_slot, ":result", slot_quest_target_troop_is_prisoner, ":quest_target_troop_is_prisoner"),
        (quest_set_slot, ":result", slot_quest_target_faction, ":quest_target_faction"),
        (quest_set_slot, ":result", slot_quest_object_center, ":quest_object_center"),
        (quest_set_slot, ":result", slot_quest_target_party, ":quest_target_party"),
        (quest_set_slot, ":result", slot_quest_target_party_template, ":quest_target_party_template"),
        (quest_set_slot, ":result", slot_quest_target_amount, ":quest_target_amount"),
        (quest_set_slot, ":result", slot_quest_importance, ":quest_importance"),
        (quest_set_slot, ":result", slot_quest_xp_reward, ":quest_xp_reward"),
        (quest_set_slot, ":result", slot_quest_gold_reward, ":quest_gold_reward"),
        (quest_set_slot, ":result", slot_quest_convince_value, ":quest_convince_value"),
        (quest_set_slot, ":result", slot_quest_expiration_days, ":quest_expiration_days"),
        (quest_set_slot, ":result", slot_quest_dont_give_again_period, ":quest_dont_give_again_period"),
        (quest_set_slot, ":result", slot_quest_current_state, 0),
        (quest_set_slot, ":result", slot_quest_giver_troop, ":giver_troop"),
        (quest_set_slot, ":result", slot_quest_giver_center, ":giver_center_no"),
        (quest_set_slot, ":result", slot_quest_target_dna, ":quest_target_dna"),
        (quest_set_slot, ":result", slot_quest_target_item, ":quest_target_item"),
      (try_end),
      
      (assign, reg0, ":result"),
  ]),
  
  # script_cf_get_random_lord_in_a_center_with_faction
  # Input: arg1 = faction_no
  # Output: reg0 = troop_no, Can Fail!
  ("cf_get_random_lord_in_a_center_with_faction",
    [
      (store_script_param_1, ":faction_no"),
      (assign, ":result", -1),
      (assign, ":count_lords", 0),
      (try_for_range, ":lord_no", heroes_begin, heroes_end),
        (store_troop_faction, ":lord_faction_no", ":lord_no"),
        (eq, ":faction_no", ":lord_faction_no"),
        (troop_slot_eq, ":lord_no", slot_troop_occupation, slto_kingdom_hero),
        (troop_slot_eq, ":lord_no", slot_troop_is_prisoner, 0),
        (troop_get_slot, ":lord_party", ":lord_no", slot_troop_leaded_party),
        (ge, ":lord_party", 0),
        (party_get_attached_to, ":lord_attachment", ":lord_party"),
        (is_between, ":lord_attachment", centers_begin, centers_end), #is troop in a center?
        (val_add, ":count_lords", 1),
      (try_end),
      (store_random_in_range, ":random_lord", 0, ":count_lords"),
      (assign, ":count_lords", 0),
      (try_for_range, ":lord_no", heroes_begin, heroes_end),
        (eq, ":result", -1),
        (store_troop_faction, ":lord_faction_no", ":lord_no"),
        (eq, ":faction_no", ":lord_faction_no"),
        (troop_slot_eq, ":lord_no", slot_troop_occupation, slto_kingdom_hero),
        (troop_slot_eq, ":lord_no", slot_troop_is_prisoner, 0),
        (troop_get_slot, ":lord_party", ":lord_no", slot_troop_leaded_party),
        (ge, ":lord_party", 0),
        (party_get_attached_to, ":lord_attachment", ":lord_party"),
        (is_between, ":lord_attachment", centers_begin, centers_end), #is troop in a center?
        (val_add, ":count_lords", 1),
        (lt, ":random_lord", ":count_lords"),
        (assign, ":result", ":lord_no"),
      (try_end),
      (neq, ":result", -1),
      (assign, reg0, ":result"),
  ]),
  # script_cf_get_random_lord_from_another_faction_in_a_center
  # Input: arg1 = faction_no
  # Output: reg0 = troop_no, Can Fail!
  ("cf_get_random_lord_from_another_faction_in_a_center",
    [
      (store_script_param_1, ":faction_no"),
      (assign, ":result", -1),
      (assign, ":count_lords", 0),
      (try_for_range, ":lord_no", heroes_begin, heroes_end),
        (store_troop_faction, ":lord_faction_no", ":lord_no"),
        (neq, ":lord_faction_no", ":faction_no"),
        (store_relation, ":our_relation", ":lord_faction_no", "fac_player_faction"),
        (store_relation, ":lord_relation", ":lord_faction_no", ":faction_no"),
        (lt, ":lord_relation", 0),
        (ge, ":our_relation", 0),
        (troop_slot_eq, ":lord_no", slot_troop_occupation, slto_kingdom_hero),
        (troop_slot_eq, ":lord_no", slot_troop_is_prisoner, 0),
        (troop_get_slot, ":lord_party", ":lord_no", slot_troop_leaded_party),
        (ge, ":lord_party", 0),
        (party_get_attached_to, ":lord_attachment", ":lord_party"),
        (is_between, ":lord_attachment", centers_begin, centers_end), #is troop in a center?
        (val_add, ":count_lords", 1),
      (try_end),
      (store_random_in_range, ":random_lord", 0, ":count_lords"),
      (assign, ":count_lords", 0),
      (try_for_range, ":lord_no", heroes_begin, heroes_end),
        (eq, ":result", -1),
        (store_troop_faction, ":lord_faction_no", ":lord_no"),
        (neq, ":lord_faction_no", ":faction_no"),
        (store_relation, ":our_relation", ":lord_faction_no", "fac_player_faction"),
        (store_relation, ":lord_relation", ":lord_faction_no", ":faction_no"),
        (lt, ":lord_relation", 0),
        (ge, ":our_relation", 0),
        (troop_slot_eq, ":lord_no", slot_troop_occupation, slto_kingdom_hero),
        (troop_slot_eq, ":lord_no", slot_troop_is_prisoner, 0),
        (troop_get_slot, ":lord_party", ":lord_no", slot_troop_leaded_party),
        (ge, ":lord_party", 0),
        (party_get_attached_to, ":lord_attachment", ":lord_party"),
        (is_between, ":lord_attachment", centers_begin, centers_end), #is troop in a center?
        (val_add, ":count_lords", 1),
        (lt, ":random_lord", ":count_lords"),
        (assign, ":result", ":lord_no"),
      (try_end),
      (neq, ":result", -1),
      (assign, reg0, ":result"),
  ]),
  # script_cf_troop_get_random_leaded_town_or_village_except_center
  # Input: arg1 = troop_no, arg2 = except_center_no
  # Output: reg0 = center_no (Can fail)
  ("cf_troop_get_random_leaded_town_or_village_except_center",
    [
      (store_script_param_1, ":troop_no"),
      (store_script_param_2, ":except_center_no"),

      (assign, ":num_centers", 0),
      (try_for_range, ":center_no", centers_begin, centers_end),
        (neg|party_slot_eq, ":center_no", slot_party_type, spt_castle),
        (party_slot_eq, ":center_no", slot_town_lord, ":troop_no"),
        (neq, ":center_no", ":except_center_no"),
        (val_add, ":num_centers", 1),
      (try_end),

      (gt, ":num_centers", 0),
      (store_random_in_range, ":random_center", 0, ":num_centers"),
      (assign, ":end_cond", centers_end),
      (try_for_range, ":center_no", centers_begin, ":end_cond"),
        (neg|party_slot_eq, ":center_no", slot_party_type, spt_castle),
        (party_slot_eq, ":center_no", slot_town_lord, ":troop_no"),
        (neq, ":center_no", ":except_center_no"),
        (val_sub, ":random_center", 1),
        (lt, ":random_center", 0),
        (assign, ":target_center", ":center_no"),
        (assign, ":end_cond", 0),
      (try_end),
      (assign, reg0, ":target_center"),
  ]),
  #script_cf_select_random_village_with_faction:
  # This script selects a random village in range [villages_begin, villages_end)
  # such that faction of the village is equal to given_faction
  # INPUT:
  # arg1 = faction_no
  
  #OUTPUT:
  # This script may return false if there is no matching village.
  # reg0 = village_no
  ("cf_select_random_village_with_faction",
    [
      (store_script_param_1, ":faction_no"),
      (assign, ":result", -1),
      # First count num matching spawn points
      (assign, ":no_villages", 0),
      (try_for_range,":cur_village", villages_begin, villages_end),
        (store_faction_of_party, ":cur_faction", ":cur_village"),
        (eq, ":cur_faction", ":faction_no"),
        (val_add, ":no_villages", 1),
      (try_end),
      (gt, ":no_villages", 0), #Fail if there are no villages
      (store_random_in_range, ":random_village", 0, ":no_villages"),
      (assign, ":no_villages", 0),
      (try_for_range,":cur_village", villages_begin, villages_end),
        (eq, ":result", -1),
        (store_faction_of_party, ":cur_faction", ":cur_village"),
        (eq, ":cur_faction", ":faction_no"),
        (val_add, ":no_villages", 1),
        (gt, ":no_villages", ":random_village"),
        (assign, ":result", ":cur_village"),
      (try_end),
      (assign, reg0, ":result"),
  ]),
  #script_cf_select_random_town_with_faction:
  # This script selects a random town in range [towns_begin, towns_end)
  # such that faction of the town is equal to given_faction
  # INPUT:
  # arg1 = faction_no
  
  #OUTPUT:
  # This script may return false if there is no matching town.
  # reg0 = town_no
  ("cf_select_random_town_with_faction",
    [
      (store_script_param_1, ":faction_no"),
      (assign, ":result", -1),
      # First count num matching spawn points
      (assign, ":no_towns", 0),
      (try_for_range,":cur_town", towns_begin, towns_end),
        (store_faction_of_party, ":cur_faction", ":cur_town"),
        (eq, ":cur_faction", ":faction_no"),
        (val_add, ":no_towns", 1),
      (try_end),
      (gt, ":no_towns", 0), #Fail if there are no towns
      (store_random_in_range, ":random_town", 0, ":no_towns"),
      (assign, ":no_towns", 0),
      (try_for_range,":cur_town", towns_begin, towns_end),
        (eq, ":result", -1),
        (store_faction_of_party, ":cur_faction", ":cur_town"),
        (eq, ":cur_faction", ":faction_no"),
        (val_add, ":no_towns", 1),
        (gt, ":no_towns", ":random_town"),
        (assign, ":result", ":cur_town"),
      (try_end),
      (assign, reg0, ":result"),
  ]),
  # script_finish_quest
  # Input: arg1 = quest_no, arg2 = finish_percentage
  # Output: none
  ("finish_quest",
    [
      (store_script_param_1, ":quest_no"),
      (store_script_param_2, ":finish_percentage"),
      
      (quest_get_slot, ":quest_giver", ":quest_no", slot_quest_giver_troop),
      (quest_get_slot, ":quest_importance", ":quest_no", slot_quest_importance),
      (quest_get_slot, ":quest_xp_reward", ":quest_no", slot_quest_xp_reward),
      (quest_get_slot, ":quest_gold_reward", ":quest_no", slot_quest_gold_reward),
      
      (try_begin),
        (lt, ":finish_percentage", 100),
        (val_mul, ":quest_xp_reward", ":finish_percentage"),
        (val_div, ":quest_xp_reward", 100),
        (val_mul, ":quest_gold_reward", ":finish_percentage"),
        (val_div, ":quest_gold_reward", 100),
        #Changing the relation factor. Negative relation if less than 75% of the quest is finished.
        #Positive relation if more than 75% of the quest is finished.
        (assign, ":importance_multiplier", ":finish_percentage"),
        (val_sub, ":importance_multiplier", 75),
        (val_mul, ":quest_importance", ":importance_multiplier"),
        (val_div, ":quest_importance", 100),
      (else_try),
        (val_div, ":quest_importance", 4),
        (val_add, ":quest_importance", 1),
        (call_script, "script_change_player_relation_with_troop", ":quest_giver", ":quest_importance"),
      (try_end),
      
      (add_xp_as_reward, ":quest_xp_reward"),
      (troop_add_gold, "trp_player", ":quest_gold_reward"),
      (call_script, "script_end_quest", ":quest_no"),
  ]),
  # script_abort_quest
  # Input: arg1 = quest_no, arg2 = apply relation penalty
  # Output: none
  ("abort_quest",
    [
      (store_script_param_1, ":quest_no"),
      (store_script_param_2, ":abort_type"), #0=aborted by event, 1=abort by talking 2=abort by expire

      (assign, ":quest_return_penalty", -1),
      (assign, ":quest_expire_penalty", -2),
      
#      (quest_get_slot, ":quest_object_troop", ":quest_no", slot_quest_object_troop),
      (try_begin),
        (eq, ":quest_no", "qst_deliver_message"),

        (assign, ":quest_expire_penalty", -3),
      (else_try),
        (eq, ":quest_no", "qst_raise_troops"),
        (quest_get_slot, ":quest_giver_troop", ":quest_no", slot_quest_giver_troop),
        (call_script, "script_change_debt_to_troop", ":quest_giver_troop", 100),
        (assign, ":quest_return_penalty", -4),
        (assign, ":quest_expire_penalty", -5),
      (else_try),
        (eq, ":quest_no", "qst_escort_merchant_caravan"),
        (assign, ":quest_return_penalty", -1),
        (assign, ":quest_expire_penalty", -3),
      (else_try),
        (eq, ":quest_no", "qst_troublesome_bandits"),
        (assign, ":quest_return_penalty", -1),
        (assign, ":quest_expire_penalty", -2),
      #Other quests
      (else_try),
        (eq, ":quest_no", "qst_join_faction"),
        (assign, ":quest_return_penalty", -3),
        (assign, ":quest_expire_penalty", -3),
      (try_end),
      (try_begin),
        (gt, ":abort_type", 0),
        (quest_get_slot, ":quest_giver", ":quest_no", slot_quest_giver_troop),
        (assign, ":relation_penalty", ":quest_return_penalty"),
        (try_begin),
          (eq, ":abort_type", 2),
          (assign, ":relation_penalty", ":quest_expire_penalty"),
        (try_end),
          (call_script, "script_change_player_relation_with_troop", ":quest_giver", ":relation_penalty"),
      (try_end),
      (fail_quest, ":quest_no"),
      (call_script, "script_end_quest", ":quest_no"),
  ]),
  # script_change_debt_to_troop
  # Input: arg1 = troop_no, arg2 = new debt amount
  # Output: none
  ("change_debt_to_troop",
    [
      (store_script_param_1, ":troop_no"),
      (store_script_param_2, ":new_debt"),
      
      (troop_get_slot, ":cur_debt", ":troop_no", slot_troop_player_debt),
      (assign, reg1, ":cur_debt"),
      (val_add, ":cur_debt", ":new_debt"),
      (assign, reg2, ":cur_debt"),
      (troop_set_slot, ":troop_no", slot_troop_player_debt, ":cur_debt"),
      (str_store_troop_name, s1, ":troop_no"),
      (display_message, "@You now owe {reg2} denars to {s1}."),
  ]),
  
	("cf_check_relation_with_faction",
		[
			#(store_relation,<destination>,<faction_id_1>,<faction_id_2>),
			(store_script_param_1, ":fac_no"),
			(store_relation,":rel",":fac_no","fac_player_faction"),
			(ge,":rel",0),
		]
	),
 
	("get_job",
		[
			(try_begin),
				(eq,"$wenguan",1),
				(assign,":job",1),
			(else_try),
				(eq,"$wuguan",1),
				(assign,":job",2),
			(try_end),
			(assign,reg45,":job"),
		]
	),

	("command_lord_avalible",
		[
			(store_script_param_1, ":cmd_lv"),
			(call_script,"script_get_job"),
			(assign,":job",reg45),
			(assign,":able",0),
			(try_begin),
				(eq,":cmd_lv",0),
				(assign,":able",1),
			(else_try),
				(eq,":cmd_lv",1),
				(ge,"$quest_prestige",setting_vclp_1),
				(try_begin),
					(eq,":job",1),
					(ge,"$faction_rank",setting_vclge_1),
					(assign,":able",1),
				(else_try),
					(eq,":job",2),
					(ge,"$faction_rank",setting_vclgu_1),
					(assign,":able",1),
				(try_end),
			(else_try),
				(eq,":cmd_lv",2),
				(ge,"$quest_prestige",setting_vclp_2),
				(try_begin),
					(eq,":job",1),
					(ge,"$faction_rank",setting_vclge_2),
					(assign,":able",1),
				(else_try),
					(eq,":job",2),
					(ge,"$faction_rank",setting_vclgu_2),
					(assign,":able",1),
				(try_end),
			(else_try),
				(eq,":cmd_lv",3),
				(ge,"$quest_prestige",setting_vclp_3),
				(try_begin),
					(eq,":job",1),
					(ge,"$faction_rank",setting_vclge_3),
					(assign,":able",1),
				(else_try),
					(eq,":job",2),
					(ge,"$faction_rank",setting_vclgu_3),
					(assign,":able",1),
				(try_end),
			(try_end),
			(assign,reg45,":able"),
		]
 ),
 
	("suggestion_success_poss",
  [
   (store_skill_level,":skl_st",skl_stratagem,"trp_player"),
   (store_skill_level,":skl_ls",skl_leadership,"trp_player"),
   (store_character_level,":base_lv","trp_player"),
   (assign,":job_lv","$faction_rank"),
   (store_attribute_level,":attr_int","trp_player",ca_intelligence),
   (store_attribute_level,":attr_cha","trp_player",ca_charisma),
   (assign,":poss",0),
   (val_mul,":base_lv",setting_base_lv_rate),
   (val_div,":base_lv",100),
   (val_mul,":job_lv",setting_job_lv_rate),
   (val_div,":job_lv",100),
   (val_mul,":attr_int",setting_int_rate),
   (val_div,":attr_int",100),
   (val_mul,":attr_cha",setting_cha_rate),
   (val_div,":attr_cha",100),
   (val_mul,":skl_st",setting_stsk_lv_rate),
   (val_div,":skl_st",100),
   (val_mul,":skl_ls",setting_lssk_lv_rate),
   (val_div,":skl_ls",100),
   (val_add,":poss",":base_lv"),
   (val_add,":poss",":job_lv"),
   (val_add,":poss",":attr_int"),
   (val_add,":poss",":attr_cha"),
   (val_add,":poss",":skl_st"),
   (val_add,":poss",":skl_ls"),
   (val_mul,":poss",setting_base_rate),
   (val_div,":poss",100),
   (try_begin),
    (eq,"$sf",1),
    (val_mul,":poss",setting_sk_lv_1_rate),
    (val_div,":poss",100),
   (else_try),
    (eq,"$sf",2),
    (val_mul,":poss",setting_sk_lv_2_rate),
    (val_div,":poss",100),
   (try_end),
   
   (assign,reg45,":poss"),
  ]
),
	
	("try_suggest",
		[
			(store_random_in_range,":rand",1,setting_suggestion_success_possibility_rate+1),
			(call_script,"script_suggestion_success_poss"),
			(assign,":gate",reg45),
			(assign,reg45,0),
			(try_begin),
				(le,":rand",":gate"),
				(assign,reg45,1),
			(try_end),
		]
	),
##SG
  ("count_qi_xi_agents",
    [
     (try_for_agents, ":cur_agent"),
       (agent_is_human, ":cur_agent"),
       (neg|agent_is_alive, ":cur_agent"),
       (agent_get_slot,":re",":cur_agent", slot_agent_is_not_reinforcement),
       (eq,":re",2),
#       (agent_get_team,":team",":cur_agent"),
#       (eq,":team",3),
       (val_sub,"$qi_xi_num",1),
       (try_begin),
         (agent_is_wounded, ":cur_agent"),
         (val_add,"$qi_xi_num",1),
         (val_add,"$wounded",1),
       (try_end),
     (try_end),
     ]),

  ("add_qi_xi_troop_to_main_party",
    [
        (party_add_members,"p_main_party","$qi_xi_troop","$qi_xi_num"),
        (party_wound_members, "p_main_party", "$qi_xi_troop","$wounded"),
        (store_skill_level,":st",skl_stratagem,"trp_player"),
        (store_character_level,":trp_lv","$qi_xi_troop"),
        (val_mul,":st",2),
        (val_mul,":st",":trp_lv"),
        (store_mul,":add_xp",":st","$qi_xi_num"),
        (set_show_messages,0),
        (party_add_xp,"p_main_party",":add_xp"),
        (set_show_messages,1),
        (assign,"$use_qixi",0),
        (assign,"$qi_xi_troop",-1),
        (assign,"$amount_to_use",0),
        (assign,"$qi_xi_num",0),
     ]),

   #Huoji
  ("sg_huo_ji",
    [
        (val_sub,"$max_st",1),
        (val_sub,"$hj_use_count",1),
        (try_begin),
          (lt,"$hj_use_count",1),
          (assign, "$can_use_fire", 0),
        (try_end),
        (get_player_agent_no,":player"), 
        (agent_get_look_position,pos1,":player"),
        (position_move_y,pos1,4000), 
        (store_random_in_range,":rp",0,100),
        (store_skill_level,":st",skl_stratagem,"trp_player"),
        (store_mul,":dm",":st",5),
        (val_add,":dm",10),
        (store_mul,":b_dist",":st",200),
        (try_begin),
          (eq,"$huoji",1),
          (val_add,":b_dist",200),
        (else_try),
          (eq,"$huoji",2),
          (val_add,":b_dist",400),
        (try_end),
        (val_add,":b_dist",1000),
        (val_mul,":st",5),
        (store_attribute_level,":int","trp_player",ca_intelligence),
        (val_mul,":int",2),
        (store_add,":p_rp",":int",":st"),
        (try_begin),
          (eq,"$huoji",1),
          (val_add,":p_rp",10),
        (else_try),
          (eq,"$huoji",2),
          (val_add,":p_rp",20),
        (try_end),
        (val_add,":p_rp","$c_rp"),

        (assign,":e_rp",0),#
        (try_for_agents,":agents"), 
           (neg|agent_is_ally,":agents"),
           (agent_is_alive,":agents"),
           (agent_get_troop_id,":agent",":agents"),
           (troop_is_hero,":agent"),
           (store_skill_level,":e_st",skl_stratagem,":agent"),
           (store_attribute_level,":e_int",":agent",ca_intelligence),
           (val_mul,":e_st",5),
           (val_mul,":e_int",2),
           (store_add,":he",":e_int",":e_st"),#
           (gt,":he",":e_rp"),#
           (assign,":e_rp",":he"),#
        (try_end),

        (store_sub,":t_rp",":p_rp",":e_rp"),
        (val_add,":rp",":t_rp"),
        (try_begin),
          (eq, "$current_terrain",1),
          (val_sub,":rp",20),
        (else_try),
          (eq, "$current_terrain",2),
          (val_add,":rp",20),
        (try_end),
        (try_begin),
          (ge,":rp",100),#100
          (display_message,"str_success"),
          (try_for_agents,":agents"),
            (agent_get_look_position,pos2,":agents"),  
            (get_distance_between_positions,":dist",pos1,pos2),
            (lt,":dist",":b_dist"),
            (store_agent_hit_points,":hp",":agents",1),
            (val_sub,":hp",":dm"),
            (agent_set_hit_points,":agents",":hp",1),
            (agent_set_animation, ":agents", 284),
            (lt,":hp",1),
            (agent_deliver_damage_to_agent,":player",":agents"),
          (end_try),
          (play_sound, "snd_fire_burning"),
          (position_set_z_to_ground_level, pos1),
          (particle_system_burst, "psys_massive_fire", pos1, 50),
          (particle_system_burst, "psys_war_smoke", pos1, 30),
          (position_move_y,pos1,2000),
          (particle_system_burst, "psys_massive_fire", pos1, 50),
          (particle_system_burst, "psys_war_smoke", pos1, 30),
          (position_move_x,pos1,2000),
          (particle_system_burst, "psys_massive_fire", pos1, 50),
          (particle_system_burst, "psys_war_smoke", pos1, 30),
          (position_move_x,pos1,-4000),
          (particle_system_burst, "psys_massive_fire", pos1, 50),
          (particle_system_burst, "psys_war_smoke", pos1, 30),
          (position_move_y,pos1,-2000),
          (particle_system_burst, "psys_massive_fire", pos1, 50),
          (particle_system_burst, "psys_war_smoke", pos1, 30),
          (position_move_y,pos1,-2000),
          (particle_system_burst, "psys_massive_fire", pos1, 50),
          (particle_system_burst, "psys_war_smoke", pos1, 30),
          (position_move_x,pos1,2000),
          (particle_system_burst, "psys_massive_fire", pos1, 50),
          (particle_system_burst, "psys_war_smoke", pos1, 30),
          (position_move_x,pos1,2000),
          (particle_system_burst, "psys_massive_fire", pos1, 50),
          (particle_system_burst, "psys_war_smoke", pos1, 30),
          (position_move_y,pos1,2000),
          (particle_system_burst, "psys_massive_fire", pos1, 30),
          (particle_system_burst, "psys_war_smoke", pos1, 30),
        (else_try),
          (display_message,"str_failure"),
        (end_try),
     ]),
    #Lijian
  ("sg_li_jian",
    [
        (display_message,"str_lijian"),
        (val_sub,"$max_st",1),
        (get_player_agent_no,":player"), 
        (agent_get_team,":team",":player"),
        (agent_get_look_position,pos1,":player"),
        (store_skill_level,":st",skl_stratagem,"trp_player"),
        (store_mul,":b_dist",":st",100),
        (try_begin),
          (eq,"$lijian",1),
          (val_add,":b_dist",200),
        (else_try),
          (eq,"$lijian",2),
          (val_add,":b_dist",400),
        (try_end),
        (val_add,":b_dist",800),
        (val_mul,":st",3),
        (store_attribute_level,":int","trp_player",ca_intelligence),
        (store_add,":p_rp",":int",":st"),
        (try_begin),
          (eq,"$lijian",1),
          (val_add,":p_rp",10),
        (else_try),
          (eq,"$lijian",2),
          (val_add,":p_rp",20),
        (try_end),
        (val_add,":p_rp","$c_rp"),

        (assign,":e_rp",0),#
        (assign,":e_js",0),
        (try_for_agents,":agents"), 
           (neg|agent_is_ally,":agents"),
           (agent_is_alive,":agents"),
           (agent_get_troop_id,":agent",":agents"),
           (troop_is_hero,":agent"),
           (store_skill_level,":e_st",skl_stratagem,":agent"),
           (store_attribute_level,":e_int",":agent",ca_intelligence),
           (val_mul,":e_st",5),
           (store_add,":he",":e_int",":e_st"),
           (gt,":he",":e_rp"),
           (assign,":e_rp",":he"),
           (assign,":e_js",":agent"),
           (agent_get_look_position,pos40,":agents"),
        (try_end),

        (store_sub,":t_rp",":p_rp",":e_rp"),
        (val_add,":t_rp","$num_ae"),

        (try_begin),
          (gt,":e_js",0),
          (this_or_next|eq,":e_js","trp_jiaxu"),
          (this_or_next|eq,":e_js","trp_guojia"),
          (eq,":e_js","trp_zhugeliang"),
          (store_random_in_range,":rp",0,100),
          (val_add,":rp",":t_rp"),
          (lt,":rp",100),
          (str_store_troop_name,s59,":e_js"),
          (display_message,"@success2"),
          (store_sub,":e_team",1,":team"),
          (assign,":num",0),
          (try_for_agents,":agents"),
            (agent_is_ally,":agents"),
            (neq,":agents",":player"), 
            (agent_is_alive,":agents"),
            (agent_is_human,":agents"),
            (agent_get_look_position,pos2,":agents"),  
            (get_distance_between_positions,":dist",pos40,pos2),
            (lt,":dist",5000),
            (store_random_in_range,":rp",0,100),
            (val_add,":rp",":t_rp"),
            (lt,":rp",100),
            (agent_set_team,":agents",":e_team"),
            (val_add,":num",1),
          (try_end),
          (try_begin),
            (gt,":num",0),
            (assign,reg60,":num"),
            (display_message,"@success2_1"),
          (else_try),
            (str_store_troop_name,s59,":e_js"),
            (display_message,"@failure1"),
          (try_end),
        (else_try),
          (assign,":success_num",0),
          (try_for_agents,":agents"),
            (neg|agent_is_ally,":agents"),
            (agent_is_alive,":agents"),
            (agent_is_human,":agents"),
            (agent_get_look_position,pos2,":agents"),  
            (get_distance_between_positions,":dist",pos1,pos2),
            (lt,":dist",":b_dist"),
            (store_random_in_range,":rp",0,100),
            (val_add,":rp",":t_rp"),
            (ge,":rp",100),
            (agent_set_team,":agents",":team"),
            (val_add,":success_num",1),
          (try_end),
          (try_begin),
            (gt,":success_num",0),
            (assign,reg60,":success_num"),
            (display_message,"str_success1"),
          (else_try),
            (display_message,"str_failure"),
          (try_end),
        (try_end),
     ]),
   #Qixi
  ("sg_qi_xi",
    [
        (display_message,"str_qixi"),
        (assign,"$use_qixi",2),
        (val_sub,"$max_st",1),

        (get_player_agent_no,":player"), 
        (agent_get_team,":i_team",":player"),
        (store_sub,":e_team",1,":i_team"),#
        (agent_get_look_position,pos1,":player"),
        (position_move_y,pos1,4000), 
        (store_skill_level,":st",skl_stratagem,"trp_player"),
        (val_mul,":st",5),
        (try_begin),
          (eq,"$qixi",1),
          (val_add,":st",5),
        (else_try),
          (eq,"$qixi",2),
          (val_add,":st",10),
        (try_end),
        (store_attribute_level,":int","trp_player",ca_intelligence),
        (store_add,":p_rp",":int",":st"),
        (store_random_in_range,":rp",0,20),
        (val_add,":p_rp",":rp"),

        (try_begin),
          (eq, "$current_terrain",1),
          (val_sub,":p_rp",10),
        (else_try),
          (ge, "$current_terrain",2),
          (val_add,":p_rp",20),
        (try_end),

        (try_begin),
          (lt,":p_rp",40),
          (display_message,"str_failure"),
        (else_try),
          (try_begin),
            (lt,":p_rp",50),
            (assign,":m_num",5),
          (else_try),
            (ge,":p_rp",50),
            (lt,":p_rp",70),
            (assign,":m_num",6),
          (else_try),
            (ge,":p_rp",70),
            (lt,":p_rp",90),
            (assign,":m_num",7),
          (else_try),
            (assign,":m_num",8),
          (try_end),

          (assign,":finded",0),
          (try_for_range,":i",0,":m_num"), 
            (gt,"$amount_to_use",0),
            (set_spawn_position, pos1),
            (spawn_agent,"$qi_xi_troop"),
            (agent_set_team,reg0,2),
            (agent_set_slot,reg0,slot_agent_is_not_reinforcement,2),#
            (try_begin),
              (eq,":finded",0),
              (team_set_leader,2,reg0),
              (assign,":finded",1),
            (try_end),
            (position_move_x,pos1,50),
            (val_sub,"$amount_to_use",1),
          (try_end),
          (team_set_relation,2,":i_team",1),
          (team_set_relation,2,":e_team",-1),
          (display_message,"str_success"),#
        (try_end),
     ]),
   #Hunluan
  ("sg_hun_luan",
    [
         (val_sub,"$max_st",1),
         (store_skill_level,":st",skl_stratagem,"trp_player"),

         (store_mul,":b_dist",":st",200),
         (try_begin),
           (eq,"$hunluan",1),
           (val_add,":b_dist",500),
         (else_try),
           (eq,"$hunluan",2),
           (val_add,":b_dist",1000),
         (try_end),
         (val_add,":b_dist",1200),

         (val_mul,":st",5),
         (store_attribute_level,":int","trp_player",ca_intelligence),
         (val_mul,":int",2),
         (store_add,":p_rp",":int",":st"),
         (try_begin),
          (eq,"$hunluan",1),
          (val_add,":p_rp",5),
         (else_try),
          (eq,"$hunluan",2),
          (val_add,":p_rp",10),
         (try_end),
         (val_add,":p_rp","$c_rp"),

         (assign,":e_rp",0),#
         (assign,":e_js",0),
         (try_for_agents,":agents"), 
           (neg|agent_is_ally,":agents"),
           (agent_is_alive,":agents"),
           (agent_get_troop_id,":agent",":agents"),
           (troop_is_hero,":agent"),
           (store_skill_level,":e_st",skl_stratagem,":agent"),
           (store_attribute_level,":e_int",":agent",ca_intelligence),
           (val_mul,":e_st",5),
           (val_mul,":e_int",2),
           (store_add,":he",":e_int",":e_st"),#
           (gt,":he",":e_rp"),#
           (assign,":e_rp",":he"),#
           (assign,":e_js",":agent"),
           (agent_get_look_position,pos40,":agents"),
         (try_end),

         (store_sub,":t_rp",":p_rp",":e_rp"),

        (try_begin),
          (gt,":e_js",0),
          (this_or_next|eq,":e_js","trp_jiaxu"),
          (this_or_next|eq,":e_js","trp_guojia"),
          (eq,":e_js","trp_zhugeliang"),
          (store_random_in_range,":rp",0,100),
          (val_add,":rp",":t_rp"),
          (lt,":rp",100),
          (str_store_troop_name,s59,":e_js"),
          (display_message,"@success2"),
          (assign,":num",0),
          (try_for_agents,":agents"),
            (agent_is_ally,":agents"),
            (agent_is_alive,":agents"),
            (agent_is_human,":agents"),
            (agent_get_look_position,pos2,":agents"),  
            (get_distance_between_positions,":dist",pos40,pos2),
            (lt,":dist",5000),
            (store_random_in_range,":rp",0,100),
            (val_add,":rp",":t_rp"),
            (lt, ":rp", 100),
            (copy_position,pos50,pos62),
            (store_random_in_range,":x_pos",-100,101),
            (val_mul,":x_pos",100),
            (position_set_x,pos50,":x_pos"),
            (agent_set_scripted_destination,":agents",pos50),
            (agent_set_speed_limit,":agents", 11),
            (val_add,":num",1),
          (try_end),
          (try_begin),
            (gt,":num",0),
            (assign,reg60,":num"),
            (display_message,"@success2_1"),
          (else_try),
            (str_store_troop_name,s59,":e_js"),
            (display_message,"@failure1"),
          (try_end),
        (else_try),
          (get_player_agent_no,":player"), 
          (agent_get_look_position,pos1,":player"),
          (assign,":cur_num",0),
          (try_for_agents,":agents"),
            (neg|agent_is_ally,":agents"),
            (agent_is_alive,":agents"),
            (agent_is_human,":agents"),
            (agent_get_look_position,pos2,":agents"),  
            (get_distance_between_positions,":dist",pos1,pos2),
            (lt,":dist",":b_dist"),
            (store_random_in_range,":rp",0,100),
            (val_add,":rp",":t_rp"),
            (ge, ":rp", 100),
            (copy_position,pos50,pos63),
            (store_random_in_range,":x_pos",-100,101),
            (val_mul,":x_pos",100),
            (position_set_x,pos50,":x_pos"),
            (agent_set_scripted_destination,":agents",pos50),
            (agent_set_speed_limit,":agents", 11),
            (val_add,":cur_num",1),
          (try_end),
          (try_begin),
            (gt,":cur_num",0),
            (assign,reg60,":cur_num"),
            (display_message,"str_success1"),
          (else_try),
            (display_message,"str_failure"),
          (try_end),
        (try_end),
     ]),
   #Xianjing
  ("sg_xian_jing",
    [
        (val_sub,"$max_st",1),
        (val_sub,"$xj_use_count",1),
        (try_begin),
          (lt,"$xj_use_count",1),
          (assign, "$can_use_xj", 3),
        (try_end),

        (get_player_agent_no,":player"), 
        (agent_get_look_position,pos1,":player"),
        (position_move_y,pos1,4000), 
        (store_random_in_range,":rp",0,100),
        (store_skill_level,":st",skl_stratagem,"trp_player"),
        (store_mul,":dm",":st",5),#3
        (store_mul,":b_dist",":st",160),
        (try_begin),
          (eq,"$xianjing",1),
          (val_add,":b_dist",200),
        (else_try),
          (eq,"$xianjing",2),
          (val_add,":b_dist",400),
        (try_end),
        (val_add,":b_dist",800),
        (val_mul,":st",5),
        (store_attribute_level,":int","trp_player",ca_intelligence),
        (val_mul,":int",2),
        (store_add,":p_rp",":int",":st"),
        (val_add,":p_rp","$c_rp"),
        (try_begin),
          (eq,"$xianjing",1),
          (val_add,":p_rp",10),
        (else_try),
          (eq,"$xianjing",2),
          (val_add,":p_rp",20),
        (try_end),

        (assign,":e_rp",0),#
        (try_for_agents,":agents"), 
           (neg|agent_is_ally,":agents"),
           (agent_is_alive,":agents"),
           (agent_get_troop_id,":agent",":agents"),
           (troop_is_hero,":agent"),
           (store_skill_level,":e_st",skl_stratagem,":agent"),
           (store_attribute_level,":e_int",":agent",ca_intelligence),
           (val_mul,":e_st",5),
           (val_mul,":e_int",2),
           (store_add,":he",":e_int",":e_st"),#
           (gt,":he",":e_rp"),#
           (assign,":e_rp",":he"),#
        (try_end),

        (store_sub,":t_rp",":p_rp",":e_rp"),
        (val_add,":rp",":t_rp"),
        (try_begin),
          (eq, "$current_terrain",2),
          (val_add,":rp",30),
        (else_try),
          (eq, "$current_terrain",3),
          (val_add,":rp",10),
        (try_end),
        (try_begin),
          (ge,":rp",100),
          (display_message,"str_success"),
          (try_for_agents,":agents"),
            (agent_get_look_position,pos2,":agents"),  
            (get_distance_between_positions,":dist",pos1,pos2),
            (lt,":dist",":b_dist"),
            (store_agent_hit_points,":hp",":agents",1),
            (try_begin),
              (neg|agent_is_human,":agents"),
              (assign,":hp",0),
            (else_try),
              (val_sub,":hp",":dm"),
              (agent_set_animation, ":agents", 284),
            (try_end),
            (agent_set_hit_points,":agents",":hp",1),
            (lt,":hp",1),
            (set_show_messages, 0),
            (agent_deliver_damage_to_agent,":player",":agents"),
            (set_show_messages, 1),
          (try_end),
          (play_sound, "snd_explosion1"),
          (position_set_z_to_ground_level, pos1),
          (particle_system_burst, "psys_war_smoke", pos1, 10),
          (position_move_y,pos1,2000),
          (particle_system_burst, "psys_war_smoke", pos1, 10),
          (position_move_x,pos1,2000),
          (particle_system_burst, "psys_war_smoke", pos1, 10),
          (position_move_x,pos1,-4000),
          (particle_system_burst, "psys_war_smoke", pos1, 10),
          (position_move_y,pos1,-2000),
          (particle_system_burst, "psys_war_smoke", pos1, 10),
          (position_move_y,pos1,-2000),
          (particle_system_burst, "psys_war_smoke", pos1, 10),
          (position_move_x,pos1,2000),
          (particle_system_burst, "psys_war_smoke", pos1, 10),
          (position_move_x,pos1,2000),
          (particle_system_burst, "psys_war_smoke", pos1, 10),
          (position_move_y,pos1,2000),
          (particle_system_burst, "psys_war_smoke", pos1, 10),
        (else_try),
          (display_message,"str_failure"),
        (end_try),
     ]),

 ## AI st ##
   #AI hunluan
  ("sg_hun_luan_ai",
    [
         (store_script_param_1, ":agent_no"),

         (agent_get_look_position,pos40,":agent_no"),
         (agent_get_troop_id,":troop_no",":agent_no"),
         (try_begin),#lianhuan
           (this_or_next|eq,":troop_no","trp_zhugeliang"),
           (this_or_next|eq,":troop_no","trp_pangtong"),
           (this_or_next|eq,":troop_no","trp_guojia"),
           (eq,":troop_no","trp_zhouyu"),
           (troop_set_slot,":troop_no", slot_use_st,0),
         (try_end),

         (store_skill_level,":e_st",skl_stratagem,":troop_no"),
         (store_attribute_level,":e_int",":troop_no",ca_intelligence),
         (store_mul,":b_dist",":e_st",650),
         (val_mul,":e_st",6),
         (val_mul,":e_int",2),
         (store_add,":e_rp",":e_int",":e_st"),

         (store_skill_level,":st",skl_stratagem,"trp_player"),
         (store_attribute_level,":int","trp_player",ca_intelligence),
         (val_mul,":st",5),
         (val_mul,":int",2),
         (store_add,":p_rp",":int",":st"),
         (try_begin),
           (eq,"$hunluan",1),
           (val_add,":p_rp",5),
         (else_try),
           (eq,"$hunluan",2),
           (val_add,":p_rp",10),
         (try_end),
         (val_add,":p_rp","$c_rp"),

         (store_sub,":t_rp",":e_rp",":p_rp"),

         (assign,":num",0),
         (try_for_agents,":agents"),
            (agent_is_ally,":agents"),
            (agent_is_alive,":agents"),
            (agent_is_human,":agents"),
            (agent_get_position,pos2,":agents"),  
            (get_distance_between_positions,":dist",pos40,pos2),
            (lt,":dist",":b_dist"),
            (store_random_in_range,":rp",0,100),
            (val_add,":rp",":t_rp"),
            (ge, ":rp", 100),
            (copy_position,pos50,pos62),
            (store_random_in_range,":x_pos",-100,101),
            (val_mul,":x_pos",100),
            (position_set_x,pos50,":x_pos"),
            (agent_set_scripted_destination,":agents",pos50),
            (agent_set_speed_limit,":agents", 12),
            (val_add,":num",1),
         (try_end),

         (try_begin),
            (gt,":num",0),
            (assign,reg60,":num"),
            (display_message,"@success2_1"),
         (else_try),
            (str_store_troop_name,s59,":troop_no"),
            (display_message,"@failure1"),
         (try_end),
     ]),

    #AI lijian
  ("sg_li_jian_ai",
    [
        (store_script_param_1, ":agent_no"),

        (agent_get_look_position,pos40,":agent_no"),
        (agent_get_troop_id,":troop_no",":agent_no"),
        (try_begin),#lianhuan
          (this_or_next|eq,":troop_no","trp_guojia"),
          (eq,":troop_no","trp_zhouyu"),
          (troop_set_slot,":troop_no", slot_use_st,0),
        (try_end),

        (store_skill_level,":e_st",skl_stratagem,":troop_no"),
        (store_mul,":b_dist",":e_st",550),
        (val_mul,":e_st",4),
        (store_attribute_level,":e_int",":troop_no",ca_intelligence),
        (store_add,":e_rp",":e_int",":e_st"),

        (store_skill_level,":st",skl_stratagem,"trp_player"),
        (store_attribute_level,":int","trp_player",ca_intelligence),
        (val_mul,":st",3),
        (store_add,":p_rp",":int",":st"),
        (try_begin),
          (eq,"$lijian",1),
          (val_add,":p_rp",10),
        (else_try),
          (eq,"$lijian",2),
          (val_add,":p_rp",20),
        (try_end),
        (val_add,":p_rp","$c_rp"),

        (store_sub,":t_rp",":e_rp",":p_rp"),
        (val_sub,":t_rp","$num_ae"),

        (get_player_agent_no,":player"), 
        (agent_get_team,":i_team",":player"),
        (store_sub,":e_team",1,":i_team"),
        (assign,":num",0),
        (try_for_agents,":cur_agent"),
          (agent_is_ally,":cur_agent"),
          (neq,":cur_agent",":player"), 
          (agent_is_alive,":cur_agent"),
          (agent_is_human,":cur_agent"),
          (agent_get_position,pos2,":cur_agent"),  
          (get_distance_between_positions,":dist",pos40,pos2),
          (lt,":dist",":b_dist"),
          (store_random_in_range,":rp",0,100),
          (val_add,":rp",":t_rp"),
          (ge,":rp",100),
          (agent_set_team,":cur_agent",":e_team"),
          (val_add,":num",1),
        (try_end),
        (try_begin),
          (gt,":num",0),
          (assign,reg60,":num"),
          (display_message,"@success2_1"),
        (else_try),
          (str_store_troop_name,s59,":troop_no"),
          (display_message,"@failure1"),
        (try_end),
     ]),

   #AI huoji
  ("sg_huo_ji_ai",
    [
        (store_script_param_1, ":agent_no"),

        (agent_get_troop_id,":troop_no",":agent_no"),
        (try_begin),#lianhuan
          (this_or_next|eq,":troop_no","trp_zhugeliang"),
          (eq,":troop_no","trp_zhouyu"),
          (troop_set_slot,":troop_no", slot_use_st,0),
        (try_end),

        (store_skill_level,":e_st",skl_stratagem,":troop_no"),
        (store_attribute_level,":e_int",":troop_no",ca_intelligence),
        (store_mul,":b_dist",":e_st",500),
        (store_mul,":dm_max",":e_st",7),
        (store_random_in_range,":dm",40,":dm_max"),
        (val_mul,":e_st",6),
        (val_mul,":e_int",2),
        (store_add,":e_rp",":e_int",":e_st"),

        (store_skill_level,":st",skl_stratagem,"trp_player"),
        (store_attribute_level,":int","trp_player",ca_intelligence),
        (val_mul,":st",5),
        (val_mul,":int",2),
        (store_add,":p_rp",":int",":st"),
        (try_begin),
          (eq,"$huoji",1),
          (val_add,":p_rp",10),
        (else_try),
          (eq,"$huoji",2),
          (val_add,":p_rp",20),
        (try_end),
        (val_add,":p_rp","$c_rp"),

        (store_sub,":t_rp",":e_rp",":p_rp"),

        (store_random_in_range,":rp",0,100),
        (val_add,":rp",":t_rp"),

        (try_begin),
          (eq, "$current_terrain",1),
          (val_sub,":rp",20),
        (else_try),
          (eq, "$current_terrain",2),
          (val_add,":rp",20),
        (try_end),

        (try_begin),
          (ge,":rp",100),#100
          (get_player_agent_no,":player"), 
          (try_for_agents,":agents"),
            (agent_get_look_position,pos2,":agents"),  
            (get_distance_between_positions,":dist",pos47,pos2),
            (lt,":dist",":b_dist"),
            (store_agent_hit_points,":hp",":agents",1),
            (val_sub,":hp",":dm"),
            (try_begin),
               (eq,":agents",":player"), 
#               (store_div,":half_dm",":dm",2),
               (val_add,":hp",10),
            (try_end),
            (agent_set_hit_points,":agents",":hp",1),
            (agent_set_animation, ":agents", 284),
            (lt,":hp",1),
            (agent_deliver_damage_to_agent,":agent_no",":agents"),
          (try_end),
          (play_sound, "snd_fire_burning"),
          (position_set_z_to_ground_level, pos47),
          (particle_system_burst, "psys_massive_fire", pos47, 50),
          (particle_system_burst, "psys_war_smoke", pos47, 30),
          (position_move_y,pos47,2000),
          (particle_system_burst, "psys_massive_fire", pos47, 50),
          (particle_system_burst, "psys_war_smoke", pos47, 30),
          (position_move_x,pos47,2000),
          (particle_system_burst, "psys_massive_fire", pos47, 50),
          (particle_system_burst, "psys_war_smoke", pos47, 30),
          (position_move_x,pos47,-4000),
          (particle_system_burst, "psys_massive_fire", pos47, 50),
          (particle_system_burst, "psys_war_smoke", pos47, 30),
          (position_move_y,pos47,-2000),
          (particle_system_burst, "psys_massive_fire", pos47, 50),
          (particle_system_burst, "psys_war_smoke", pos47, 30),
          (position_move_y,pos47,-2000),
          (particle_system_burst, "psys_massive_fire", pos47, 50),
          (particle_system_burst, "psys_war_smoke", pos47, 30),
          (position_move_x,pos47,2000),
          (particle_system_burst, "psys_massive_fire", pos47, 50),
          (particle_system_burst, "psys_war_smoke", pos47, 30),
          (position_move_x,pos47,2000),
          (particle_system_burst, "psys_massive_fire", pos47, 50),
          (particle_system_burst, "psys_war_smoke", pos47, 30),
          (position_move_y,pos47,2000),
          (particle_system_burst, "psys_massive_fire", pos47, 30),
          (particle_system_burst, "psys_war_smoke", pos47, 30),
        (else_try),
          (str_store_troop_name,s59,":troop_no"),
          (display_message,"@failure1"),
        (end_try),
     ]),

    #AI qixi
  ("sg_qi_xi_ai",
    [
        (store_script_param_1, ":agent_no"),

        (agent_get_troop_id,":troop_no",":agent_no"),
        (try_begin),#lianhuan
          (this_or_next|eq,":troop_no","trp_zhugeliang"),
          (eq,":troop_no","trp_pangtong"),
          (troop_set_slot,":troop_no", slot_use_st,0),
        (try_end),

        (store_skill_level,":e_st",skl_stratagem,":troop_no"),
        (val_mul,":e_st",5),
        (store_attribute_level,":e_int",":troop_no",ca_intelligence),
        (val_mul,":e_int",2),
        (store_add,":e_rp",":e_int",":e_st"),

        (store_skill_level,":st",skl_stratagem,"trp_player"),
        (store_attribute_level,":int","trp_player",ca_intelligence),
        (val_mul,":st",5),
        (val_mul,":int",2),
        (store_add,":p_rp",":int",":st"),
        (try_begin),
          (eq,"$qixi",1),
          (val_add,":p_rp",10),
        (else_try),
          (eq,"$qixi",2),
          (val_add,":p_rp",20),
        (try_end),
        (val_add,":p_rp","$c_rp"),

        (store_sub,":t_rp",":e_rp",":p_rp"),

        (store_random_in_range,":rp",0,100),
        (val_add,":rp",":t_rp"),
        (try_begin),
          (ge,":rp",100),
          (agent_get_team,":e_team",":agent_no"),
          (assign,":dist",999999),
          (get_player_agent_no,":player"), 
          (agent_get_position,pos2,":player"), 
          (try_begin),
            (eq, ":e_team", 1),
            (try_begin),
              (entry_point_get_position,pos49,1),
              (get_distance_between_positions,":cur_dist",pos49,pos2),
              (lt,":cur_dist",":dist"),
              (assign,":dist",":cur_dist"),
              (assign,":entry",4),
            (try_end),
            (try_begin),
              (entry_point_get_position,pos49,2),
              (get_distance_between_positions,":cur_dist",pos49,pos2),
              (lt,":cur_dist",":dist"),
              (assign,":dist",":cur_dist"),
              (assign,":entry",6),
            (try_end),
            (try_begin),
              (entry_point_get_position,pos49,5),
              (get_distance_between_positions,":cur_dist",pos49,pos2),
              (lt,":cur_dist",":dist"),
              (assign,":entry",8),
            (try_end),
            (add_reinforcements_to_entry,":entry",7),
          (else_try),
            (try_begin),
              (entry_point_get_position,pos49,4),
              (get_distance_between_positions,":cur_dist",pos49,pos2),
              (lt,":cur_dist",":dist"),
              (assign,":dist",":cur_dist"),
              (assign,":entry",5),
            (try_end),
            (try_begin),
              (entry_point_get_position,pos49,2),
              (get_distance_between_positions,":cur_dist",pos49,pos2),
              (lt,":cur_dist",":dist"),
              (assign,":dist",":cur_dist"),
              (assign,":entry",7),
            (try_end),
            (try_begin),
              (entry_point_get_position,pos49,5),
              (get_distance_between_positions,":cur_dist",pos49,pos2),
              (lt,":cur_dist",":dist"),
              (assign,":dist",":cur_dist"),
              (assign,":entry",9),
            (try_end),
            (add_reinforcements_to_entry,":entry",7),
          (try_end),
        (else_try),
          (str_store_troop_name,s59,":troop_no"),
          (display_message,"@failure1"),
        (try_end),
        (team_give_order, "$ai_team", grc_cavalry, mordr_charge),##?
     ]),


#SANGO NEW
("wounded",
   [
      (store_script_param_1, ":party"), 
      (party_get_num_companion_stacks, ":num_stacks",":party"),
      (assign, reg0, 0),
      (try_for_range, ":i_stack", 0, ":num_stacks"),
        (party_stack_get_troop_id,     ":stack_troop",":party",":i_stack"),
        (neg|troop_is_hero, ":stack_troop"),
        (party_stack_get_size,         ":stack_size",":party",":i_stack"),
        (party_stack_get_num_wounded, ":num_wounded",":party",":i_stack"),
        (val_sub, ":stack_size", ":num_wounded"),
        (val_add, reg0, ":stack_size"),
      (try_end),
    ]),
("remove_war_party",[
(try_for_parties,reg11),
  (party_get_template_id,reg12,reg11),
  (try_begin),
     (this_or_next|eq,reg12,"pt_wei_war_party"),
     (this_or_next|eq,reg12,"pt_shu_war_party"),
     (eq,reg12,"pt_wu_war_party"),
     (remove_party,reg11),
  (try_end),
(try_end)]),

("move_party",[
(try_for_parties,reg11),
(party_get_template_id,reg12,reg11),
(store_faction_of_party,"$party_faction",reg11),
(try_begin),
(eq,"$party_faction","fac_kingdom_caowei"),
(neq,reg12,"pt_wei_war_party"),
(neq,reg12,"pt_wei_caravan"),
(neq,reg12,"pt_wei_gongcheng"),
(assign,"$move_party",reg12),
(else_try),
(eq,"$party_faction","fac_kingdom_shuhan"),
(neq,reg12,"pt_shu_war_party"),
(neq,reg12,"pt_shu_caravan"),
(neq,reg12,"pt_shu_gongcheng"),
(assign,"$move_party",reg12),
(else_try),
(eq,"$party_faction","fac_kingdom_wu"),
(neq,reg12,"pt_wu_war_party"),
(neq,reg12,"pt_wu_caravan"),
(neq,reg12,"pt_wu_gongcheng"),
(assign,"$move_party",reg12),
(try_end),
(party_set_ai_behavior,"$move_party",ai_bhvr_patrol_party),        
(party_set_ai_object,"$move_party","p_castle_4")]),
]

from ss_basic_linker import *
#ss_basic_scripts_exec()
ss_add_to_object(scripts,ss_basic_init_scripts)
