# -*- coding: cp1254 -*-
from header_common import *
from header_operations import *
from module_constants 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_music import *
from ID_animations import *
####################################################################################################################################
# LAV MODIFICATIONS START (COMPANIONS OVERSEER MOD)
####################################################################################################################################
from header_presentations import *
####################################################################################################################################
# LAV MODIFICATIONS END (COMPANIONS OVERSEER MOD)
####################################################################################################################################

# Josef v586 - kt0's autoresolve code 
import string
from process_common import *
from module_troops import *
from module_items import *

# pulls the gigantor values out of the skill blob and returns a 3-tuple
# containing power draw, power strike, and power draw skill values.
def kt_get_power_skills( flags ):
   pdraw = 0
   pstrk = 0
   pthrw = 0
   pdraw_top = knows_power_draw_10 + knows_power_draw_5
   pstrk_top = knows_power_strike_10 + knows_power_strike_5
   pthrw_top = knows_power_throw_10 + knows_power_throw_5
   
   if ( flags & pdraw_top ) > 0:
      pdraw = flags & pdraw_top
      pdraw /= knows_power_draw_1
   if ( flags & pstrk_top ) > 0:
      pstrk = flags & pstrk_top
      pstrk /= knows_power_strike_1
   if ( flags & pthrw_top ) > 0:
      pthrw = flags & pthrw_top
      pthrw /= knows_power_throw_1
   
   return (pdraw, pstrk, pthrw)

# pulls the gigantor values out of the skill blob and returns a 3-tuple
# containing shield, athletics, and ironflesh skill values.
def kt_get_melee_skills( flags ):
   shld = 0
   athl = 0
   irfl = 0
   shld_top = knows_shield_10 + knows_shield_5
   athl_top = knows_athletics_10 + knows_athletics_5
   irfl_top = knows_ironflesh_10 + knows_ironflesh_5
   
   if ( flags & shld_top ) > 0:
      shld = flags & shld_top
      shld /= knows_shield_1
   if ( flags & athl_top ) > 0:
      athl = flags & athl_top
      athl /= knows_athletics_1
   if ( flags & irfl_top ) > 0:
      irfl = flags & irfl_top
      irfl /= knows_ironflesh_1
   
   return (shld, athl, irfl)

# parse troop items and return a tuple containing average item values. 
# we make assumptions on the flags and average gear of the same type
# to get aggregate values.  note that the weights given to items in a
# list that aren't guaranteed with a tf_ flag are a guess.  i'm counting
# no flag as a 0 value in the average which might not be correct.
def kt_parse_troop_items( item_list, flags, ohprof, thprof, poleprof, bowprof, xbowprof, throwprof, pstrike, pdraw, pthrow ):
   mw_value = 0 # melee weapon damage of the greater if multiple
   mw_count = 0 # never seen a guy without a weapon O_O
   rw_value = 0 # ranged weapon damage
   rw_count = 1
   ha_value = 0 # head armor
   ha_count = 1
   ba_value = 0 # body armor
   ba_count = 1
   fa_value = 0 # foot armor
   fa_count = 1
   na_value = 0 # hand armor
   na_count = 1
   sh_value = 0 # shield percentage 0-100
   sh_count = 1
   ho_value = 0 # horse aggregate charge and armor value
   ho_count = 1

   guarantee_horse = 0
   guarantee_ranged = 0
   troop_type = kt_troop_type_footsoldier

   # parse guarantee flags
   if ( flags & tf_guarantee_boots ) > 0:
      fa_count = 0
   if ( flags & tf_guarantee_armor ) > 0:
      ba_count = 0
   if ( flags & tf_guarantee_helmet ) > 0:
      ha_count = 0
   if ( flags & tf_guarantee_horse ) > 0:
      ho_count = 0
      guarantee_horse = 1
   if ( flags & tf_guarantee_shield ) > 0:
      sh_count = 0
   if ( flags & tf_guarantee_ranged ) > 0:
      rw_count = 0
      guarantee_ranged = 1
   #print "Guarantees: ", guarantee_horse, guarantee_ranged # pete
   # divine the troop type from the guarantee flags.  this isn't 100%.
   if guarantee_horse and guarantee_ranged:
      troop_type = kt_troop_type_mtdarcher
   elif guarantee_horse and not guarantee_ranged:
      troop_type = kt_troop_type_cavalry
   elif not guarantee_horse and guarantee_ranged:
      troop_type = kt_troop_type_archer
   else:
      troop_type = kt_troop_type_footsoldier
   
   # constants
   pierce_flag = pierce << iwf_damage_type_bits
   blunt_flag = blunt << iwf_damage_type_bits

   # parse each item
   # once we know the type, we pull the values from the appropriate places.
   # if we don't know the type, we ignore the item.  we also ignore ammo
   # and books and a handful of other things intentionally.
   for item in item_list:
      item_type = items[item][3] & 0xFF
      if itp_type_horse == item_type:
         ho_count += 1
         chg = get_thrust_damage( items[item][6] )
         arm = get_body_armor( items[item][6] )
         ho_value += chg
         ho_value += (arm+5)/10
      # we only consider the higher of thrust or swing damage
      elif item_type in (itp_type_one_handed_wpn, itp_type_two_handed_wpn, itp_type_polearm):
         mw_count += 1
         swd = get_swing_damage( items[item][6] )
         thd = get_thrust_damage( items[item][6] )
         speed = get_speed_rating( items[item][6] )
         if (swd & pierce_flag) > 0:
            swd &= 0xFF
            swd *= 3
            swd /= 2
         elif (swd & blunt_flag) > 0:
            swd &= 0xFF
            swd *= 5
            swd /= 4
         if (thd & pierce_flag) > 0:
            thd &= 0xFF
            thd *= 3
            thd /= 2
         elif (thd & blunt_flag) > 0:
            thd &= 0xFF
            thd *= 5
            thd /= 4
         # also modify by speed rating and proficiency
         prof = 100
         if item_type == itp_type_one_handed_wpn:
            prof = ohprof
         elif item_type == itp_type_two_handed_wpn:
            prof = thprof
         elif item_type == itp_type_polearm:
            prof = poleprof            
         swd *= speed
         swd *= prof
         thd *= speed
         thd *= prof
         if pstrike > 0:
            swd *= (100 + pstrike * 8)
            swd /= 100
            thd *= (100 + pstrike * 8)
            thd /= 100
         swd /= 10000
         thd /= 10000
         if swd > thd:
            mw_value += swd
         else:
            mw_value += thd
      elif item_type in (itp_type_bow, itp_type_crossbow, itp_type_thrown):
         rw_count += 1
         rdam = get_thrust_damage( items[item][6] )
         # adjust for type
         if (rdam & pierce_flag) > 0:
            rdam &= 0xFF
            rdam *= 3
            rdam /= 2
         elif (rdam & blunt_flag) > 0:
            rdam &= 0xFF
            rdam *= 5
            rdam /= 4
         # adjust for speed and accuracy
         acc = get_leg_armor( items[item][6] )
         spd = get_speed_rating( items[item][6] )
         if acc == 0:
            acc = 100
         rdam *= acc
         rdam *= spd
         # adjust for proficiency
         if item_type == itp_type_bow:
            rdam *= bowprof
            if pdraw > 0:
               pdraw_amt = get_difficulty( items[item][6] )
               pdraw_amt += 4
               if pdraw < pdraw_amt:
                  pdraw_amt = pdraw
               rdam *= (100 + pdraw_amt*14)
               rdam /= 100
         elif item_type == itp_type_crossbow:
            rdam *= xbowprof
         elif item_type == itp_type_thrown:
            rdam *= throwprof
            if pthrow > 0:
               rdam *= (100 + pthrow*10)
               rdam /= 100
         rdam /= 1000000
         rw_value += rdam
      elif itp_type_shield == item_type:
         sh_count += 1
         sh_value += get_weapon_length( items[item][6] )
      elif item_type in (itp_type_head_armor, itp_type_body_armor, itp_type_foot_armor, itp_type_hand_armor):
         if itp_type_head_armor == item_type:            
            ha_count += 1
         elif itp_type_body_armor == item_type:
            ba_count += 1
         elif itp_type_foot_armor == item_type:
            fa_count += 1
         elif itp_type_hand_armor == item_type:
            na_count += 1
            na_value += get_body_armor( items[item][6] )
         else:
            print "ERROR:  item ", items[item][0], " is unknown armor type!" # shouldn't ever get this
         ba_value += get_body_armor( items[item][6] )
         fa_value += get_leg_armor( items[item][6] )
         ha_value += get_head_armor( items[item][6] )

   # do the averaging; values will be rough
   if ba_count > 0:   # nb:  this doesn't catch no body armor + gloves case
      ba_value -= na_value
      ba_value /= ba_count
      if na_count > 0:
         na_value /= na_count
      ba_value += na_value
   if ha_count > 0:
      ha_value /= ha_count
   if fa_count > 0:
      fa_value /= fa_count
   if mw_count > 0:
      mw_value /= mw_count
   if rw_count > 0:
      rw_value /= rw_count
   if sh_count > 0:
      sh_value /= sh_count
   if ho_count > 0:
      ho_value /= ho_count

   return (mw_value, rw_value, ha_value, ba_value, fa_value, sh_value, ho_value, troop_type)

# generates code tuples for setting slots based on values accessible
# during compile.  this gets inserted into the scripts array and parsed
# like any other module code. 
def kt_python_init_troop_slots():
   module_code = []
   
   # figure out our bounds
   underscore_pos = string.find( soldiers_begin, "_" )
   id_str = soldiers_begin[ underscore_pos+1:len(soldiers_begin) ]
   begin_troop = find_troop( troops, id_str )
   underscore_pos = string.find( soldiers_begin, "_" )
   id_str = soldiers_end[ underscore_pos+1 : len(soldiers_end) ]   
   end_troop = find_troop( troops, id_str )
   
      
   # process for each troop
   for i_troop in range(begin_troop, end_troop+1):
      oneh_prof = (troops[i_troop][9] >> one_handed_bits) & 0x3FF
	  
      twoh_prof = (troops[i_troop][9] >> two_handed_bits) & 0x3FF
      pole_prof = (troops[i_troop][9] >> polearm_bits) & 0x3FF
      arch_prof = (troops[i_troop][9] >> archery_bits) & 0x3FF
      xbow_prof = (troops[i_troop][9] >> crossbow_bits) & 0x3FF
      thrw_prof = (troops[i_troop][9] >> throwing_bits) & 0x3FF
      att_str = (troops[i_troop][8] & 0xFF)
      att_agi = (troops[i_troop][8] & 0xFF00) >> 8
      att_int = (troops[i_troop][8] & 0xFF0000) >> 16
      att_cha = (troops[i_troop][8] & 0xFF000000) >> 24
      # setup special skills (add whatever you care about here as well)
      (skill_pdraw, skill_pstrike, skill_pthrow) = kt_get_power_skills( troops[i_troop][10] )
      (skill_shld, skill_athl, skill_irfl) = kt_get_melee_skills( troops[i_troop][10] )
      mw_value = 0
      rw_value = 0
      ha_value = 0
      ba_value = 0
      fa_value = 0
      sh_value = 0
      ho_value = 0
      troop_type = 0
      (mw_value, rw_value, ha_value, ba_value, fa_value, sh_value, ho_value, troop_type) = kt_parse_troop_items( troops[i_troop][7], troops[i_troop][3], oneh_prof, twoh_prof, pole_prof, arch_prof, xbow_prof, thrw_prof, skill_pstrike, skill_pdraw, skill_pthrow )
      d_val = ha_value + ba_value + fa_value + sh_value
      d_val /= 5
      d_val += skill_irfl*2
      d_val += att_str
      if troop_type in (kt_troop_type_mtdarcher, kt_troop_type_archer):
         o_val = mw_value / 3 + rw_value
      if troop_type in (kt_troop_type_footsoldier, kt_troop_type_cavalry):
         o_val = mw_value + rw_value / 4
      h_val = ho_value
      module_code.append( (troop_set_slot, "trp_"+troops[i_troop][0], kt_slot_troop_o_val, o_val) )
      module_code.append( (troop_set_slot, "trp_"+troops[i_troop][0], kt_slot_troop_d_val, d_val) )
      module_code.append( (troop_set_slot, "trp_"+troops[i_troop][0], kt_slot_troop_h_val, h_val) )
      module_code.append( (troop_set_slot, "trp_"+troops[i_troop][0], kt_slot_troop_type, troop_type) )	  
		 
      #print "Troop: ", troops[i_troop][0], o_val, d_val, h_val, troop_type, " O,Type"  
	  #print "Troop: ", troops[i_troop][0], o_val, d_val, h_val, troop_type, " O,Type" 
      #print "Troop: ", troops[i_troop][0], mw_value, rw_value, ha_value, ba_value, fa_value, sh_value, ho_value, troop_type
      #print "Troop: ", troops[i_troop][0], d_val, oneh_prof, " is defence factor, 1h proficiency" 	
      #print "Troop: ", troops[i_troop][0], h_val, " is horseyness factor" 
	  

      old_val = troops[i_troop][8]
      old_val >>= level_bits
      old_val &= level_mask
      old_val += 12
      old_val *= old_val
      old_val /= 100
      troop_string = "footsoldier"
      if troop_type == kt_troop_type_cavalry:
         troop_string = "cavalry"
      if troop_type == kt_troop_type_archer:
         troop_string = "archer"
      if troop_type == kt_troop_type_mtdarcher:
         troop_string = "mtdarcher"
     
      #print "Troop: ", troops[i_troop][0], kt_slot_troop_o_val, o_val, troop_string, " is offence factor" # shouldn't ever get this	
	  
   return module_code[:]
   
# end kt0
####################################################################################################################
# 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 = [


  #script_game_start:
  # This script is called when a new game is started
  # INPUT: none
  ("game_start",
   [

      # Version checks
      (assign, "$mod_version_initialized", 1),
      (assign, "$mod_version", PATCH_VERSION * 256 + PATCH_SUBVERSION),

      (faction_set_slot, "fac_player_supporters_faction", slot_faction_state, sfs_inactive),
      (assign, "$g_player_luck", 200),
      (assign, "$g_player_luck", 200),
      (troop_set_slot, "trp_player", slot_troop_occupation, slto_kingdom_hero),
	  # NE dk
	  (troop_set_slot, "trp_dark_knight_lord", slot_troop_leaded_party, -1),
      (troop_set_slot, "trp_dark_knight_lord1", slot_troop_leaded_party, -1),
      (troop_set_slot, "trp_dark_knight_lord2", slot_troop_leaded_party, -1),
      (troop_set_slot, "trp_dark_knight_lord3", slot_troop_leaded_party, -1),
      (troop_set_slot, "trp_dark_knight_lord4", slot_troop_leaded_party, -1),
	  (party_set_faction,"p_main_party","fac_player_faction"), #This is a bug fix for a bug that sometimes does and sometimes does not show up - Jinnai
    
	  # end NE dk
      (store_random_in_range, ":starting_training_ground", training_grounds_begin, training_grounds_end),
      (party_relocate_near_party, "p_main_party", ":starting_training_ground", 3),
      (str_store_troop_name, s5, "trp_player"),
      (party_set_name, "p_main_party", s5),
      (call_script, "script_update_party_creation_random_limits"),
      (assign, "$g_player_party_icon", -1),
	  
	  #Warband changes begin -- set this early 
	  (try_for_range, ":npc", 0, kingdom_ladies_end),
	    (this_or_next|eq, ":npc", "trp_player"),
		(is_between, ":npc", active_npcs_begin, kingdom_ladies_end),
		(troop_set_slot, ":npc", slot_troop_father, -1),
		(troop_set_slot, ":npc", slot_troop_mother, -1),
		(troop_set_slot, ":npc", slot_troop_guardian, -1),
		(troop_set_slot, ":npc", slot_troop_spouse, -1),
		(troop_set_slot, ":npc", slot_troop_betrothed, -1),
        (troop_set_slot, ":npc", slot_troop_prisoner_of_party, -1),		
        (troop_set_slot, ":npc", slot_lady_last_suitor, -1),		
        (troop_set_slot, ":npc", slot_troop_stance_on_faction_issue, -1),		
		
		(store_random_in_range, ":decision_seed", 0, 10000),
        (troop_set_slot, ":npc", slot_troop_set_decision_seed, ":decision_seed"),	#currently not used
        (troop_set_slot, ":npc", slot_troop_temp_decision_seed, ":decision_seed"),	#currently not used, holds for at least 24 hours			
	  (try_end),

	  (assign, "$g_lord_long_term_count", 0),

	  (call_script, "script_initialize_banner_info"),
	  (call_script, "script_initialize_item_info"),
	  (call_script, "script_initialize_aristocracy"),
      (call_script, "script_initialize_npcs"),
      (assign, "$disable_npc_complaints", 0),
      #NPC companion changes end
      
      # Setting random feast time
      (try_for_range, ":faction_no", kingdoms_begin, kingdoms_end),
        (store_random_in_range, ":last_feast_time", 0, 312), #240 + 72
        (val_mul, ":last_feast_time", -1),
        (faction_set_slot, ":faction_no", slot_faction_last_feast_start_time, ":last_feast_time"),
      (try_end),
      
      # 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_swadian_recruit"),
      # (faction_set_slot, "fac_culture_1",  slot_faction_tier_2_troop, "trp_swadian_militia"),
      # (faction_set_slot, "fac_culture_1",  slot_faction_tier_3_troop, "trp_swadian_footman"),
      # (faction_set_slot, "fac_culture_1",  slot_faction_tier_4_troop, "trp_swadian_infantry"),
      # (faction_set_slot, "fac_culture_1",  slot_faction_tier_5_troop, "trp_swadian_knight"),

      # (faction_set_slot, "fac_culture_2", slot_faction_tier_1_troop, "trp_vaegir_recruit"),
      # (faction_set_slot, "fac_culture_2", slot_faction_tier_2_troop, "trp_vaegir_footman"),
      # (faction_set_slot, "fac_culture_2", slot_faction_tier_3_troop, "trp_vaegir_veteran"),
      # (faction_set_slot, "fac_culture_2", slot_faction_tier_4_troop, "trp_vaegir_infantry"),
      # (faction_set_slot, "fac_culture_2", slot_faction_tier_5_troop, "trp_vaegir_knight"),

      # (faction_set_slot, "fac_culture_3", slot_faction_tier_1_troop, "trp_khergit_tribesman"),
      # (faction_set_slot, "fac_culture_3", slot_faction_tier_2_troop, "trp_khergit_skirmisher"),
      # (faction_set_slot, "fac_culture_3", slot_faction_tier_3_troop, "trp_khergit_horseman"),
      # (faction_set_slot, "fac_culture_3", slot_faction_tier_4_troop, "trp_khergit_horse_archer"),
      # (faction_set_slot, "fac_culture_3", slot_faction_tier_5_troop, "trp_khergit_veteran_horse_archer"),

      # (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"),
	  
# NE dk	  
      (faction_set_slot, "fac_culture_1",  slot_faction_tier_1_troop, "trp_swadian_recruit"),
      (faction_set_slot, "fac_culture_1",  slot_faction_tier_2_troop, "trp_swadian_proselyte"),
      (faction_set_slot, "fac_culture_1",  slot_faction_tier_3_troop, "trp_swadian_sergeant"),
      (faction_set_slot, "fac_culture_1",  slot_faction_tier_4_troop, "trp_swadian_captain"),
      (faction_set_slot, "fac_culture_1",  slot_faction_tier_5_troop, "trp_swadian_squire"),
      (faction_set_slot, "fac_culture_1",  slot_faction_noble_troop, "trp_swadian_man_at_arms"),

      (faction_set_slot, "fac_culture_2", slot_faction_tier_1_troop, "trp_vaegir_recruit"),
      (faction_set_slot, "fac_culture_2", slot_faction_tier_2_troop, "trp_vaegir_footman"),
      (faction_set_slot, "fac_culture_2", slot_faction_tier_3_troop, "trp_vaegir_varangian"),
      (faction_set_slot, "fac_culture_2", slot_faction_tier_4_troop, "trp_vaegir_horseman"),
      (faction_set_slot, "fac_culture_2", slot_faction_tier_5_troop, "trp_vaegir_master_bowyer"),
      (faction_set_slot, "fac_culture_2", slot_faction_noble_troop, "trp_vaegir_ivory_bowman"),

      (faction_set_slot, "fac_culture_3", slot_faction_tier_1_troop, "trp_khergit_tribesman"),
      (faction_set_slot, "fac_culture_3", slot_faction_tier_2_troop, "trp_khergit_kharash"),
      (faction_set_slot, "fac_culture_3", slot_faction_tier_3_troop, "trp_khergit_rider"),
      (faction_set_slot, "fac_culture_3", slot_faction_tier_4_troop, "trp_khergit_horse_archer"),
      (faction_set_slot, "fac_culture_3", slot_faction_tier_5_troop, "trp_khergit_savage_lancer"),
      (faction_set_slot, "fac_culture_3", slot_faction_noble_troop, "trp_khergit_tribal_chieftain"),

      (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_thrall"),
      (faction_set_slot, "fac_culture_4", slot_faction_tier_3_troop, "trp_nord_warrior"),
      (faction_set_slot, "fac_culture_4", slot_faction_tier_4_troop, "trp_nord_shieldmaster"),
      (faction_set_slot, "fac_culture_4", slot_faction_tier_5_troop, "trp_nord_berserker"),
      (faction_set_slot, "fac_culture_4", slot_faction_noble_troop, "trp_nord_housecarl"),

      (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_crossbowman"),
      (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_master_swordsman"),
      (faction_set_slot, "fac_culture_5", slot_faction_noble_troop, "trp_rhodok_armsman"),
      
      (faction_set_slot, "fac_culture_dark_knights", slot_faction_tier_1_troop, "trp_dark_initiate"),
      (faction_set_slot, "fac_culture_dark_knights", slot_faction_tier_2_troop, "trp_dark_acolyte"),
      (faction_set_slot, "fac_culture_dark_knights", slot_faction_tier_3_troop, "trp_dark_page"),
      (faction_set_slot, "fac_culture_dark_knights", slot_faction_tier_4_troop, "trp_dark_squire"),
      (faction_set_slot, "fac_culture_dark_knights", slot_faction_tier_5_troop, "trp_dark_knight"),
      (faction_set_slot, "fac_culture_dark_knights", slot_faction_noble_troop, "trp_shadow_knight"),	  
# NE end dk  

      (faction_set_slot, "fac_culture_6", slot_faction_tier_1_troop, "trp_sarranid_recruit"),
      (faction_set_slot, "fac_culture_6", slot_faction_tier_2_troop, "trp_sarranid_seyman"),
      (faction_set_slot, "fac_culture_6", slot_faction_tier_3_troop, "trp_sarranid_akinci"),
      (faction_set_slot, "fac_culture_6", slot_faction_tier_4_troop, "trp_sarranid_dervish"),
      (faction_set_slot, "fac_culture_6", slot_faction_tier_5_troop, "trp_sarranid_cataphract"),
	  
# NE dk
      (faction_set_slot, "fac_culture_6", slot_faction_noble_troop, "trp_sarranid_eunuch"),
# NE end dk

      (faction_set_slot, "fac_culture_1", slot_faction_town_walker_male_troop, "trp_town_walker_1"),
      (faction_set_slot, "fac_culture_1", slot_faction_town_walker_female_troop, "trp_town_walker_2"),
      (faction_set_slot, "fac_culture_1", slot_faction_village_walker_male_troop, "trp_village_walker_1"),
      (faction_set_slot, "fac_culture_1", slot_faction_village_walker_female_troop, "trp_village_walker_2"),
      (faction_set_slot, "fac_culture_1", slot_faction_town_spy_male_troop, "trp_spy_walker_1"),
      (faction_set_slot, "fac_culture_1", slot_faction_town_spy_female_troop, "trp_spy_walker_2"),

      (faction_set_slot, "fac_culture_2", slot_faction_town_walker_male_troop, "trp_town_walker_1"),
      (faction_set_slot, "fac_culture_2", slot_faction_town_walker_female_troop, "trp_town_walker_2"),
      (faction_set_slot, "fac_culture_2", slot_faction_village_walker_male_troop, "trp_village_walker_1"),
      (faction_set_slot, "fac_culture_2", slot_faction_village_walker_female_troop, "trp_village_walker_2"),
      (faction_set_slot, "fac_culture_2", slot_faction_town_spy_male_troop, "trp_spy_walker_1"),
      (faction_set_slot, "fac_culture_2", slot_faction_town_spy_female_troop, "trp_spy_walker_2"),

      (faction_set_slot, "fac_culture_3", slot_faction_town_walker_male_troop, "trp_khergit_townsman"),
      (faction_set_slot, "fac_culture_3", slot_faction_town_walker_female_troop, "trp_khergit_townswoman"),
      (faction_set_slot, "fac_culture_3", slot_faction_village_walker_male_troop, "trp_khergit_townsman"),
      (faction_set_slot, "fac_culture_3", slot_faction_village_walker_female_troop, "trp_khergit_townswoman"),
      (faction_set_slot, "fac_culture_3", slot_faction_town_spy_male_troop, "trp_spy_walker_1"),
      (faction_set_slot, "fac_culture_3", slot_faction_town_spy_female_troop, "trp_spy_walker_2"),

      (faction_set_slot, "fac_culture_4", slot_faction_town_walker_male_troop, "trp_town_walker_1"),
      (faction_set_slot, "fac_culture_4", slot_faction_town_walker_female_troop, "trp_town_walker_2"),
      (faction_set_slot, "fac_culture_4", slot_faction_village_walker_male_troop, "trp_village_walker_1"),
      (faction_set_slot, "fac_culture_4", slot_faction_village_walker_female_troop, "trp_village_walker_2"),
      (faction_set_slot, "fac_culture_4", slot_faction_town_spy_male_troop, "trp_spy_walker_1"),
      (faction_set_slot, "fac_culture_4", slot_faction_town_spy_female_troop, "trp_spy_walker_2"),

      (faction_set_slot, "fac_culture_5", slot_faction_town_walker_male_troop, "trp_town_walker_1"),
      (faction_set_slot, "fac_culture_5", slot_faction_town_walker_female_troop, "trp_town_walker_2"),
      (faction_set_slot, "fac_culture_5", slot_faction_village_walker_male_troop, "trp_village_walker_1"),
      (faction_set_slot, "fac_culture_5", slot_faction_village_walker_female_troop, "trp_village_walker_2"),
      (faction_set_slot, "fac_culture_5", slot_faction_town_spy_male_troop, "trp_spy_walker_1"),
      (faction_set_slot, "fac_culture_5", slot_faction_town_spy_female_troop, "trp_spy_walker_2"),

      (faction_set_slot, "fac_culture_6", slot_faction_town_walker_male_troop, "trp_sarranid_townsman"),
      (faction_set_slot, "fac_culture_6", slot_faction_town_walker_female_troop, "trp_sarranid_townswoman"),
      (faction_set_slot, "fac_culture_6", slot_faction_village_walker_male_troop, "trp_sarranid_townsman"),
      (faction_set_slot, "fac_culture_6", slot_faction_village_walker_female_troop, "trp_sarranid_townswoman"),
      (faction_set_slot, "fac_culture_6", slot_faction_town_spy_male_troop, "trp_spy_walker_1"),
      (faction_set_slot, "fac_culture_6", slot_faction_town_spy_female_troop, "trp_spy_walker_2"),

      (try_begin),
        (eq, "$cheat_mode", 1),
        (assign, reg3, "$cheat_mode"),
        (display_message, "@{!}DEBUG : Completed faction troop assignments, cheat mode: {reg3}"),
      (try_end),
      
# Factions:
      (faction_set_slot, "fac_kingdom_1",  slot_faction_culture, "fac_culture_1"),
      (faction_set_slot, "fac_kingdom_1",  slot_faction_leader, "trp_kingdom_1_lord"),
	  (troop_set_slot, "trp_kingdom_1_lord", slot_troop_renown, 1200),
	  
      (faction_set_slot, "fac_kingdom_2",  slot_faction_culture, "fac_culture_2"),
      (faction_set_slot, "fac_kingdom_2",  slot_faction_leader, "trp_kingdom_2_lord"),
	  (troop_set_slot, "trp_kingdom_2_lord", slot_troop_renown, 1200),

      (faction_set_slot, "fac_kingdom_3",  slot_faction_culture, "fac_culture_3"),
      (faction_set_slot, "fac_kingdom_3",  slot_faction_leader, "trp_kingdom_3_lord"),
	  (troop_set_slot, "trp_kingdom_3_lord", slot_troop_renown, 1200),

      (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"),
	  (troop_set_slot, "trp_kingdom_4_lord", slot_troop_renown, 1200),

      (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"),
	  (troop_set_slot, "trp_kingdom_5_lord", slot_troop_renown, 1200),

      (faction_set_slot, "fac_kingdom_6",  slot_faction_culture, "fac_culture_6"),
      (faction_set_slot, "fac_kingdom_6",  slot_faction_leader, "trp_kingdom_6_lord"),
	  (troop_set_slot, "trp_kingdom_6_lord", slot_troop_renown, 1200),
	  
# NE dk
      (faction_set_slot, "fac_dark_knights",  slot_faction_culture, "fac_culture_dark_knights"),
      (faction_set_slot, "fac_dark_knights",  slot_faction_leader, "trp_dark_knight_lord"),
      (store_random_in_range, ":renown", 0, 1000),
      (val_add, ":renown", 1500),
      (troop_set_slot, "trp_dark_knight_lord", slot_troop_renown, ":renown"),
      (try_for_range, ":dk", "trp_dark_knight_lord1", "trp_kingdom_1_pretender"),
          (store_random_in_range, ":renown", 0, 500),
          (val_add, ":renown", 1000),
          (troop_set_slot, ":dk", slot_troop_renown, ":renown"),
      (try_end),
	  
# NE End dk

      (assign, ":player_faction_culture", "fac_culture_1"),  
      (faction_set_slot, "fac_player_supporters_faction",  slot_faction_culture, ":player_faction_culture"),
      (faction_set_slot, "fac_player_faction",  slot_faction_culture, ":player_faction_culture"),
	  
      (try_for_range, ":faction_no", kingdoms_begin, kingdoms_end),
        (faction_set_slot, ":faction_no", slot_faction_marshall, -1),
      (try_end), 
      (faction_set_slot, "fac_player_supporters_faction", slot_faction_marshall, "trp_player"),
      (call_script, "script_initialize_faction_troop_types"),


# 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), #1000
        (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),

	  (call_script, "script_initialize_trade_routes"),
	  (call_script, "script_initialize_town_arena_info"),
      #start some tournaments
      (try_for_range, ":town_no", towns_begin, towns_end),
        (store_random_in_range, ":rand", 0, 100),
        (lt, ":rand", 20),
        (store_random_in_range, ":random_days", 12, 15),
        (party_set_slot, ":town_no", slot_town_has_tournament, ":random_days"),
      (try_end),

      #village products -- at some point we might make it so that the villages supply raw materials to towns, and the towns produce manufactured goods
	  #village products designate the raw materials produced in the vicinity
	  #right now, just doing a test for grain produced in the swadian heartland
	  


	  # fill_village_bound_centers
    #pass 1: Give one village to each castle
      (try_for_range, ":cur_center", castles_begin, castles_end),
        (assign, ":min_dist", 999999),
        (assign, ":min_dist_village", -1),
        (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.
          (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),

      		  	  
	# 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_walls", ":offset"),
        (party_set_slot,":town_no", slot_town_walls, ":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_mayor", ":offset"),
        (party_set_slot,":town_no", slot_town_elder, ":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", "scn_town_1_center", ":offset"),
        (party_set_slot,":town_no", slot_town_center, ":cur_object_no"),
        (party_set_slot,":town_no", slot_town_reinforcement_party_template, "pt_center_reinforcements"),
      (try_end),


	  
# Castles
      (try_for_range, ":castle_no", castles_begin, castles_end),
        (store_sub, ":offset", ":castle_no", castles_begin),
        (val_mul, ":offset", 3),

#        (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"),
        (store_add, ":interior_scene_no", "scn_castle_1_prison", ":offset"),
        (party_set_slot,":castle_no", slot_town_prison, ":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_town_13", slot_center_siege_with_belfry, 1),
      (party_set_slot,"p_town_16", slot_center_siege_with_belfry, 1),

      (party_set_slot,"p_castle_1", slot_center_siege_with_belfry, 1),
      (party_set_slot,"p_castle_2", slot_center_siege_with_belfry, 1),
      (party_set_slot,"p_castle_4", slot_center_siege_with_belfry, 1),
      (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_11", slot_center_siege_with_belfry, 1),
      (party_set_slot,"p_castle_13", slot_center_siege_with_belfry, 1),
      (party_set_slot,"p_castle_21", slot_center_siege_with_belfry, 1),
      (party_set_slot,"p_castle_25", slot_center_siege_with_belfry, 1),
      (party_set_slot,"p_castle_34", slot_center_siege_with_belfry, 1),
      (party_set_slot,"p_castle_35", slot_center_siege_with_belfry, 1),
      (party_set_slot,"p_castle_38", slot_center_siege_with_belfry, 1),
      (party_set_slot,"p_castle_40", slot_center_siege_with_belfry, 1),
      (party_set_slot,"p_castle_41", slot_center_siege_with_belfry, 1),
      (party_set_slot,"p_castle_42", slot_center_siege_with_belfry, 1),
      (party_set_slot,"p_castle_43", slot_center_siege_with_belfry, 1),

	  # Villages characters
      (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_elder", ":offset"),
        (party_set_slot,":village_no", slot_town_elder, ":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_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),
      
      (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.

      #faction banners
      (faction_set_slot, "fac_kingdom_1", slot_faction_banner, "mesh_banner_kingdom_f"),
      (faction_set_slot, "fac_kingdom_2", slot_faction_banner, "mesh_banner_kingdom_b"),
      (faction_set_slot, "fac_kingdom_3", slot_faction_banner, "mesh_banner_kingdom_c"),
      (faction_set_slot, "fac_kingdom_4", slot_faction_banner, "mesh_banner_kingdom_a"),
      (faction_set_slot, "fac_kingdom_5", slot_faction_banner, "mesh_banner_kingdom_d"),
      (faction_set_slot, "fac_kingdom_6", slot_faction_banner, "mesh_banner_kingdom_e"),
	  # NE dk
	  (faction_set_slot, "fac_dark_knights", slot_faction_banner, "mesh_banner_kingdom_dk"),
	  #(faction_set_slot, "fac_dark_knights", slot_faction_banner, "mesh_banner_kingdom_e"),
      # NE end dk
      (try_for_range, ":cur_faction", npc_kingdoms_begin, npc_kingdoms_end),
        (faction_get_slot, ":cur_faction_king", ":cur_faction", slot_faction_leader),
        (faction_get_slot, ":cur_faction_banner", ":cur_faction", slot_faction_banner),
        (val_sub, ":cur_faction_banner", banner_meshes_begin),
        (val_add, ":cur_faction_banner", banner_scene_props_begin),
        (troop_set_slot, ":cur_faction_king", slot_troop_banner_scene_prop, ":cur_faction_banner"),
      (try_end),
      (assign, ":num_khergit_lords_assigned", 0),
      (assign, ":num_sarranid_lords_assigned", 0),
      (assign, ":num_other_lords_assigned", 0),
            
      (try_for_range, ":kingdom_hero", active_npcs_begin, active_npcs_end),
        (this_or_next|troop_slot_eq, ":kingdom_hero", slot_troop_occupation, slto_kingdom_hero),
        (troop_slot_eq, ":kingdom_hero", slot_troop_occupation, slto_inactive_pretender),
        
        (store_troop_faction, ":kingdom_hero_faction", ":kingdom_hero"),
        (neg|faction_slot_eq, ":kingdom_hero_faction", slot_faction_leader, ":kingdom_hero"),
        (try_begin), 
          (eq, ":kingdom_hero_faction", "fac_kingdom_3"), #Khergit Khanate
          (store_add, ":kingdom_3_banners_begin", banner_scene_props_begin, khergit_banners_begin_offset),
          (store_add, ":banner_id", ":kingdom_3_banners_begin", ":num_khergit_lords_assigned"),
          (troop_set_slot, ":kingdom_hero", slot_troop_banner_scene_prop, ":banner_id"),
          (val_add, ":num_khergit_lords_assigned", 1),
        (else_try),
          (eq, ":kingdom_hero_faction", "fac_kingdom_6"), #Sarranid Sultanate
          (store_add, ":kingdom_6_banners_begin", banner_scene_props_begin, sarranid_banners_begin_offset),
          (store_add, ":banner_id", ":kingdom_6_banners_begin", ":num_sarranid_lords_assigned"),
          (troop_set_slot, ":kingdom_hero", slot_troop_banner_scene_prop, ":banner_id"),
          (val_add, ":num_sarranid_lords_assigned", 1),
        (else_try),
          (assign, ":hero_offset", ":num_other_lords_assigned"),
          (try_begin),
            (gt, ":hero_offset", khergit_banners_begin_offset),#Do not add khergit banners to other lords
            (val_add, ":hero_offset", khergit_banners_end_offset),
            (val_sub, ":hero_offset", khergit_banners_begin_offset),
          (try_end),
          (try_begin),
            (gt, ":hero_offset", sarranid_banners_begin_offset),#Do not add sarranid banners to other lords
            (val_add, ":hero_offset", sarranid_banners_end_offset),
            (val_sub, ":hero_offset", sarranid_banners_begin_offset),
          (try_end),
          (store_add, ":banner_id", banner_scene_props_begin, ":hero_offset"),
          (troop_set_slot, ":kingdom_hero", slot_troop_banner_scene_prop, ":banner_id"),
          (val_add, ":num_other_lords_assigned", 1),
        (try_end),
        (try_begin),
          (this_or_next|lt, ":banner_id", banner_scene_props_begin),
          (gt, ":banner_id", banner_scene_props_end_minus_one),
          (display_message, "@{!}ERROR: Not enough banners for heroes!"),
        (try_end),

        (store_character_level, ":level", ":kingdom_hero"),
        (store_mul, ":renown", ":level", ":level"),
        (val_div, ":renown", 4), #for top lord, is about 400

		(troop_get_slot, ":age", ":kingdom_hero", slot_troop_age),
        (store_mul, ":age_addition", ":age", ":age"),
        (val_div, ":age_addition", 8), #for top lord, is about 400
		(val_add, ":renown", ":age_addition"),
			
        (try_begin),
          (faction_slot_eq, ":kingdom_hero_faction", slot_faction_leader, ":kingdom_hero"),
          (store_random_in_range, ":random_renown", 250, 400),
        (else_try),
          (store_random_in_range, ":random_renown", 0, 100),
        (try_end),
        (val_add, ":renown", ":random_renown"),

        (troop_set_slot, ":kingdom_hero", slot_troop_renown, ":renown"),				
      (try_end),

      (try_for_range, ":troop_no", "trp_player", "trp_merchants_end"),
        (add_troop_note_tableau_mesh, ":troop_no", "tableau_troop_note_mesh"),
      (try_end),
	  
      (try_for_range, ":center_no", centers_begin, centers_end),
        (add_party_note_tableau_mesh, ":center_no", "tableau_center_note_mesh"),
      (try_end),

      (try_for_range, ":faction_no", kingdoms_begin, kingdoms_end),
        (is_between, ":faction_no", "fac_kingdom_1", kingdoms_end), #Excluding player kingdom
        (add_faction_note_tableau_mesh, ":faction_no", "tableau_faction_note_mesh"),
      (else_try),
        (add_faction_note_tableau_mesh, ":faction_no", "tableau_faction_note_mesh_banner"),
      (try_end),

	

	  
	  # NE building
# Build the special buildings in the 5 capitals to begin with - Jinnai
      (party_set_slot,"p_town_6",slot_center_has_cathedral,1),
      (faction_set_slot,"fac_kingdom_1",slot_faction_special_building_a,"p_town_6"),
      (party_set_slot,"p_town_8",slot_center_has_ivory_temple,1),
      (faction_set_slot,"fac_kingdom_2",slot_faction_special_building_a,"p_town_8"),
      (party_set_slot,"p_town_10",slot_center_has_palace,1),
      (faction_set_slot,"fac_kingdom_3",slot_faction_special_building_a,"p_town_10"),
      (party_set_slot,"p_town_1",slot_center_has_hall,1),
      (faction_set_slot,"fac_kingdom_4",slot_faction_special_building_a,"p_town_1"),
      (party_set_slot,"p_town_5",slot_center_has_chambers,1),
      (faction_set_slot,"fac_kingdom_5",slot_faction_special_building_a,"p_town_5"),
	  (party_set_slot,"p_town_19",slot_center_has_baths,1),
      (faction_set_slot,"fac_kingdom_6",slot_faction_special_building_a,"p_town_19"),

# Set the special troops from the special buildings - Jinnai
      (faction_set_slot,"fac_kingdom_1",slot_faction_special_troop_1,"trp_swadian_paladin"),
      (faction_set_slot,"fac_kingdom_1",slot_faction_special_troop_2,"trp_swadian_priest"),
# Disabling the earl as it's been removed - soulmata
#      (faction_set_slot,"fac_kingdom_1",slot_faction_special_troop_3,"trp_swadian_earl"),

      (faction_set_slot,"fac_kingdom_2",slot_faction_special_troop_1,"trp_vaegir_ivory_sentinel"),
      (faction_set_slot,"fac_kingdom_2",slot_faction_special_troop_2,"trp_vaegir_knyaz"),
# Again disabling third elite option as it's been removed
#      (faction_set_slot,"fac_kingdom_2",slot_faction_special_troop_3,"trp_vaegir_majorprince"),

      (faction_set_slot,"fac_kingdom_3",slot_faction_special_troop_1,"trp_khergit_guanren"),
      (faction_set_slot,"fac_kingdom_3",slot_faction_special_troop_2,"trp_khergit_keshik"),
# Again disabling third elite option as it's been removed
#      (faction_set_slot,"fac_kingdom_3",slot_faction_special_troop_3,"trp_khergit_emangudai"),

      (faction_set_slot,"fac_kingdom_4",slot_faction_special_troop_1,"trp_nord_einherjar"),
      (faction_set_slot,"fac_kingdom_4",slot_faction_special_troop_2,"trp_nord_valkyrie"),
# Again disable third elite option as it's been removed
#      (faction_set_slot,"fac_kingdom_4",slot_faction_special_troop_3,"trp_nord_valhalla"),

      (faction_set_slot,"fac_kingdom_5",slot_faction_special_troop_1,"trp_rhodok_arbalest"),
      (faction_set_slot,"fac_kingdom_5",slot_faction_special_troop_2,"trp_rhodok_spear_knight"),
# Again disabling third elite option as it's been removed
#      (faction_set_slot,"fac_kingdom_5",slot_faction_special_troop_3,"trp_rhodok_captain"),

      (faction_set_slot,"fac_kingdom_6",slot_faction_special_troop_1,"trp_sarranid_zhayedan"),
      (faction_set_slot,"fac_kingdom_6",slot_faction_special_troop_2,"trp_sarranid_spahbod_serden"),
# Again disabling third elite option as it's been removed
#      (faction_set_slot,"fac_kingdom_6",slot_faction_special_troop_3,"trp_sarranid_satrap"),	  
	  # Ne end building
	  
	  
	  #Give centers to factions first, to ensure more equal distributions
	  (call_script, "script_give_center_to_faction_aux", "p_town_1", "fac_kingdom_4"),
	  (call_script, "script_give_center_to_faction_aux", "p_town_2", "fac_kingdom_4"),
	  (call_script, "script_give_center_to_faction_aux", "p_town_3", "fac_kingdom_5"),
	  (call_script, "script_give_center_to_faction_aux", "p_town_4", "fac_kingdom_1"),
	  (call_script, "script_give_center_to_faction_aux", "p_town_5", "fac_kingdom_5"),
	  (call_script, "script_give_center_to_faction_aux", "p_town_6", "fac_kingdom_1"),
	  (call_script, "script_give_center_to_faction_aux", "p_town_7", "fac_kingdom_1"),
	  (call_script, "script_give_center_to_faction_aux", "p_town_8", "fac_kingdom_2"),
	  (call_script, "script_give_center_to_faction_aux", "p_town_9", "fac_kingdom_2"),
	  (call_script, "script_give_center_to_faction_aux", "p_town_10", "fac_kingdom_3"),
	  (call_script, "script_give_center_to_faction_aux", "p_town_11", "fac_kingdom_2"),
	  (call_script, "script_give_center_to_faction_aux", "p_town_12", "fac_kingdom_4"),
	  (call_script, "script_give_center_to_faction_aux", "p_town_13", "fac_kingdom_2"),
	  (call_script, "script_give_center_to_faction_aux", "p_town_14", "fac_kingdom_3"),
	  (call_script, "script_give_center_to_faction_aux", "p_town_15", "fac_kingdom_5"),
	  (call_script, "script_give_center_to_faction_aux", "p_town_16", "fac_kingdom_1"),
	  (call_script, "script_give_center_to_faction_aux", "p_town_17", "fac_kingdom_3"),
	  (call_script, "script_give_center_to_faction_aux", "p_town_18", "fac_kingdom_3"),
	  (call_script, "script_give_center_to_faction_aux", "p_town_19", "fac_kingdom_6"),
	  (call_script, "script_give_center_to_faction_aux", "p_town_20", "fac_kingdom_6"),
	  (call_script, "script_give_center_to_faction_aux", "p_town_21", "fac_kingdom_6"),
	  (call_script, "script_give_center_to_faction_aux", "p_town_22", "fac_kingdom_6"),
	  
	  # NE city
	  #(call_script, "script_give_center_to_faction_aux", "p_town_23", "fac_robber_knights"),	  
	  # NE end city
	  
      (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_3"),
      (call_script, "script_give_center_to_faction_aux", "p_castle_3", "fac_kingdom_2"),
      (call_script, "script_give_center_to_faction_aux", "p_castle_4", "fac_kingdom_2"),
      (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_1"),
      (call_script, "script_give_center_to_faction_aux", "p_castle_7", "fac_kingdom_3"),
      (call_script, "script_give_center_to_faction_aux", "p_castle_8", "fac_kingdom_2"),
      (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_4"),
      (call_script, "script_give_center_to_faction_aux", "p_castle_11", "fac_kingdom_4"),

      (call_script, "script_give_center_to_faction_aux", "p_castle_12", "fac_kingdom_4"),
      (call_script, "script_give_center_to_faction_aux", "p_castle_13", "fac_kingdom_1"),
      (call_script, "script_give_center_to_faction_aux", "p_castle_14", "fac_kingdom_5"),
      (call_script, "script_give_center_to_faction_aux", "p_castle_15", "fac_kingdom_5"),
      (call_script, "script_give_center_to_faction_aux", "p_castle_16", "fac_kingdom_5"),
      (call_script, "script_give_center_to_faction_aux", "p_castle_17", "fac_kingdom_3"),
      (call_script, "script_give_center_to_faction_aux", "p_castle_18", "fac_kingdom_2"),
      (call_script, "script_give_center_to_faction_aux", "p_castle_19", "fac_kingdom_2"),
      (call_script, "script_give_center_to_faction_aux", "p_castle_20", "fac_kingdom_1"),

      (call_script, "script_give_center_to_faction_aux", "p_castle_21", "fac_kingdom_5"),
      (call_script, "script_give_center_to_faction_aux", "p_castle_22", "fac_kingdom_3"),
      (call_script, "script_give_center_to_faction_aux", "p_castle_23", "fac_kingdom_1"),
      (call_script, "script_give_center_to_faction_aux", "p_castle_24", "fac_kingdom_1"),

      (call_script, "script_give_center_to_faction_aux", "p_castle_25", "fac_kingdom_1"),
      (call_script, "script_give_center_to_faction_aux", "p_castle_26", "fac_kingdom_1"),
      (call_script, "script_give_center_to_faction_aux", "p_castle_27", "fac_kingdom_1"),
      (call_script, "script_give_center_to_faction_aux", "p_castle_28", "fac_kingdom_5"),

      (call_script, "script_give_center_to_faction_aux", "p_castle_29", "fac_kingdom_2"), 
      (call_script, "script_give_center_to_faction_aux", "p_castle_30", "fac_kingdom_3"),
      (call_script, "script_give_center_to_faction_aux", "p_castle_31", "fac_kingdom_1"),

      (call_script, "script_give_center_to_faction_aux", "p_castle_32", "fac_kingdom_4"),
      (call_script, "script_give_center_to_faction_aux", "p_castle_33", "fac_kingdom_5"),
      (call_script, "script_give_center_to_faction_aux", "p_castle_34", "fac_kingdom_4"),
      (call_script, "script_give_center_to_faction_aux", "p_castle_35", "fac_kingdom_1"),
      
      (call_script, "script_give_center_to_faction_aux", "p_castle_36", "fac_kingdom_4"),
      (call_script, "script_give_center_to_faction_aux", "p_castle_37", "fac_kingdom_2"),
      (call_script, "script_give_center_to_faction_aux", "p_castle_38", "fac_kingdom_3"),
      (call_script, "script_give_center_to_faction_aux", "p_castle_39", "fac_kingdom_2"),
      (call_script, "script_give_center_to_faction_aux", "p_castle_40", "fac_kingdom_3"),
      
      (call_script, "script_give_center_to_faction_aux", "p_castle_41", "fac_kingdom_6"),
      (call_script, "script_give_center_to_faction_aux", "p_castle_42", "fac_kingdom_6"),
      (call_script, "script_give_center_to_faction_aux", "p_castle_43", "fac_kingdom_6"),
      (call_script, "script_give_center_to_faction_aux", "p_castle_44", "fac_kingdom_6"),
      (call_script, "script_give_center_to_faction_aux", "p_castle_45", "fac_kingdom_6"),
      (call_script, "script_give_center_to_faction_aux", "p_castle_46", "fac_kingdom_6"),
      (call_script, "script_give_center_to_faction_aux", "p_castle_47", "fac_kingdom_6"),
      (call_script, "script_give_center_to_faction_aux", "p_castle_48", "fac_kingdom_6"),
      

	  #Now give towns to great lords
      (call_script, "script_give_center_to_lord", "p_town_1",  "trp_kingdom_4_lord", 0),
      (call_script, "script_give_center_to_lord", "p_town_2",  "trp_knight_4_1", 0),
      (call_script, "script_give_center_to_lord", "p_town_3",  "trp_knight_5_1", 0),
      (call_script, "script_give_center_to_lord", "p_town_4",  "trp_knight_1_1", 0),
      (call_script, "script_give_center_to_lord", "p_town_5",  "trp_kingdom_5_lord", 0),
      (call_script, "script_give_center_to_lord", "p_town_6",  "trp_kingdom_1_lord", 0),
      (call_script, "script_give_center_to_lord", "p_town_7",  "trp_knight_1_2", 0),
      
      (call_script, "script_give_center_to_lord", "p_town_8",  "trp_kingdom_2_lord", 0),
      (call_script, "script_give_center_to_lord", "p_town_9",  "trp_knight_2_1", 0),
      (call_script, "script_give_center_to_lord", "p_town_10", "trp_kingdom_3_lord", 0),
      (call_script, "script_give_center_to_lord", "p_town_11", "trp_knight_2_2", 0),
      (call_script, "script_give_center_to_lord", "p_town_12", "trp_knight_4_2", 0),
      (call_script, "script_give_center_to_lord", "p_town_13", "trp_knight_2_3", 0),
      (call_script, "script_give_center_to_lord", "p_town_14", "trp_knight_3_1", 0),

      (call_script, "script_give_center_to_lord", "p_town_15", "trp_knight_5_2", 0),
      (call_script, "script_give_center_to_lord", "p_town_16", "trp_knight_1_4", 0), #changed from 1_3
      (call_script, "script_give_center_to_lord", "p_town_17", "trp_knight_3_2", 0),
      (call_script, "script_give_center_to_lord", "p_town_18", "trp_knight_3_3", 0),	  
	  
      (call_script, "script_give_center_to_lord", "p_town_19", "trp_kingdom_6_lord", 0),
      (call_script, "script_give_center_to_lord", "p_town_20", "trp_knight_6_1", 0), 
      (call_script, "script_give_center_to_lord", "p_town_21", "trp_knight_6_2", 0),
      (call_script, "script_give_center_to_lord", "p_town_22", "trp_knight_6_3", 0),	  	  
	  
# NE city
#      #(call_script, "script_give_center_to_lord", "p_town_23", "trp_bin_hoffman", 0),	
# NE 

      # Give family castles to certain nobles.
      (call_script, "script_give_center_to_lord", "p_castle_29", "trp_knight_2_10", 0), #Nelag_Castle
      (call_script, "script_give_center_to_lord", "p_castle_30", "trp_knight_3_4", 0), #Asugan_Castle
      (call_script, "script_give_center_to_lord", "p_castle_35", "trp_knight_1_3", 0), #Haringoth_Castle
	  
      (call_script, "script_assign_lords_to_empty_centers"),
	  	  
	  #set original factions
      (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"),
        (party_set_slot, ":center_no", slot_center_original_faction,  ":original_faction"),
        (party_set_slot, ":center_no", slot_center_ex_faction,  ":original_faction"),
      (try_end),
	  	  
	  #set territorial disputes/outstanding border issues 
	  (party_set_slot, "p_castle_10", slot_center_ex_faction, "fac_kingdom_2"), #vaegirs claim nord-held alburq
	  (party_set_slot, "p_castle_13", slot_center_ex_faction, "fac_kingdom_4"), #nords claim swadian-held kelredan
	  (party_set_slot, "p_castle_15", slot_center_ex_faction, "fac_kingdom_1"), #swadians claim rhodok-held ergelon
	  (party_set_slot, "p_castle_46", slot_center_ex_faction, "fac_kingdom_5"), #rhodoks claim sarranid-held weyyah
	  (party_set_slot, "p_castle_40", slot_center_ex_faction, "fac_kingdom_6"), #sarranids claim khergit-held uhhun
	  (party_set_slot, "p_town_11",   slot_center_ex_faction, "fac_kingdom_3"), #Khergits claim vaegir-held curaw
	  
	  #Swadians, being in the middle, will have additional claims on two of their neighhbors
	  (party_set_slot, "p_castle_15", slot_center_ex_faction, "fac_kingdom_1"), #swadians claim vaegir-held tilbault
	  (party_set_slot, "p_castle_22", slot_center_ex_faction, "fac_kingdom_1"), #swadians claim khergit-held unuzdaq	  	  	  	  
	  
      (call_script, "script_update_village_market_towns"),	  

	  #this should come after assignment of territorial grievances
      (try_for_range, ":unused", 0, 70),
        (try_begin),
          (eq, "$cheat_mode", 1),
          (display_message, "@{!}DEBUG -- initial war/peace check begins"),
        (try_end),
        (call_script, "script_randomly_start_war_peace_new", 0),
      (try_end),

	  
      #Initialize walkers
      (try_for_range, ":center_no", centers_begin, centers_end),
        (this_or_next|party_slot_eq, ":center_no", slot_party_type, spt_town),
                     (party_slot_eq, ":center_no", slot_party_type, spt_village),
        (try_for_range, ":walker_no", 0, num_town_walkers),
          (call_script, "script_center_set_walker_to_type", ":center_no", ":walker_no", walkert_default),
        (try_end),
      (try_end),

	  	  
	  #This needs to be after market towns
	  (call_script, "script_initialize_economic_information"),

	  (try_for_range, ":village_no", villages_begin, villages_end),	
        (call_script, "script_refresh_village_merchant_inventory", ":village_no"),
        (call_script, "script_refresh_village_merchant_inventory", ":village_no"),
      (try_end),	  
	  	  	  	 
      (try_for_range, ":troop_id", original_kingdom_heroes_begin, active_npcs_end),
        (try_begin),
          (store_troop_faction, ":faction_id", ":troop_id"),
          (is_between, ":faction_id", kingdoms_begin, kingdoms_end),
          (troop_set_slot, ":troop_id", slot_troop_original_faction, ":faction_id"),
          (try_begin),
            (is_between, ":troop_id", pretenders_begin, pretenders_end),
            (faction_set_slot, ":faction_id", slot_faction_has_rebellion_chance, 1),			
          (try_end),
        (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),#add town garrisons
        #Add initial center wealth
        (assign, ":initial_wealth", 2000),
        (try_begin),
          (is_between, ":center_no", towns_begin, towns_end),
          (val_mul, ":initial_wealth", 2),
        (try_end),
        (party_set_slot, ":center_no", slot_town_wealth, ":initial_wealth"),
      
        (assign, ":garrison_strength", 15), 
        (try_begin),
          (party_slot_eq, ":center_no", slot_party_type, spt_town),
          (assign, ":garrison_strength", 40), 
        (try_end),
        (try_for_range, ":unused", 0, ":garrison_strength"),
          (call_script, "script_cf_reinforce_party", ":center_no"),
        (try_end),
        ## ADD some XP initially
        (store_div, ":xp_rounds", ":garrison_strength", 5),
        (val_add, ":xp_rounds", 2),
        
        (game_get_reduce_campaign_ai, ":reduce_campaign_ai"),                
        
        (try_begin), #hard
          (eq, ":reduce_campaign_ai", 0),
          (assign, ":xp_addition_for_centers", 7500),
        (else_try), #moderate
          (eq, ":reduce_campaign_ai", 1),
          (assign, ":xp_addition_for_centers", 5000),
        (else_try), #easy
          (eq, ":reduce_campaign_ai", 2),
          (assign, ":xp_addition_for_centers", 2500),
        (try_end),
        
        (try_for_range, ":unused", 0, ":xp_rounds"),          
          (party_upgrade_with_xp, ":center_no", ":xp_addition_for_centers", 0),
        (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),
        (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"),
        (party_set_slot, ":center_no", slot_town_player_odds, 1000),
      (try_end),
		
	#More pre-Warband family structures removed here

	  #Warband changes begin - set companions relations
	  (try_for_range, ":companion", companions_begin, companions_end),
		(try_for_range, ":other_companion", companions_begin, companions_end),
			(neq, ":other_companion", ":companion"),
			(neg|troop_slot_eq, ":companion", slot_troop_personalityclash_object, ":other_companion"),
			(neg|troop_slot_eq, ":companion", slot_troop_personalityclash2_object, ":other_companion"),
			(call_script, "script_troop_change_relation_with_troop", ":companion", ":other_companion", 7), #companions have a starting relation of 14, unless they are rivals
		(try_end),
	  (try_end),	
	
	  #Warband changes continue -  sets relations in the same faction
      (try_for_range, ":lord", original_kingdom_heroes_begin, active_npcs_end),
		(troop_slot_eq, ":lord", slot_troop_occupation, slto_kingdom_hero),
		(troop_get_slot, ":lord_faction", ":lord", slot_troop_original_faction),
				
		(try_for_range, ":other_hero", original_kingdom_heroes_begin, active_npcs_end),
			(this_or_next|troop_slot_eq, ":other_hero", slot_troop_occupation, slto_kingdom_hero),
				(troop_slot_eq, ":other_hero", slot_troop_occupation, slto_inactive_pretender),
			(troop_get_slot, ":other_hero_faction", ":other_hero", slot_troop_original_faction),
			(eq, ":other_hero_faction", ":lord_faction"),
			(call_script, "script_troop_get_family_relation_to_troop", ":lord", ":other_hero"),
			(call_script, "script_troop_change_relation_with_troop", ":lord", ":other_hero", reg0),
			
			(store_random_in_range, ":random", 0, 11), #this will be scored twice between two kingdom heroes, so starting relation will average 10. Between lords and pretenders it will average 7.5
			(call_script, "script_troop_change_relation_with_troop", ":lord", ":other_hero", ":random"),
		(try_end),		
	  (try_end),

	  #do about 5 years' worth of political history (assuming 3 random checks a day)
	  (try_for_range, ":unused", 0, 5000),
		(call_script, "script_cf_random_political_event"),
	  (try_end),
	  (assign, "$total_random_quarrel_changes", 0),
	  (assign, "$total_relation_adds", 0),
	  (assign, "$total_relation_subs", 0),
	  
	  (try_for_range, ":kingdom", kingdoms_begin, kingdoms_end),
		(call_script, "script_evaluate_realm_stability", ":kingdom"),
	  (try_end),
	  #Warband changes end
	  
	  (try_begin),
	    (eq, "$cheat_mode", 1),
	    (assign, reg3, "$cheat_mode"),
	    (display_message, "@{!}DEBUG : Completed political events, cheat mode: {reg3}"),
	  (try_end),

	  #assign love interests to unmarried male lords
	  (try_for_range, ":cur_troop", lords_begin, lords_end),
	    (troop_slot_eq, ":cur_troop", slot_troop_spouse, -1),
		(neg|is_between, ":cur_troop", kings_begin, kings_end),
		(neg|is_between, ":cur_troop", pretenders_begin, pretenders_end),
		
		(call_script, "script_assign_troop_love_interests", ":cur_troop"),
	  (try_end),

	  (store_random_in_range, "$romantic_attraction_seed", 0, 5),
	  
	  (try_begin),
	    (eq, "$cheat_mode", 1),
	    (assign, reg3, "$romantic_attraction_seed"),
	    (display_message, "@{!}DEBUG : Assigned love interests. Attraction seed: {reg3}"),
	  (try_end),
	  
	  #we need to spawn more bandits in warband, because map is bigger.
      #(try_for_range, ":unused", 0, 7),
      #  (call_script, "script_spawn_bandits"),
      #(try_end),

      #(set_spawn_radius, 50),
      #(try_for_range, ":unused", 0, 25),
      #  (spawn_around_party, "p_main_party", "pt_looters"),
      #(try_end),
	  	  
      (try_for_range, ":unused", 0, 10),
        (call_script, "script_spawn_bandits"),
      (try_end),

      #we are adding looter parties around each village with 1/5 probability.
      (set_spawn_radius, 5),
      (try_for_range, ":cur_village", villages_begin, villages_end),
        (store_random_in_range, ":random_value", 0, 5),               
        (eq, ":random_value", 0),
        (spawn_around_party, ":cur_village", "pt_looters"),
      (try_end),

      (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_travellers"),
      (call_script, "script_update_tavern_minstrels"),
      (call_script, "script_update_booksellers"),
	  
      (try_for_range, ":village_no", villages_begin, villages_end),
        (call_script, "script_update_volunteer_troops_in_village", ":village_no"),
      (try_end),
	  
	  # ne noble
	  (try_for_range, ":town_no", towns_begin, towns_end), # Init nobles in towns - Jinnai
        (call_script, "script_update_volunteer_troops_in_town", ":town_no"),
        (call_script, "script_update_npc_volunteer_troops_in_town", ":town_no"),
      (try_end),
	  # ne end noble
	  
	  
      (try_for_range, ":cur_kingdom", kingdoms_begin, kingdoms_end),
        (call_script, "script_update_faction_notes", ":cur_kingdom"),
        (store_random_in_range, ":random_no", -60, 0),
        (faction_set_slot, ":faction_no", slot_faction_last_offensive_concluded, ":random_no"),
      (try_end),
	  
      (try_for_range, ":cur_troop", original_kingdom_heroes_begin, active_npcs_end),
        # Updated by Lav for 0.608b7 unofficial patch
        (store_troop_faction, ":faction_no", ":cur_troop"),
        (call_script, "script_troop_set_title_according_to_faction", ":cur_troop", ":faction_no"),
        # Update by Lav ends here
        (call_script, "script_update_troop_notes", ":cur_troop"),
      (try_end),

      (try_for_range, ":cur_center", centers_begin, centers_end),
        (call_script, "script_update_center_notes", ":cur_center"),
      (try_end),
	  
      (call_script, "script_update_troop_notes", "trp_player"),

	  #Place kingdom ladies
      (try_for_range, ":troop_id", kingdom_ladies_begin, kingdom_ladies_end),
		(call_script, "script_get_kingdom_lady_social_determinants", ":troop_id"),
		(troop_set_slot, ":troop_id", slot_troop_cur_center, reg1),
	  (try_end),
	  
	  (try_begin),
	    (eq, "$cheat_mode", 1),
	    (assign, reg3, "$cheat_mode"),
	    (display_message, "@{!}DEBUG : Located kingdom ladies, cheat mode: {reg3}"),
	  (try_end),
	  
      (try_for_range, ":faction_no", kingdoms_begin, kingdoms_end),
        (call_script, "script_faction_recalculate_strength", ":faction_no"),
      (try_end),

	  (faction_set_slot, "fac_kingdom_1", slot_faction_adjective, "str_kingdom_1_adjective"),
	  (faction_set_slot, "fac_kingdom_2", slot_faction_adjective, "str_kingdom_2_adjective"),
	  (faction_set_slot, "fac_kingdom_3", slot_faction_adjective, "str_kingdom_3_adjective"),
	  (faction_set_slot, "fac_kingdom_4", slot_faction_adjective, "str_kingdom_4_adjective"),
	  (faction_set_slot, "fac_kingdom_5", slot_faction_adjective, "str_kingdom_5_adjective"),
	  (faction_set_slot, "fac_kingdom_6", slot_faction_adjective, "str_kingdom_6_adjective"),
	  
##      (assign, "$players_kingdom", "fac_kingdom_1"),
##      (call_script, "script_give_center_to_lord", "p_town_7", "trp_player", 0),
##      (call_script, "script_give_center_to_lord", "p_town_16", "trp_player", 0),
####      (call_script, "script_give_center_to_lord", "p_castle_10", "trp_player", 0),
##      (assign, "$g_castle_requested_by_player", "p_castle_10"),
      (call_script, "script_get_player_party_morale_values"),
      (party_set_morale, "p_main_party", reg0),
	  # NE dk
      (faction_set_slot, "fac_dark_knights", slot_faction_state, sfs_inactive),
      (party_set_faction,"p_main_party","fac_player_faction"), #This is a bug fix for a bug that sometimes does and sometimes does not show up - Jinnai
	  # NE End dk
      (troop_set_note_available, "trp_player", 1),

      (try_for_range, ":troop_no", kings_begin, kings_end),
        (troop_set_note_available, ":troop_no", 1),
      (try_end),
	  
      (try_for_range, ":troop_no", lords_begin, lords_end),
        (troop_set_note_available, ":troop_no", 1),
      (try_end),

	  (try_for_range, ":troop_no", kingdom_ladies_begin, kingdom_ladies_end),
        (troop_set_note_available, ":troop_no", 1),
      (try_end),
	  (troop_set_note_available, "trp_knight_1_1_wife", 0),

      (try_for_range, ":troop_no", pretenders_begin, pretenders_end),
        (troop_set_note_available, ":troop_no", 1),
      (try_end),
	  
	  #Lady and companion notes become available as you meet/recruit them
	  
      (try_for_range, ":faction_no", npc_kingdoms_begin, npc_kingdoms_end),
        (faction_set_note_available, ":faction_no", 1),
      (try_end),
      (faction_set_note_available, "fac_neutral", 0),
	  
      (try_for_range, ":party_no", centers_begin, centers_end),
        (party_set_note_available, ":party_no", 1),
      (try_end),
    ]),

  #script_game_get_use_string
  # This script is called from the game engine for getting using information text
  # INPUT: used_scene_prop_id  
  # OUTPUT: s0
  ("game_get_use_string",
   [
     (store_script_param, ":instance_id", 1),

     (prop_instance_get_scene_prop_kind, ":scene_prop_id", ":instance_id"),
     
     (try_begin),
       (this_or_next|eq, ":scene_prop_id", "spr_winch_b"),
       (eq, ":scene_prop_id", "spr_winch"),
       (assign, ":effected_object", "spr_portcullis"),
     (else_try),
       (this_or_next|eq, ":scene_prop_id", "spr_door_destructible"),
       (this_or_next|eq, ":scene_prop_id", "spr_castle_f_door_b"),
       (this_or_next|eq, ":scene_prop_id", "spr_castle_e_sally_door_a"),
       (this_or_next|eq, ":scene_prop_id", "spr_castle_f_sally_door_a"),
       (this_or_next|eq, ":scene_prop_id", "spr_earth_sally_gate_left"),
       (this_or_next|eq, ":scene_prop_id", "spr_earth_sally_gate_right"),
       (this_or_next|eq, ":scene_prop_id", "spr_viking_keep_destroy_sally_door_left"),
       (this_or_next|eq, ":scene_prop_id", "spr_viking_keep_destroy_sally_door_right"),
       (this_or_next|eq, ":scene_prop_id", "spr_castle_f_door_a"),
       (this_or_next|eq, ":scene_prop_id", "spr_siege_ladder_move_6m"),
       (this_or_next|eq, ":scene_prop_id", "spr_siege_ladder_move_8m"),
       (this_or_next|eq, ":scene_prop_id", "spr_siege_ladder_move_10m"),
       (this_or_next|eq, ":scene_prop_id", "spr_siege_ladder_move_12m"),
       (eq, ":scene_prop_id", "spr_siege_ladder_move_14m"),
       (assign, ":effected_object", ":scene_prop_id"),
     (try_end),   

     (scene_prop_get_slot, ":item_situation", ":instance_id", scene_prop_open_or_close_slot),
   
     (try_begin), #opening/closing portcullis
       (eq, ":effected_object", "spr_portcullis"),

       (try_begin),
         (eq, ":item_situation", 0),
         (str_store_string, s0, "str_open_gate"),
       (else_try), 
         (str_store_string, s0, "str_close_gate"),
       (try_end),
     (else_try), #opening/closing door
       (this_or_next|eq, ":effected_object", "spr_door_destructible"),
       (this_or_next|eq, ":effected_object", "spr_castle_f_door_b"),
       (this_or_next|eq, ":effected_object", "spr_castle_e_sally_door_a"),
       (this_or_next|eq, ":effected_object", "spr_castle_f_sally_door_a"),
       (this_or_next|eq, ":effected_object", "spr_earth_sally_gate_left"),
       (this_or_next|eq, ":effected_object", "spr_earth_sally_gate_right"),
       (this_or_next|eq, ":effected_object", "spr_viking_keep_destroy_sally_door_left"),
       (this_or_next|eq, ":effected_object", "spr_viking_keep_destroy_sally_door_right"),
       (eq, ":effected_object", "spr_castle_f_door_a"),

       (try_begin),
         (eq, ":item_situation", 0),
         (str_store_string, s0, "str_open_door"),
       (else_try),
         (str_store_string, s0, "str_close_door"),
       (try_end),
     (else_try), #raising/dropping ladder
       (try_begin),
         (eq, ":item_situation", 0),
         (str_store_string, s0, "str_raise_ladder"),
       (else_try),
         (str_store_string, s0, "str_drop_ladder"),
       (try_end),
     (try_end),
   ]),

  #script_game_quick_start
  # This script is called from the game engine for initializing the global variables for tutorial, multiplayer and custom battle modes.
  # INPUT:
  # none
  # OUTPUT:
  # none
  ("game_quick_start",
    [
      #for quick battle mode
      (assign, "$g_is_quick_battle", 0),
      (assign, "$g_quick_battle_game_type", 0),
      (assign, "$g_quick_battle_troop", quick_battle_troops_begin),
      (assign, "$g_quick_battle_map", quick_battle_scenes_begin),
      (assign, "$g_quick_battle_team_1_faction", "fac_kingdom_1"),
      (assign, "$g_quick_battle_team_2_faction", "fac_kingdom_2"),
      (assign, "$g_quick_battle_army_1_size", 25),
      (assign, "$g_quick_battle_army_2_size", 25),

      (faction_set_slot, "fac_outlaws", slot_faction_quick_battle_tier_1_infantry, "trp_mountain_bandit"),
      (faction_set_slot, "fac_outlaws", slot_faction_quick_battle_tier_2_infantry, "trp_sea_raider"),
      (faction_set_slot, "fac_outlaws", slot_faction_quick_battle_tier_1_archer, "trp_forest_bandit"),
      (faction_set_slot, "fac_outlaws", slot_faction_quick_battle_tier_2_archer, "trp_taiga_bandit"),
      (faction_set_slot, "fac_outlaws", slot_faction_quick_battle_tier_1_cavalry, "trp_steppe_bandit"),
      (faction_set_slot, "fac_outlaws", slot_faction_quick_battle_tier_2_cavalry, "trp_desert_bandit"),
      (faction_set_slot, "fac_kingdom_1", slot_faction_quick_battle_tier_1_infantry, "trp_swadian_infantry"),
      (faction_set_slot, "fac_kingdom_1", slot_faction_quick_battle_tier_2_infantry, "trp_swadian_sergeant"),
      (faction_set_slot, "fac_kingdom_1", slot_faction_quick_battle_tier_1_archer, "trp_swadian_skirmisher"),
      (faction_set_slot, "fac_kingdom_1", slot_faction_quick_battle_tier_2_archer, "trp_swadian_crossbowman"),
      (faction_set_slot, "fac_kingdom_1", slot_faction_quick_battle_tier_1_cavalry, "trp_swadian_squire"),
      (faction_set_slot, "fac_kingdom_1", slot_faction_quick_battle_tier_2_cavalry, "trp_swadian_knight"),
      (faction_set_slot, "fac_kingdom_2", slot_faction_quick_battle_tier_1_infantry, "trp_vaegir_footman"),
      (faction_set_slot, "fac_kingdom_2", slot_faction_quick_battle_tier_2_infantry, "trp_vaegir_sergeant"),
      (faction_set_slot, "fac_kingdom_2", slot_faction_quick_battle_tier_1_archer, "trp_vaegir_bowman"),
      (faction_set_slot, "fac_kingdom_2", slot_faction_quick_battle_tier_2_archer, "trp_vaegir_archer"),
      (faction_set_slot, "fac_kingdom_2", slot_faction_quick_battle_tier_1_cavalry, "trp_vaegir_horseman"),
      (faction_set_slot, "fac_kingdom_2", slot_faction_quick_battle_tier_2_cavalry, "trp_vaegir_druzhina"),
      (faction_set_slot, "fac_kingdom_3", slot_faction_quick_battle_tier_1_infantry, "trp_khergit_dismounted_lancer_multiplayer_ai"),
      (faction_set_slot, "fac_kingdom_3", slot_faction_quick_battle_tier_2_infantry, "trp_khergit_dismounted_lancer_multiplayer_ai"),
      (faction_set_slot, "fac_kingdom_3", slot_faction_quick_battle_tier_1_archer, "trp_khergit_horse_archer"),
      (faction_set_slot, "fac_kingdom_3", slot_faction_quick_battle_tier_2_archer, "trp_khergit_veteran_horse_archer"),
      (faction_set_slot, "fac_kingdom_3", slot_faction_quick_battle_tier_1_cavalry, "trp_khergit_lancer"),
      (faction_set_slot, "fac_kingdom_3", slot_faction_quick_battle_tier_2_cavalry, "trp_khergit_lancer"),
      (faction_set_slot, "fac_kingdom_4", slot_faction_quick_battle_tier_1_infantry, "trp_nord_warrior"),
      (faction_set_slot, "fac_kingdom_4", slot_faction_quick_battle_tier_2_infantry, "trp_nord_berserker"),
      (faction_set_slot, "fac_kingdom_4", slot_faction_quick_battle_tier_1_archer, "trp_nord_raiding_archer"),
      (faction_set_slot, "fac_kingdom_4", slot_faction_quick_battle_tier_2_archer, "trp_nord_skald"),
      (faction_set_slot, "fac_kingdom_4", slot_faction_quick_battle_tier_1_cavalry, "trp_nord_scout_multiplayer_ai"),
      (faction_set_slot, "fac_kingdom_4", slot_faction_quick_battle_tier_2_cavalry, "trp_nord_scout_multiplayer_ai"),
      (faction_set_slot, "fac_kingdom_5", slot_faction_quick_battle_tier_1_infantry, "trp_rhodok_veteran_spearman"),
      (faction_set_slot, "fac_kingdom_5", slot_faction_quick_battle_tier_2_infantry, "trp_rhodok_swordsman"),
      (faction_set_slot, "fac_kingdom_5", slot_faction_quick_battle_tier_1_archer, "trp_rhodok_crossbowman"),
      (faction_set_slot, "fac_kingdom_5", slot_faction_quick_battle_tier_2_archer, "trp_rhodok_veteran_crossbowman"),
      (faction_set_slot, "fac_kingdom_5", slot_faction_quick_battle_tier_1_cavalry, "trp_rhodok_scout_multiplayer_ai"),
      (faction_set_slot, "fac_kingdom_5", slot_faction_quick_battle_tier_2_cavalry, "trp_rhodok_scout_multiplayer_ai"),
      (faction_set_slot, "fac_kingdom_6", slot_faction_quick_battle_tier_1_infantry, "trp_sarranid_janissary"),
      (faction_set_slot, "fac_kingdom_6", slot_faction_quick_battle_tier_2_infantry, "trp_sarranid_dervish"),
      (faction_set_slot, "fac_kingdom_6", slot_faction_quick_battle_tier_1_archer, "trp_sarranid_kamandaran"),
      (faction_set_slot, "fac_kingdom_6", slot_faction_quick_battle_tier_2_archer, "trp_sarranid_kamandaran_serden"),
      (faction_set_slot, "fac_kingdom_6", slot_faction_quick_battle_tier_1_cavalry, "trp_sarranid_timariot"),
      (faction_set_slot, "fac_kingdom_6", slot_faction_quick_battle_tier_2_cavalry, "trp_sarranid_mamluke"),
      (faction_set_slot, "fac_dark_knights", slot_faction_quick_battle_tier_1_infantry, "trp_dark_initiate"),
      (faction_set_slot, "fac_dark_knights", slot_faction_quick_battle_tier_2_infantry, "trp_dark_acolyte"),
      (faction_set_slot, "fac_dark_knights", slot_faction_quick_battle_tier_1_archer, "trp_dark_skirmisher"),
      (faction_set_slot, "fac_dark_knights", slot_faction_quick_battle_tier_2_archer, "trp_dark_archer"),
      (faction_set_slot, "fac_dark_knights", slot_faction_quick_battle_tier_1_cavalry, "trp_dark_squire"),
      (faction_set_slot, "fac_dark_knights", slot_faction_quick_battle_tier_2_cavalry, "trp_dark_knight"),
      #for multiplayer mode
      (assign, "$g_multiplayer_selected_map", multiplayer_scenes_begin),
      (assign, "$g_multiplayer_respawn_period", 5),
      (assign, "$g_multiplayer_round_max_seconds", 300),
      (assign, "$g_multiplayer_game_max_minutes", 30),
      (assign, "$g_multiplayer_game_max_points", 300),

      (server_get_renaming_server_allowed, "$g_multiplayer_renaming_server_allowed"),
      (server_get_changing_game_type_allowed, "$g_multiplayer_changing_game_type_allowed"),
      (assign, "$g_multiplayer_point_gained_from_flags", 100),
      (assign, "$g_multiplayer_point_gained_from_capturing_flag", 5),
      (assign, "$g_multiplayer_game_type", 0),
      (assign, "$g_multiplayer_team_1_faction", "fac_kingdom_1"),
      (assign, "$g_multiplayer_team_2_faction", "fac_kingdom_2"),
      (assign, "$g_multiplayer_next_team_1_faction", "$g_multiplayer_team_1_faction"),
      (assign, "$g_multiplayer_next_team_2_faction", "$g_multiplayer_team_2_faction"),
      (assign, "$g_multiplayer_num_bots_team_1", 0),
      (assign, "$g_multiplayer_num_bots_team_2", 0),
      (assign, "$g_multiplayer_number_of_respawn_count", 0),
      (assign, "$g_multiplayer_num_bots_voteable", 50),
      (assign, "$g_multiplayer_max_num_bots", 101),
      (assign, "$g_multiplayer_factions_voteable", 1),
      (assign, "$g_multiplayer_maps_voteable", 1),
      (assign, "$g_multiplayer_kick_voteable", 1),
      (assign, "$g_multiplayer_ban_voteable", 1),
      (assign, "$g_multiplayer_valid_vote_ratio", 51), #more than 50 percent
      (assign, "$g_multiplayer_auto_team_balance_limit", 3), #auto balance when difference is more than 2
      (assign, "$g_multiplayer_player_respawn_as_bot", 1),
      (assign, "$g_multiplayer_stats_chart_opened_manually", 0),
      (assign, "$g_multiplayer_mission_end_screen", 0),
      (assign, "$g_multiplayer_ready_for_spawning_agent", 1),
      (assign, "$g_multiplayer_welcome_message_shown", 0),
      (assign, "$g_multiplayer_allow_player_banners", 1),
      (assign, "$g_multiplayer_force_default_armor", 1),
      (assign, "$g_multiplayer_disallow_ranged_weapons", 0),
      
      (assign, "$g_multiplayer_initial_gold_multiplier", 100),
      (assign, "$g_multiplayer_battle_earnings_multiplier", 100),
      (assign, "$g_multiplayer_round_earnings_multiplier", 100),
  
      #faction banners
      (faction_set_slot, "fac_kingdom_1", slot_faction_banner, "mesh_banner_kingdom_f"),
      (faction_set_slot, "fac_kingdom_2", slot_faction_banner, "mesh_banner_kingdom_b"),
      (faction_set_slot, "fac_kingdom_3", slot_faction_banner, "mesh_banner_kingdom_c"),
      (faction_set_slot, "fac_kingdom_4", slot_faction_banner, "mesh_banner_kingdom_a"),
      (faction_set_slot, "fac_kingdom_5", slot_faction_banner, "mesh_banner_kingdom_d"),
      (faction_set_slot, "fac_kingdom_6", slot_faction_banner, "mesh_banner_kingdom_e"),
	  # NE dk
	  (faction_set_slot, "fac_dark_knights", slot_faction_banner, "mesh_banner_kingdom_dk"),
	  #(faction_set_slot, "fac_dark_knights", slot_faction_banner, "mesh_banner_kingdom_e"),
      # NE end dk
	  
      (try_for_range, ":cur_item", all_items_begin, all_items_end),
        (try_for_range, ":cur_faction", npc_kingdoms_begin, npc_kingdoms_end),
          (store_sub, ":faction_index", ":cur_faction", npc_kingdoms_begin),
          (val_add, ":faction_index", slot_item_multiplayer_faction_price_multipliers_begin),
          (item_set_slot, ":cur_item", ":faction_index", 100), #100 is the default price multiplier
        (try_end),
      (try_end),
      (store_sub, ":swadian_price_slot", "fac_kingdom_1", npc_kingdoms_begin),
      (val_add, ":swadian_price_slot", slot_item_multiplayer_faction_price_multipliers_begin),
      (store_sub, ":vaegir_price_slot", "fac_kingdom_2", npc_kingdoms_begin),
      (val_add, ":vaegir_price_slot", slot_item_multiplayer_faction_price_multipliers_begin),
      (store_sub, ":khergit_price_slot", "fac_kingdom_3", npc_kingdoms_begin),
      (val_add, ":khergit_price_slot", slot_item_multiplayer_faction_price_multipliers_begin),
      (store_sub, ":nord_price_slot", "fac_kingdom_4", npc_kingdoms_begin),
      (val_add, ":nord_price_slot", slot_item_multiplayer_faction_price_multipliers_begin),
      (store_sub, ":rhodok_price_slot", "fac_kingdom_5", npc_kingdoms_begin),
      (val_add, ":rhodok_price_slot", slot_item_multiplayer_faction_price_multipliers_begin),
      (store_sub, ":sarranid_price_slot", "fac_kingdom_6", npc_kingdoms_begin),
      (val_add, ":sarranid_price_slot", slot_item_multiplayer_faction_price_multipliers_begin),

#      (item_set_slot, "itm_steppe_horse", ":khergit_price_slot", 50),

      #arrows
      (item_set_slot, "itm_arrows", slot_item_multiplayer_item_class, multi_item_class_type_arrow),      
      (item_set_slot, "itm_barbed_arrows", slot_item_multiplayer_item_class, multi_item_class_type_arrow),      
      (item_set_slot, "itm_bodkin_arrows", slot_item_multiplayer_item_class, multi_item_class_type_arrow),
      (item_set_slot, "itm_khergit_arrows", slot_item_multiplayer_item_class, multi_item_class_type_arrow),
      #bolts
      (item_set_slot, "itm_bolts", slot_item_multiplayer_item_class, multi_item_class_type_bolt),
      (item_set_slot, "itm_steel_bolts", slot_item_multiplayer_item_class, multi_item_class_type_bolt),
      #bows
      (item_set_slot, "itm_crossbow", slot_item_multiplayer_item_class, multi_item_class_type_bow),
      (item_set_slot, "itm_heavy_crossbow", slot_item_multiplayer_item_class, multi_item_class_type_bow),
      (item_set_slot, "itm_sniper_crossbow", slot_item_multiplayer_item_class, multi_item_class_type_bow),
      (item_set_slot, "itm_nomad_bow", slot_item_multiplayer_item_class, multi_item_class_type_bow),
      (item_set_slot, "itm_khergit_bow", slot_item_multiplayer_item_class, multi_item_class_type_bow),
      (item_set_slot, "itm_strong_bow", slot_item_multiplayer_item_class, multi_item_class_type_bow),
      (item_set_slot, "itm_war_bow", slot_item_multiplayer_item_class, multi_item_class_type_bow),
      (item_set_slot, "itm_short_bow", slot_item_multiplayer_item_class, multi_item_class_type_bow),
      (item_set_slot, "itm_long_bow", slot_item_multiplayer_item_class, multi_item_class_type_bow),
      (item_set_slot, "itm_light_crossbow", slot_item_multiplayer_item_class, multi_item_class_type_bow),      
      #swords
      (item_set_slot, "itm_sword_medieval_a", slot_item_multiplayer_item_class, multi_item_class_type_sword),
      (item_set_slot, "itm_sword_medieval_b", slot_item_multiplayer_item_class, multi_item_class_type_sword),
      (item_set_slot, "itm_sword_medieval_b_small", slot_item_multiplayer_item_class, multi_item_class_type_sword),
      (item_set_slot, "itm_sword_medieval_c", slot_item_multiplayer_item_class, multi_item_class_type_sword),
      (item_set_slot, "itm_sword_medieval_c_small", slot_item_multiplayer_item_class, multi_item_class_type_sword),
      (item_set_slot, "itm_scimitar", slot_item_multiplayer_item_class, multi_item_class_type_sword),
      (item_set_slot, "itm_scimitar_b", slot_item_multiplayer_item_class, multi_item_class_type_sword),
      (item_set_slot, "itm_dagger", slot_item_multiplayer_item_class, multi_item_class_type_sword),
      (item_set_slot, "itm_sword_khergit_1", slot_item_multiplayer_item_class, multi_item_class_type_sword),
      (item_set_slot, "itm_sword_khergit_2", slot_item_multiplayer_item_class, multi_item_class_type_sword),
      (item_set_slot, "itm_sword_khergit_3", slot_item_multiplayer_item_class, multi_item_class_type_sword),
      (item_set_slot, "itm_sword_khergit_4", slot_item_multiplayer_item_class, multi_item_class_type_sword),
      (item_set_slot, "itm_sword_viking_1", slot_item_multiplayer_item_class, multi_item_class_type_sword),
      (item_set_slot, "itm_sword_viking_2", slot_item_multiplayer_item_class, multi_item_class_type_sword),
      (item_set_slot, "itm_sword_viking_2_small", slot_item_multiplayer_item_class, multi_item_class_type_sword),
      (item_set_slot, "itm_sword_viking_3", slot_item_multiplayer_item_class, multi_item_class_type_sword),
      (item_set_slot, "itm_sword_viking_3_small", slot_item_multiplayer_item_class, multi_item_class_type_sword),
      (item_set_slot, "itm_bastard_sword_a", slot_item_multiplayer_item_class, multi_item_class_type_two_handed_sword),
      (item_set_slot, "itm_bastard_sword_b", slot_item_multiplayer_item_class, multi_item_class_type_two_handed_sword),
      (item_set_slot, "itm_sword_two_handed_a", slot_item_multiplayer_item_class, multi_item_class_type_two_handed_sword),
      (item_set_slot, "itm_sword_two_handed_b", slot_item_multiplayer_item_class, multi_item_class_type_two_handed_sword),
      (item_set_slot, "itm_arabian_sword_a", slot_item_multiplayer_item_class, multi_item_class_type_two_handed_sword),
      (item_set_slot, "itm_arabian_sword_b", slot_item_multiplayer_item_class, multi_item_class_type_two_handed_sword),
      (item_set_slot, "itm_sarranid_cavalry_sword", slot_item_multiplayer_item_class, multi_item_class_type_two_handed_sword),
      (item_set_slot, "itm_arabian_sword_d", slot_item_multiplayer_item_class, multi_item_class_type_two_handed_sword),
	  
      #axe
      (item_set_slot, "itm_axe", slot_item_multiplayer_item_class, multi_item_class_type_axe),
      (item_set_slot, "itm_battle_axe", slot_item_multiplayer_item_class, multi_item_class_type_axe),
      (item_set_slot, "itm_one_handed_war_axe_a", slot_item_multiplayer_item_class, multi_item_class_type_axe),
      (item_set_slot, "itm_one_handed_war_axe_b", slot_item_multiplayer_item_class, multi_item_class_type_axe),
      (item_set_slot, "itm_one_handed_battle_axe_a", slot_item_multiplayer_item_class, multi_item_class_type_axe),
      (item_set_slot, "itm_one_handed_battle_axe_b", slot_item_multiplayer_item_class, multi_item_class_type_axe),
      (item_set_slot, "itm_one_handed_battle_axe_c", slot_item_multiplayer_item_class, multi_item_class_type_axe),
	  
      (item_set_slot, "itm_two_handed_axe", slot_item_multiplayer_item_class, multi_item_class_type_two_handed_axe),
      (item_set_slot, "itm_two_handed_battle_axe_2", slot_item_multiplayer_item_class, multi_item_class_type_two_handed_axe),
      (item_set_slot, "itm_shortened_voulge", slot_item_multiplayer_item_class, multi_item_class_type_two_handed_axe),
      (item_set_slot, "itm_bardiche", slot_item_multiplayer_item_class, multi_item_class_type_two_handed_axe),
      (item_set_slot, "itm_great_axe", slot_item_multiplayer_item_class, multi_item_class_type_two_handed_axe),
      (item_set_slot, "itm_great_bardiche", slot_item_multiplayer_item_class, multi_item_class_type_two_handed_axe),
      (item_set_slot, "itm_long_axe", slot_item_multiplayer_item_class, multi_item_class_type_two_handed_axe),
      (item_set_slot, "itm_long_axe_b", slot_item_multiplayer_item_class, multi_item_class_type_two_handed_axe),
      (item_set_slot, "itm_long_axe_c", slot_item_multiplayer_item_class, multi_item_class_type_two_handed_axe),
      (item_set_slot, "itm_voulge", slot_item_multiplayer_item_class, multi_item_class_type_two_handed_axe),
      (item_set_slot, "itm_long_bardiche", slot_item_multiplayer_item_class, multi_item_class_type_two_handed_axe),
      (item_set_slot, "itm_great_long_bardiche", slot_item_multiplayer_item_class, multi_item_class_type_two_handed_axe),
	  
      #blunt
      (item_set_slot, "itm_mace_1", slot_item_multiplayer_item_class, multi_item_class_type_blunt),
      (item_set_slot, "itm_mace_2", slot_item_multiplayer_item_class, multi_item_class_type_blunt),
      (item_set_slot, "itm_mace_3", slot_item_multiplayer_item_class, multi_item_class_type_blunt),
      (item_set_slot, "itm_mace_4", slot_item_multiplayer_item_class, multi_item_class_type_blunt),
      (item_set_slot, "itm_long_spiked_club", slot_item_multiplayer_item_class, multi_item_class_type_blunt),
      (item_set_slot, "itm_long_hafted_spiked_mace", slot_item_multiplayer_item_class, multi_item_class_type_blunt),
	  
      (item_set_slot, "itm_maul", slot_item_multiplayer_item_class, multi_item_class_type_blunt),
      (item_set_slot, "itm_sledgehammer", slot_item_multiplayer_item_class, multi_item_class_type_blunt),
      (item_set_slot, "itm_warhammer", slot_item_multiplayer_item_class, multi_item_class_type_blunt),
      (item_set_slot, "itm_morningstar", slot_item_multiplayer_item_class, multi_item_class_type_blunt),
      #picks
      (item_set_slot, "itm_military_sickle_a", slot_item_multiplayer_item_class, multi_item_class_type_war_picks),
      (item_set_slot, "itm_fighting_pick", slot_item_multiplayer_item_class, multi_item_class_type_war_picks),
      (item_set_slot, "itm_military_pick", slot_item_multiplayer_item_class, multi_item_class_type_war_picks),
      (item_set_slot, "itm_club_with_spike_head", slot_item_multiplayer_item_class, multi_item_class_type_war_picks),
	  
	  #Cleavers
      (item_set_slot, "itm_military_cleaver_b", slot_item_multiplayer_item_class, multi_item_class_type_cleavers),
      (item_set_slot, "itm_military_cleaver_c", slot_item_multiplayer_item_class, multi_item_class_type_cleavers),
      (item_set_slot, "itm_two_handed_cleaver", slot_item_multiplayer_item_class, multi_item_class_type_cleavers),
      (item_set_slot, "itm_hafted_blade_a", slot_item_multiplayer_item_class, multi_item_class_type_cleavers),
      (item_set_slot, "itm_hafted_blade_b", slot_item_multiplayer_item_class, multi_item_class_type_cleavers),
      (item_set_slot, "itm_shortened_military_scythe", slot_item_multiplayer_item_class, multi_item_class_type_cleavers),
	  
      (item_set_slot, "itm_sarranid_mace_1", slot_item_multiplayer_item_class, multi_item_class_type_blunt),
      (item_set_slot, "itm_sarranid_axe_a", slot_item_multiplayer_item_class, multi_item_class_type_blunt),
      (item_set_slot, "itm_sarranid_axe_b", slot_item_multiplayer_item_class, multi_item_class_type_blunt),
      (item_set_slot, "itm_sarranid_two_handed_axe_a", slot_item_multiplayer_item_class, multi_item_class_type_two_handed_axe),
      (item_set_slot, "itm_sarranid_two_handed_axe_b", slot_item_multiplayer_item_class, multi_item_class_type_two_handed_axe),
      (item_set_slot, "itm_sarranid_two_handed_mace_1", slot_item_multiplayer_item_class, multi_item_class_type_two_handed_axe),
      (item_set_slot, "itm_bamboo_spear", slot_item_multiplayer_item_class, multi_item_class_type_spear),
	  
	  
	  
      #spears
      (item_set_slot, "itm_double_sided_lance", slot_item_multiplayer_item_class, multi_item_class_type_spear),
      (item_set_slot, "itm_glaive", slot_item_multiplayer_item_class, multi_item_class_type_spear),
      (item_set_slot, "itm_poleaxe", slot_item_multiplayer_item_class, multi_item_class_type_spear),
      (item_set_slot, "itm_polehammer", slot_item_multiplayer_item_class, multi_item_class_type_spear),
      (item_set_slot, "itm_staff", slot_item_multiplayer_item_class, multi_item_class_type_spear),
      (item_set_slot, "itm_quarter_staff", slot_item_multiplayer_item_class, multi_item_class_type_spear),
      (item_set_slot, "itm_iron_staff", slot_item_multiplayer_item_class, multi_item_class_type_spear),
	  
      (item_set_slot, "itm_shortened_spear", slot_item_multiplayer_item_class, multi_item_class_type_spear),
      (item_set_slot, "itm_spear", slot_item_multiplayer_item_class, multi_item_class_type_spear),
      (item_set_slot, "itm_war_spear", slot_item_multiplayer_item_class, multi_item_class_type_spear),
      (item_set_slot, "itm_military_scythe", slot_item_multiplayer_item_class, multi_item_class_type_spear),
      (item_set_slot, "itm_pike", slot_item_multiplayer_item_class, multi_item_class_type_spear),
      (item_set_slot, "itm_ashwood_pike", slot_item_multiplayer_item_class, multi_item_class_type_spear),
      (item_set_slot, "itm_awlpike", slot_item_multiplayer_item_class, multi_item_class_type_spear),
      (item_set_slot, "itm_awlpike_long", slot_item_multiplayer_item_class, multi_item_class_type_spear),
      #lance
      (item_set_slot, "itm_light_lance", slot_item_multiplayer_item_class, multi_item_class_type_lance),
      (item_set_slot, "itm_lance", slot_item_multiplayer_item_class, multi_item_class_type_lance),
      (item_set_slot, "itm_heavy_lance", slot_item_multiplayer_item_class, multi_item_class_type_lance),
      (item_set_slot, "itm_great_lance", slot_item_multiplayer_item_class, multi_item_class_type_lance),
      #shields
	  
      (item_set_slot, "itm_tab_shield_round_a", slot_item_multiplayer_item_class, multi_item_class_type_small_shield),
      (item_set_slot, "itm_tab_shield_round_b", slot_item_multiplayer_item_class, multi_item_class_type_small_shield),
      (item_set_slot, "itm_tab_shield_round_c", slot_item_multiplayer_item_class, multi_item_class_type_small_shield),
      (item_set_slot, "itm_tab_shield_round_d", slot_item_multiplayer_item_class, multi_item_class_type_small_shield),
      (item_set_slot, "itm_tab_shield_round_e", slot_item_multiplayer_item_class, multi_item_class_type_small_shield),
      (item_set_slot, "itm_tab_shield_kite_a", slot_item_multiplayer_item_class, multi_item_class_type_small_shield),
      (item_set_slot, "itm_tab_shield_kite_b", slot_item_multiplayer_item_class, multi_item_class_type_small_shield),
      (item_set_slot, "itm_tab_shield_kite_c", slot_item_multiplayer_item_class, multi_item_class_type_small_shield),
      (item_set_slot, "itm_tab_shield_kite_d", slot_item_multiplayer_item_class, multi_item_class_type_small_shield),
      (item_set_slot, "itm_tab_shield_kite_cav_a", slot_item_multiplayer_item_class, multi_item_class_type_small_shield),
      (item_set_slot, "itm_tab_shield_kite_cav_b", slot_item_multiplayer_item_class, multi_item_class_type_small_shield),
      (item_set_slot, "itm_tab_shield_heater_a", slot_item_multiplayer_item_class, multi_item_class_type_small_shield),
      (item_set_slot, "itm_tab_shield_heater_b", slot_item_multiplayer_item_class, multi_item_class_type_small_shield),
      (item_set_slot, "itm_tab_shield_heater_c", slot_item_multiplayer_item_class, multi_item_class_type_small_shield),
      (item_set_slot, "itm_tab_shield_heater_d", slot_item_multiplayer_item_class, multi_item_class_type_small_shield),
      (item_set_slot, "itm_tab_shield_heater_cav_a", slot_item_multiplayer_item_class, multi_item_class_type_small_shield),
      (item_set_slot, "itm_tab_shield_heater_cav_b", slot_item_multiplayer_item_class, multi_item_class_type_small_shield),
      (item_set_slot, "itm_tab_shield_pavise_a", slot_item_multiplayer_item_class, multi_item_class_type_small_shield),
      (item_set_slot, "itm_tab_shield_pavise_b", slot_item_multiplayer_item_class, multi_item_class_type_small_shield),
      (item_set_slot, "itm_tab_shield_pavise_c", slot_item_multiplayer_item_class, multi_item_class_type_small_shield),
      (item_set_slot, "itm_tab_shield_pavise_d", slot_item_multiplayer_item_class, multi_item_class_type_small_shield),
      (item_set_slot, "itm_tab_shield_small_round_a", slot_item_multiplayer_item_class, multi_item_class_type_small_shield),
      (item_set_slot, "itm_tab_shield_small_round_b", slot_item_multiplayer_item_class, multi_item_class_type_small_shield),
      (item_set_slot, "itm_tab_shield_small_round_c", slot_item_multiplayer_item_class, multi_item_class_type_small_shield),
      (item_set_slot, "itm_spear", slot_item_multiplayer_item_class, multi_item_class_type_spear),
      #throwing
      (item_set_slot, "itm_darts", slot_item_multiplayer_item_class, multi_item_class_type_throwing),
      (item_set_slot, "itm_war_darts", slot_item_multiplayer_item_class, multi_item_class_type_throwing),
      (item_set_slot, "itm_javelin", slot_item_multiplayer_item_class, multi_item_class_type_throwing), 
      (item_set_slot, "itm_jarid", slot_item_multiplayer_item_class, multi_item_class_type_throwing), 
      (item_set_slot, "itm_throwing_spears", slot_item_multiplayer_item_class, multi_item_class_type_throwing), 
	  
      (item_set_slot, "itm_throwing_axes", slot_item_multiplayer_item_class, multi_item_class_type_throwing_axe),
      (item_set_slot, "itm_light_throwing_axes", slot_item_multiplayer_item_class, multi_item_class_type_throwing_axe),
      (item_set_slot, "itm_heavy_throwing_axes", slot_item_multiplayer_item_class, multi_item_class_type_throwing_axe),
       #armors
      (item_set_slot, "itm_red_shirt", slot_item_multiplayer_item_class, multi_item_class_type_light_armor),
      (item_set_slot, "itm_red_tunic", slot_item_multiplayer_item_class, multi_item_class_type_light_armor),
      (item_set_slot, "itm_aketon_green", slot_item_multiplayer_item_class, multi_item_class_type_light_armor),
      (item_set_slot, "itm_padded_cloth", slot_item_multiplayer_item_class, multi_item_class_type_light_armor),
      (item_set_slot, "itm_red_gambeson", slot_item_multiplayer_item_class, multi_item_class_type_light_armor),
      (item_set_slot, "itm_leather_armor", slot_item_multiplayer_item_class, multi_item_class_type_light_armor),
      (item_set_slot, "itm_haubergeon", slot_item_multiplayer_item_class, multi_item_class_type_light_armor),
      (item_set_slot, "itm_coat_of_plates_red", slot_item_multiplayer_item_class, multi_item_class_type_light_armor),
      (item_set_slot, "itm_brigandine_red", slot_item_multiplayer_item_class, multi_item_class_type_light_armor),
      (item_set_slot, "itm_mail_with_surcoat", slot_item_multiplayer_item_class, multi_item_class_type_light_armor),
      (item_set_slot, "itm_linen_tunic", slot_item_multiplayer_item_class, multi_item_class_type_light_armor),
      (item_set_slot, "itm_leather_vest", slot_item_multiplayer_item_class, multi_item_class_type_light_armor),
      (item_set_slot, "itm_leather_jerkin", slot_item_multiplayer_item_class, multi_item_class_type_light_armor),
      (item_set_slot, "itm_studded_leather_coat", slot_item_multiplayer_item_class, multi_item_class_type_light_armor),
      (item_set_slot, "itm_lamellar_vest", slot_item_multiplayer_item_class, multi_item_class_type_light_armor),
      (item_set_slot, "itm_lamellar_armor", slot_item_multiplayer_item_class, multi_item_class_type_light_armor),
      (item_set_slot, "itm_coarse_tunic", slot_item_multiplayer_item_class, multi_item_class_type_light_armor),
      (item_set_slot, "itm_tribal_warrior_outfit", slot_item_multiplayer_item_class, multi_item_class_type_light_armor),
      (item_set_slot, "itm_khergit_guard_armor", slot_item_multiplayer_item_class, multi_item_class_type_light_armor),
      (item_set_slot, "itm_blue_tunic", slot_item_multiplayer_item_class, multi_item_class_type_light_armor),
      (item_set_slot, "itm_mail_hauberk", slot_item_multiplayer_item_class, multi_item_class_type_light_armor),
      (item_set_slot, "itm_mail_shirt", slot_item_multiplayer_item_class, multi_item_class_type_light_armor),
      (item_set_slot, "itm_byrnie", slot_item_multiplayer_item_class, multi_item_class_type_light_armor),
	  (item_set_slot, "itm_lamellar_vest_khergit", slot_item_multiplayer_item_class, multi_item_class_type_light_armor),
	  (item_set_slot, "itm_steppe_armor", slot_item_multiplayer_item_class, multi_item_class_type_light_armor),

	  
      (item_set_slot, "itm_banded_armor", slot_item_multiplayer_item_class, multi_item_class_type_light_armor),
      (item_set_slot, "itm_cuir_bouilli", slot_item_multiplayer_item_class, multi_item_class_type_light_armor),
      (item_set_slot, "itm_scale_armor", slot_item_multiplayer_item_class, multi_item_class_type_light_armor),
	  
      (item_set_slot, "itm_padded_leather", slot_item_multiplayer_item_class, multi_item_class_type_light_armor),
      (item_set_slot, "itm_green_tunic", slot_item_multiplayer_item_class, multi_item_class_type_light_armor),
      (item_set_slot, "itm_tunic_with_green_cape", slot_item_multiplayer_item_class, multi_item_class_type_light_armor),
      (item_set_slot, "itm_aketon_green", slot_item_multiplayer_item_class, multi_item_class_type_light_armor),
      (item_set_slot, "itm_ragged_outfit", slot_item_multiplayer_item_class, multi_item_class_type_light_armor),
      (item_set_slot, "itm_surcoat_over_mail", slot_item_multiplayer_item_class, multi_item_class_type_light_armor),

      (item_set_slot, "itm_sarranid_elite_armor", slot_item_multiplayer_item_class, multi_item_class_type_light_armor),
      (item_set_slot, "itm_skirmisher_armor", slot_item_multiplayer_item_class, multi_item_class_type_light_armor),
      (item_set_slot, "itm_archers_vest", slot_item_multiplayer_item_class, multi_item_class_type_light_armor),
      (item_set_slot, "itm_sarranid_leather_armor", slot_item_multiplayer_item_class, multi_item_class_type_light_armor),
      (item_set_slot, "itm_sarranid_cloth_robe", slot_item_multiplayer_item_class, multi_item_class_type_light_armor),
      (item_set_slot, "itm_sarranid_mail_shirt", slot_item_multiplayer_item_class, multi_item_class_type_light_armor),
      (item_set_slot, "itm_sarranid_cavalry_robe", slot_item_multiplayer_item_class, multi_item_class_type_light_armor),
      (item_set_slot, "itm_arabian_armor_b", slot_item_multiplayer_item_class, multi_item_class_type_light_armor),
      (item_set_slot, "itm_mamluke_mail", slot_item_multiplayer_item_class, multi_item_class_type_light_armor),
      (item_set_slot, "itm_khergit_elite_armor", slot_item_multiplayer_item_class, multi_item_class_type_light_armor),
      (item_set_slot, "itm_vaegir_elite_armor", slot_item_multiplayer_item_class, multi_item_class_type_light_armor),
	  (item_set_slot, "itm_khergit_armor", slot_item_multiplayer_item_class, multi_item_class_type_light_armor),

	  
	  

  
      #boots
      (item_set_slot, "itm_hide_boots", slot_item_multiplayer_item_class, multi_item_class_type_light_foot),
      (item_set_slot, "itm_ankle_boots", slot_item_multiplayer_item_class, multi_item_class_type_light_foot),
      (item_set_slot, "itm_nomad_boots", slot_item_multiplayer_item_class, multi_item_class_type_light_foot),
      (item_set_slot, "itm_leather_boots", slot_item_multiplayer_item_class, multi_item_class_type_light_foot),
      (item_set_slot, "itm_splinted_leather_greaves", slot_item_multiplayer_item_class, multi_item_class_type_light_foot),
      (item_set_slot, "itm_mail_chausses", slot_item_multiplayer_item_class, multi_item_class_type_light_foot),
      (item_set_slot, "itm_splinted_leather_greaves", slot_item_multiplayer_item_class, multi_item_class_type_light_foot),
      (item_set_slot, "itm_splinted_greaves", slot_item_multiplayer_item_class, multi_item_class_type_light_foot),
      (item_set_slot, "itm_mail_boots", slot_item_multiplayer_item_class, multi_item_class_type_light_foot),
      (item_set_slot, "itm_iron_greaves", slot_item_multiplayer_item_class, multi_item_class_type_light_foot),
      (item_set_slot, "itm_sarranid_boots_b", slot_item_multiplayer_item_class, multi_item_class_type_light_foot),
      (item_set_slot, "itm_sarranid_boots_c", slot_item_multiplayer_item_class, multi_item_class_type_light_foot),
      (item_set_slot, "itm_sarranid_boots_d", slot_item_multiplayer_item_class, multi_item_class_type_light_foot),
	  (item_set_slot, "itm_plate_boots", slot_item_multiplayer_item_class, multi_item_class_type_light_foot),
	  (item_set_slot, "itm_khergit_leather_boots", slot_item_multiplayer_item_class, multi_item_class_type_light_foot),
	  (item_set_slot, "itm_khergit_guard_boots", slot_item_multiplayer_item_class, multi_item_class_type_light_foot),

	  
	  

	  

	  
	  
      #helmets
	  
	  
      (item_set_slot, "itm_leather_steppe_cap_a", slot_item_multiplayer_item_class, multi_item_class_type_light_helm),
      (item_set_slot, "itm_leather_steppe_cap_b", slot_item_multiplayer_item_class, multi_item_class_type_light_helm),
      (item_set_slot, "itm_steppe_cap", slot_item_multiplayer_item_class, multi_item_class_type_light_helm),
      (item_set_slot, "itm_khergit_war_helmet", slot_item_multiplayer_item_class, multi_item_class_type_light_helm),
      (item_set_slot, "itm_khergit_guard_helmet", slot_item_multiplayer_item_class, multi_item_class_type_light_helm),
	  
	  
	  
      (item_set_slot, "itm_arming_cap", slot_item_multiplayer_item_class, multi_item_class_type_light_helm),
      (item_set_slot, "itm_padded_coif", slot_item_multiplayer_item_class, multi_item_class_type_light_helm),
      (item_set_slot, "itm_mail_coif", slot_item_multiplayer_item_class, multi_item_class_type_light_helm),
      (item_set_slot, "itm_footman_helmet", slot_item_multiplayer_item_class, multi_item_class_type_light_helm),
      (item_set_slot, "itm_norman_helmet", slot_item_multiplayer_item_class, multi_item_class_type_light_helm),
      (item_set_slot, "itm_kettle_hat", slot_item_multiplayer_item_class, multi_item_class_type_light_helm),
      (item_set_slot, "itm_helmet_with_neckguard", slot_item_multiplayer_item_class, multi_item_class_type_light_helm),
	  
	  (item_set_slot, "itm_bascinet_2", slot_item_multiplayer_item_class, multi_item_class_type_light_helm),
	  (item_set_slot, "itm_bascinet_3", slot_item_multiplayer_item_class, multi_item_class_type_light_helm),


	  
      (item_set_slot, "itm_flat_topped_helmet", slot_item_multiplayer_item_class, multi_item_class_type_light_helm),
      (item_set_slot, "itm_guard_helmet", slot_item_multiplayer_item_class, multi_item_class_type_light_helm),
      (item_set_slot, "itm_full_helm", slot_item_multiplayer_item_class, multi_item_class_type_light_helm),
      (item_set_slot, "itm_great_helmet", slot_item_multiplayer_item_class, multi_item_class_type_light_helm),
      (item_set_slot, "itm_nomad_cap_b", slot_item_multiplayer_item_class, multi_item_class_type_light_helm),
      (item_set_slot, "itm_skullcap", slot_item_multiplayer_item_class, multi_item_class_type_light_helm),
      (item_set_slot, "itm_leather_cap", slot_item_multiplayer_item_class, multi_item_class_type_light_helm),

      (item_set_slot, "itm_spiked_helmet", slot_item_multiplayer_item_class, multi_item_class_type_light_helm),
#      (item_set_slot, "itm_nasal_helmet", slot_item_multiplayer_item_class, multi_item_class_type_light_helm),
      (item_set_slot, "itm_nordic_archer_helmet", slot_item_multiplayer_item_class, multi_item_class_type_light_helm),
      (item_set_slot, "itm_nordic_veteran_archer_helmet", slot_item_multiplayer_item_class, multi_item_class_type_light_helm),
      (item_set_slot, "itm_nordic_footman_helmet", slot_item_multiplayer_item_class, multi_item_class_type_light_helm),
      (item_set_slot, "itm_nordic_fighter_helmet", slot_item_multiplayer_item_class, multi_item_class_type_light_helm),
      (item_set_slot, "itm_nordic_huscarl_helmet", slot_item_multiplayer_item_class, multi_item_class_type_light_helm),
      (item_set_slot, "itm_nordic_warlord_helmet", slot_item_multiplayer_item_class, multi_item_class_type_light_helm),

      (item_set_slot, "itm_sarranid_helmet1", slot_item_multiplayer_item_class, multi_item_class_type_light_helm),
      (item_set_slot, "itm_sarranid_horseman_helmet", slot_item_multiplayer_item_class, multi_item_class_type_light_helm),
      (item_set_slot, "itm_sarranid_felt_hat", slot_item_multiplayer_item_class, multi_item_class_type_light_helm),
      (item_set_slot, "itm_sarranid_veiled_helmet", slot_item_multiplayer_item_class, multi_item_class_type_light_helm),
      (item_set_slot, "itm_turban", slot_item_multiplayer_item_class, multi_item_class_type_light_helm),
      (item_set_slot, "itm_desert_turban", slot_item_multiplayer_item_class, multi_item_class_type_light_helm),
      (item_set_slot, "itm_sarranid_warrior_cap", slot_item_multiplayer_item_class, multi_item_class_type_light_helm),
      (item_set_slot, "itm_sarranid_mail_coif", slot_item_multiplayer_item_class, multi_item_class_type_light_helm),

      (item_set_slot, "itm_vaegir_fur_cap", slot_item_multiplayer_item_class, multi_item_class_type_light_helm),
      (item_set_slot, "itm_vaegir_fur_helmet", slot_item_multiplayer_item_class, multi_item_class_type_light_helm),
      (item_set_slot, "itm_vaegir_spiked_helmet", slot_item_multiplayer_item_class, multi_item_class_type_light_helm),
      (item_set_slot, "itm_vaegir_lamellar_helmet", slot_item_multiplayer_item_class, multi_item_class_type_light_helm),
      (item_set_slot, "itm_vaegir_noble_helmet", slot_item_multiplayer_item_class, multi_item_class_type_light_helm),
      (item_set_slot, "itm_vaegir_war_helmet", slot_item_multiplayer_item_class, multi_item_class_type_light_helm),
      (item_set_slot, "itm_vaegir_mask", slot_item_multiplayer_item_class, multi_item_class_type_light_helm),
	  
	  
	  #gloves
      (item_set_slot, "itm_leather_gloves", slot_item_multiplayer_item_class, multi_item_class_type_glove),           
      (item_set_slot, "itm_mail_mittens", slot_item_multiplayer_item_class, multi_item_class_type_glove),           
      (item_set_slot, "itm_scale_gauntlets", slot_item_multiplayer_item_class, multi_item_class_type_glove),
	  (item_set_slot, "itm_lamellar_gauntlets", slot_item_multiplayer_item_class, multi_item_class_type_glove),	  
	  (item_set_slot, "itm_gauntlets", slot_item_multiplayer_item_class, multi_item_class_type_glove),
	  
      #horses
      (item_set_slot, "itm_saddle_horse", slot_item_multiplayer_item_class, multi_item_class_type_horse),
      (item_set_slot, "itm_hunter", slot_item_multiplayer_item_class, multi_item_class_type_horse),
      (item_set_slot, "itm_courser", slot_item_multiplayer_item_class, multi_item_class_type_horse),
      (item_set_slot, "itm_hunter", slot_item_multiplayer_item_class, multi_item_class_type_horse),
      (item_set_slot, "itm_warhorse", slot_item_multiplayer_item_class, multi_item_class_type_horse),
      (item_set_slot, "itm_charger", slot_item_multiplayer_item_class, multi_item_class_type_horse),
      (item_set_slot, "itm_steppe_horse", slot_item_multiplayer_item_class, multi_item_class_type_horse),
      (item_set_slot, "itm_arabian_horse_a", slot_item_multiplayer_item_class, multi_item_class_type_horse),
      (item_set_slot, "itm_arabian_horse_b", slot_item_multiplayer_item_class, multi_item_class_type_horse),
	  (item_set_slot, "itm_warhorse_steppe", slot_item_multiplayer_item_class, multi_item_class_type_horse),
	  (item_set_slot, "itm_warhorse_sarranid", slot_item_multiplayer_item_class, multi_item_class_type_horse),
	  

      #1-Swadian Warriors
      #1a-Swadian Crossbowman
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_bolts", "trp_swadian_crossbowman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_steel_bolts", "trp_swadian_crossbowman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_crossbow", "trp_swadian_crossbowman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_heavy_crossbow", "trp_swadian_crossbowman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sniper_crossbow", "trp_swadian_crossbowman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sword_medieval_a", "trp_swadian_crossbowman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sword_medieval_b", "trp_swadian_crossbowman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sword_medieval_b_small", "trp_swadian_crossbowman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tab_shield_heater_a", "trp_swadian_crossbowman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tab_shield_heater_b", "trp_swadian_crossbowman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tab_shield_heater_c", "trp_swadian_crossbowman_multiplayer"),

      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_red_shirt", "trp_swadian_crossbowman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_padded_cloth", "trp_swadian_crossbowman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_leather_armor", "trp_swadian_crossbowman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_haubergeon", "trp_swadian_crossbowman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_ankle_boots", "trp_swadian_crossbowman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_leather_boots", "trp_swadian_crossbowman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_mail_chausses", "trp_swadian_crossbowman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_leather_gloves", "trp_swadian_crossbowman_multiplayer"),
	  
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_arming_cap", "trp_swadian_crossbowman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_norman_helmet", "trp_swadian_crossbowman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_helmet_with_neckguard", "trp_swadian_crossbowman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_flat_topped_helmet", "trp_swadian_crossbowman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_guard_helmet", "trp_swadian_crossbowman_multiplayer"),

      #1b-Swadian Infantry
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_awlpike", "trp_swadian_infantry_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_awlpike_long", "trp_swadian_infantry_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sword_medieval_a", "trp_swadian_infantry_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sword_medieval_b", "trp_swadian_infantry_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sword_medieval_b_small", "trp_swadian_infantry_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sword_medieval_c", "trp_swadian_infantry_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sword_medieval_c_small", "trp_swadian_infantry_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_bastard_sword_a", "trp_swadian_infantry_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_bastard_sword_b", "trp_swadian_infantry_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sword_two_handed_a", "trp_swadian_infantry_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sword_two_handed_b", "trp_swadian_infantry_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_darts", "trp_swadian_infantry_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_war_darts", "trp_swadian_infantry_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tab_shield_heater_a", "trp_swadian_infantry_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tab_shield_heater_b", "trp_swadian_infantry_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tab_shield_heater_c", "trp_swadian_infantry_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tab_shield_heater_d", "trp_swadian_infantry_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_red_tunic", "trp_swadian_infantry_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_red_gambeson", "trp_swadian_infantry_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_leather_armor", "trp_swadian_infantry_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_haubergeon", "trp_swadian_infantry_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_brigandine_red", "trp_swadian_infantry_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_ankle_boots", "trp_swadian_infantry_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_leather_boots", "trp_swadian_infantry_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_mail_chausses", "trp_swadian_infantry_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_splinted_greaves", "trp_swadian_infantry_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_arming_cap", "trp_swadian_infantry_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_norman_helmet", "trp_swadian_infantry_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_helmet_with_neckguard", "trp_swadian_infantry_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_flat_topped_helmet", "trp_swadian_infantry_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_guard_helmet", "trp_swadian_infantry_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_great_helmet", "trp_swadian_infantry_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_leather_gloves", "trp_swadian_infantry_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_mail_mittens", "trp_swadian_infantry_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_scale_gauntlets", "trp_swadian_infantry_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_gauntlets", "trp_swadian_infantry_multiplayer"),

      #1c-Swadian Man At Arms
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_darts", "trp_swadian_man_at_arms_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_war_darts", "trp_swadian_man_at_arms_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_lance", "trp_swadian_man_at_arms_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_heavy_lance", "trp_swadian_man_at_arms_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_great_lance", "trp_swadian_man_at_arms_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sword_medieval_a", "trp_swadian_man_at_arms_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sword_medieval_b", "trp_swadian_man_at_arms_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sword_medieval_b_small", "trp_swadian_man_at_arms_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sword_medieval_c", "trp_swadian_man_at_arms_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sword_medieval_c_small", "trp_swadian_man_at_arms_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_bastard_sword_a", "trp_swadian_man_at_arms_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_bastard_sword_b", "trp_swadian_man_at_arms_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tab_shield_heater_a", "trp_swadian_man_at_arms_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tab_shield_heater_b", "trp_swadian_man_at_arms_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tab_shield_heater_c", "trp_swadian_man_at_arms_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tab_shield_heater_d", "trp_swadian_man_at_arms_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_red_tunic", "trp_swadian_man_at_arms_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_padded_cloth", "trp_swadian_man_at_arms_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_leather_armor", "trp_swadian_man_at_arms_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_mail_with_surcoat", "trp_swadian_man_at_arms_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_coat_of_plates_red", "trp_swadian_man_at_arms_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_ankle_boots", "trp_swadian_man_at_arms_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_leather_boots", "trp_swadian_man_at_arms_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_mail_chausses", "trp_swadian_man_at_arms_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_splinted_greaves", "trp_swadian_man_at_arms_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_plate_boots", "trp_swadian_man_at_arms_multiplayer"),
	  
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_arming_cap", "trp_swadian_man_at_arms_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_norman_helmet", "trp_swadian_man_at_arms_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_helmet_with_neckguard", "trp_swadian_man_at_arms_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_flat_topped_helmet", "trp_swadian_man_at_arms_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_guard_helmet", "trp_swadian_man_at_arms_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_great_helmet", "trp_swadian_man_at_arms_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_leather_gloves", "trp_swadian_man_at_arms_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_mail_mittens", "trp_swadian_man_at_arms_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_scale_gauntlets", "trp_swadian_man_at_arms_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_gauntlets", "trp_swadian_man_at_arms_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_saddle_horse", "trp_swadian_man_at_arms_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_courser", "trp_swadian_man_at_arms_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_hunter", "trp_swadian_man_at_arms_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_warhorse", "trp_swadian_man_at_arms_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_charger", "trp_swadian_man_at_arms_multiplayer"),

      # #1d-Swadian Mounted Crossbowman
      # (call_script, "script_multiplayer_set_item_available_for_troop", "itm_bolts", "trp_swadian_mounted_crossbowman_multiplayer"),
      # (call_script, "script_multiplayer_set_item_available_for_troop", "itm_light_crossbow", "trp_swadian_mounted_crossbowman_multiplayer"),
      # (call_script, "script_multiplayer_set_item_available_for_troop", "itm_crossbow", "trp_swadian_mounted_crossbowman_multiplayer"),
      # (call_script, "script_multiplayer_set_item_available_for_troop", "itm_heavy_crossbow", "trp_swadian_mounted_crossbowman_multiplayer"),
      # (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tab_shield_heater_cav_a", "trp_swadian_mounted_crossbowman_multiplayer"),
      # (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tab_shield_heater_cav_b", "trp_swadian_mounted_crossbowman_multiplayer"),
      # (call_script, "script_multiplayer_set_item_available_for_troop", "itm_bastard_sword_a", "trp_swadian_mounted_crossbowman_multiplayer"),
      # (call_script, "script_multiplayer_set_item_available_for_troop", "itm_red_shirt", "trp_swadian_mounted_crossbowman_multiplayer"),
      # (call_script, "script_multiplayer_set_item_available_for_troop", "itm_padded_cloth", "trp_swadian_mounted_crossbowman_multiplayer"),
      # (call_script, "script_multiplayer_set_item_available_for_troop", "itm_leather_armor", "trp_swadian_mounted_crossbowman_multiplayer"),
      # (call_script, "script_multiplayer_set_item_available_for_troop", "itm_mail_with_surcoat", "trp_swadian_mounted_crossbowman_multiplayer"),
      # (call_script, "script_multiplayer_set_item_available_for_troop", "itm_coat_of_plates_red", "trp_swadian_mounted_crossbowman_multiplayer"),
      # (call_script, "script_multiplayer_set_item_available_for_troop", "itm_hide_boots", "trp_swadian_mounted_crossbowman_multiplayer"),
      # (call_script, "script_multiplayer_set_item_available_for_troop", "itm_arming_cap", "trp_swadian_mounted_crossbowman_multiplayer"),
      # (call_script, "script_multiplayer_set_item_available_for_troop", "itm_norman_helmet", "trp_swadian_mounted_crossbowman_multiplayer"),
      # (call_script, "script_multiplayer_set_item_available_for_troop", "itm_helmet_with_neckguard", "trp_swadian_mounted_crossbowman_multiplayer"),
      # (call_script, "script_multiplayer_set_item_available_for_troop", "itm_flat_topped_helmet", "trp_swadian_mounted_crossbowman_multiplayer"),
      # (call_script, "script_multiplayer_set_item_available_for_troop", "itm_guard_helmet", "trp_swadian_mounted_crossbowman_multiplayer"),
      # (call_script, "script_multiplayer_set_item_available_for_troop", "itm_leather_gloves", "trp_swadian_mounted_crossbowman_multiplayer"),
      # (call_script, "script_multiplayer_set_item_available_for_troop", "itm_saddle_horse", "trp_swadian_mounted_crossbowman_multiplayer"),
      # (call_script, "script_multiplayer_set_item_available_for_troop", "itm_courser", "trp_swadian_mounted_crossbowman_multiplayer"),
      # (call_script, "script_multiplayer_set_item_available_for_troop", "itm_hunter", "trp_swadian_mounted_crossbowman_multiplayer"),

      #2-Vaegir Warriors
      #2a-Vaegir Archer
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_arrows", "trp_vaegir_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_barbed_arrows", "trp_vaegir_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_scimitar", "trp_vaegir_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_mace_1", "trp_vaegir_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_mace_2", "trp_vaegir_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_nomad_bow", "trp_vaegir_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_khergit_bow", "trp_vaegir_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_strong_bow", "trp_vaegir_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_war_bow", "trp_vaegir_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_linen_tunic", "trp_vaegir_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_leather_jerkin", "trp_vaegir_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_leather_vest", "trp_vaegir_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_lamellar_vest", "trp_vaegir_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_hide_boots", "trp_vaegir_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_nomad_boots", "trp_vaegir_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_splinted_leather_greaves", "trp_vaegir_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_nomad_cap", "trp_vaegir_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_vaegir_fur_cap", "trp_vaegir_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_vaegir_fur_helmet", "trp_vaegir_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_vaegir_spiked_helmet", "trp_vaegir_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_vaegir_lamellar_helmet", "trp_vaegir_archer_multiplayer"),
      
      #2b-Vaegir Spearman
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_spear", "trp_vaegir_spearman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_war_spear", "trp_vaegir_spearman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_awlpike", "trp_vaegir_spearman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tab_shield_kite_a", "trp_vaegir_spearman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tab_shield_kite_b", "trp_vaegir_spearman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tab_shield_kite_c", "trp_vaegir_spearman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tab_shield_kite_d", "trp_vaegir_spearman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_mace_1", "trp_vaegir_spearman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_mace_2", "trp_vaegir_spearman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_mace_3", "trp_vaegir_spearman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_mace_4", "trp_vaegir_spearman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_long_hafted_spiked_mace", "trp_vaegir_spearman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_long_spiked_club", "trp_vaegir_spearman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_scimitar", "trp_vaegir_spearman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_scimitar_b", "trp_vaegir_spearman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_bardiche", "trp_vaegir_spearman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_great_bardiche", "trp_vaegir_spearman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_long_bardiche", "trp_vaegir_spearman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_great_long_bardiche", "trp_vaegir_spearman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_javelin", "trp_vaegir_spearman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_linen_tunic", "trp_vaegir_spearman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_leather_jerkin", "trp_vaegir_spearman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_leather_vest", "trp_vaegir_spearman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_lamellar_vest", "trp_vaegir_spearman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_lamellar_armor", "trp_vaegir_spearman_multiplayer"),
	  (call_script, "script_multiplayer_set_item_available_for_troop", "itm_vaegir_elite_armor", "trp_vaegir_spearman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_hide_boots", "trp_vaegir_spearman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_nomad_boots", "trp_vaegir_spearman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_splinted_leather_greaves", "trp_vaegir_spearman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_splinted_greaves", "trp_vaegir_spearman_multiplayer"),
#      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_spiked_helmet", "trp_vaegir_spearman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_vaegir_fur_cap", "trp_vaegir_spearman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_vaegir_fur_helmet", "trp_vaegir_spearman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_vaegir_spiked_helmet", "trp_vaegir_spearman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_vaegir_lamellar_helmet", "trp_vaegir_spearman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_vaegir_noble_helmet", "trp_vaegir_spearman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_vaegir_war_helmet", "trp_vaegir_spearman_multiplayer"),
	  #      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_nasal_helmet", "trp_vaegir_spearman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_leather_gloves", "trp_vaegir_spearman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_mail_mittens", "trp_vaegir_spearman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_scale_gauntlets", "trp_vaegir_spearman_multiplayer"),

      #2c-Vaegir Horseman
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_darts", "trp_vaegir_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_war_darts", "trp_vaegir_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_bardiche", "trp_vaegir_horseman_multiplayer"),
#      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_great_bardiche", "trp_vaegir_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_scimitar", "trp_vaegir_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_scimitar_b", "trp_vaegir_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_lance", "trp_vaegir_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_heavy_lance", "trp_vaegir_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tab_shield_kite_cav_a", "trp_vaegir_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tab_shield_kite_cav_b", "trp_vaegir_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tab_shield_kite_c", "trp_vaegir_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tab_shield_kite_d", "trp_vaegir_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_linen_tunic", "trp_vaegir_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_leather_vest", "trp_vaegir_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_lamellar_vest", "trp_vaegir_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_studded_leather_coat", "trp_vaegir_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_lamellar_armor", "trp_vaegir_horseman_multiplayer"),
	  (call_script, "script_multiplayer_set_item_available_for_troop", "itm_vaegir_elite_armor", "trp_vaegir_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_hide_boots", "trp_vaegir_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_nomad_boots", "trp_vaegir_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_splinted_leather_greaves", "trp_vaegir_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_splinted_greaves", "trp_vaegir_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_plate_boots", "trp_vaegir_horseman_multiplayer"),
#      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_spiked_helmet", "trp_vaegir_horseman_multiplayer"),
#      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_nasal_helmet", "trp_vaegir_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_vaegir_fur_cap", "trp_vaegir_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_vaegir_fur_helmet", "trp_vaegir_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_vaegir_spiked_helmet", "trp_vaegir_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_vaegir_lamellar_helmet", "trp_vaegir_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_vaegir_noble_helmet", "trp_vaegir_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_vaegir_war_helmet", "trp_vaegir_horseman_multiplayer"),
	  (call_script, "script_multiplayer_set_item_available_for_troop", "itm_vaegir_mask", "trp_vaegir_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_leather_gloves", "trp_vaegir_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_mail_mittens", "trp_vaegir_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_scale_gauntlets", "trp_vaegir_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_saddle_horse", "trp_vaegir_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_courser", "trp_vaegir_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_hunter", "trp_vaegir_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_warhorse_steppe", "trp_vaegir_horseman_multiplayer"),
   
      #3-Khergit Warriors
      #3a-Khergit Veteran Horse Archer
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sword_khergit_1", "trp_khergit_veteran_horse_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sword_khergit_2", "trp_khergit_veteran_horse_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sword_khergit_3", "trp_khergit_veteran_horse_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sword_khergit_4", "trp_khergit_veteran_horse_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_nomad_bow", "trp_khergit_veteran_horse_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_khergit_bow", "trp_khergit_veteran_horse_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_strong_bow", "trp_khergit_veteran_horse_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_arrows", "trp_khergit_veteran_horse_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_khergit_arrows", "trp_khergit_veteran_horse_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tab_shield_small_round_a", "trp_khergit_veteran_horse_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tab_shield_small_round_b", "trp_khergit_veteran_horse_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_leather_steppe_cap_a", "trp_khergit_veteran_horse_archer_multiplayer"),
	  (call_script, "script_multiplayer_set_item_available_for_troop", "itm_nomad_cap_b", "trp_khergit_veteran_horse_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_leather_steppe_cap_b", "trp_khergit_veteran_horse_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_steppe_cap", "trp_khergit_veteran_horse_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_khergit_armor", "trp_khergit_veteran_horse_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_steppe_armor", "trp_khergit_veteran_horse_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tribal_warrior_outfit", "trp_khergit_veteran_horse_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_lamellar_vest_khergit", "trp_khergit_veteran_horse_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_hide_boots", "trp_khergit_veteran_horse_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_nomad_boots", "trp_khergit_veteran_horse_archer_multiplayer"),
	  (call_script, "script_multiplayer_set_item_available_for_troop", "itm_khergit_leather_boots", "trp_khergit_veteran_horse_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_splinted_leather_greaves", "trp_khergit_veteran_horse_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_splinted_greaves", "trp_khergit_veteran_horse_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_steppe_horse", "trp_khergit_veteran_horse_archer_multiplayer"),
	  (call_script, "script_multiplayer_set_item_available_for_troop", "itm_leather_gloves", "trp_khergit_veteran_horse_archer_multiplayer"),
      #3a-Khergit Lancer
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_javelin", "trp_khergit_lancer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sword_khergit_1", "trp_khergit_lancer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sword_khergit_2", "trp_khergit_lancer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sword_khergit_3", "trp_khergit_lancer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sword_khergit_4", "trp_khergit_lancer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tab_shield_small_round_a", "trp_khergit_lancer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tab_shield_small_round_b", "trp_khergit_lancer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tab_shield_small_round_c", "trp_khergit_lancer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_lance", "trp_khergit_lancer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_heavy_lance", "trp_khergit_lancer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_hafted_blade_a", "trp_khergit_lancer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_hafted_blade_b", "trp_khergit_lancer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_mace_1", "trp_khergit_lancer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_mace_2", "trp_khergit_lancer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_mace_3", "trp_khergit_lancer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_one_handed_war_axe_a", "trp_khergit_lancer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_one_handed_war_axe_b", "trp_khergit_lancer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_leather_steppe_cap_a", "trp_khergit_lancer_multiplayer"),
	  (call_script, "script_multiplayer_set_item_available_for_troop", "itm_nomad_cap_b", "trp_khergit_lancer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_leather_steppe_cap_b", "trp_khergit_lancer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_steppe_cap", "trp_khergit_lancer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_khergit_war_helmet", "trp_khergit_lancer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_khergit_guard_helmet", "trp_khergit_lancer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_khergit_armor", "trp_khergit_lancer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_steppe_armor", "trp_khergit_lancer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tribal_warrior_outfit", "trp_khergit_lancer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_lamellar_armor", "trp_khergit_lancer_multiplayer"),
	  (call_script, "script_multiplayer_set_item_available_for_troop", "itm_khergit_elite_armor", "trp_khergit_lancer_multiplayer"),	  
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_hide_boots", "trp_khergit_lancer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_nomad_boots", "trp_khergit_lancer_multiplayer"),
	  (call_script, "script_multiplayer_set_item_available_for_troop", "itm_khergit_leather_boots", "trp_khergit_lancer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_splinted_leather_greaves", "trp_khergit_lancer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_splinted_greaves", "trp_khergit_lancer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_leather_gloves", "trp_khergit_lancer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_mail_mittens", "trp_khergit_lancer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_scale_gauntlets", "trp_khergit_lancer_multiplayer"),
	  (call_script, "script_multiplayer_set_item_available_for_troop", "itm_lamellar_gauntlets", "trp_khergit_lancer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_steppe_horse", "trp_khergit_lancer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_courser", "trp_khergit_lancer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_hunter", "trp_khergit_lancer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_warhorse_steppe", "trp_khergit_lancer_multiplayer"),
      
      #Nord Warriors 

      #4c-Nord Archer
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_arrows", "trp_nord_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_barbed_arrows", "trp_nord_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_bodkin_arrows", "trp_nord_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sword_viking_1", "trp_nord_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sword_viking_2", "trp_nord_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sword_viking_2_small", "trp_nord_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sword_viking_3", "trp_nord_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sword_viking_3_small", "trp_nord_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_one_handed_war_axe_a", "trp_nord_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_one_handed_war_axe_b", "trp_nord_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_two_handed_axe", "trp_nord_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_short_bow", "trp_nord_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_long_bow", "trp_nord_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_blue_tunic", "trp_nord_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_leather_jerkin", "trp_nord_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_byrnie", "trp_nord_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_leather_boots", "trp_nord_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_splinted_leather_greaves", "trp_nord_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_mail_chausses", "trp_nord_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_mail_boots", "trp_nord_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_nordic_archer_helmet", "trp_nord_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_nordic_veteran_archer_helmet", "trp_nord_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_nordic_footman_helmet", "trp_nord_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_nordic_fighter_helmet", "trp_nord_archer_multiplayer"),
 
      #4a-Nord Veteran      
#      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_darts", "trp_nord_veteran_multiplayer"),
#      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_war_darts", "trp_nord_veteran_multiplayer"),
#      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_javelin", "trp_nord_veteran_multiplayer"),
#      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_throwing_spears", "trp_nord_veteran_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sword_viking_1", "trp_nord_veteran_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sword_viking_2", "trp_nord_veteran_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sword_viking_2_small", "trp_nord_veteran_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sword_viking_3", "trp_nord_veteran_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sword_viking_3_small", "trp_nord_veteran_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_one_handed_war_axe_a", "trp_nord_veteran_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_one_handed_war_axe_b", "trp_nord_veteran_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_one_handed_battle_axe_a", "trp_nord_veteran_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_one_handed_battle_axe_b", "trp_nord_veteran_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_one_handed_battle_axe_c", "trp_nord_veteran_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_two_handed_axe", "trp_nord_veteran_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_two_handed_battle_axe_2", "trp_nord_veteran_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_great_axe", "trp_nord_veteran_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_long_axe", "trp_nord_veteran_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_long_axe_b", "trp_nord_veteran_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_long_axe_c", "trp_nord_veteran_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_spear", "trp_nord_veteran_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_war_spear", "trp_nord_veteran_multiplayer"),
	  
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tab_shield_round_a", "trp_nord_veteran_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tab_shield_round_b", "trp_nord_veteran_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tab_shield_round_c", "trp_nord_veteran_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tab_shield_round_d", "trp_nord_veteran_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tab_shield_round_e", "trp_nord_veteran_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_light_throwing_axes", "trp_nord_veteran_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_throwing_axes", "trp_nord_veteran_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_heavy_throwing_axes", "trp_nord_veteran_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_nordic_veteran_archer_helmet", "trp_nord_veteran_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_nordic_footman_helmet", "trp_nord_veteran_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_nordic_fighter_helmet", "trp_nord_veteran_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_nordic_huscarl_helmet", "trp_nord_veteran_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_nordic_warlord_helmet", "trp_nord_veteran_multiplayer"),	  
	  
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_blue_tunic", "trp_nord_veteran_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_leather_jerkin", "trp_nord_veteran_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_mail_shirt", "trp_nord_veteran_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_mail_hauberk", "trp_nord_veteran_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_banded_armor", "trp_nord_veteran_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_leather_boots", "trp_nord_veteran_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_splinted_leather_greaves", "trp_nord_veteran_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_mail_chausses", "trp_nord_veteran_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_mail_boots", "trp_nord_veteran_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_leather_gloves", "trp_nord_veteran_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_mail_mittens", "trp_nord_veteran_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_scale_gauntlets", "trp_nord_veteran_multiplayer"),
            
      #4b-Nord Scout
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_darts", "trp_nord_scout_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_war_darts", "trp_nord_scout_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_javelin", "trp_nord_scout_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_throwing_spears", "trp_nord_scout_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_light_throwing_axes", "trp_nord_scout_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_throwing_axes", "trp_nord_scout_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sword_viking_1", "trp_nord_scout_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sword_viking_2", "trp_nord_scout_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sword_viking_3", "trp_nord_scout_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_two_handed_axe", "trp_nord_scout_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_two_handed_battle_axe_2", "trp_nord_scout_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_shortened_voulge", "trp_nord_scout_multiplayer"),
	  
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_spear", "trp_nord_scout_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_war_spear", "trp_nord_scout_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_light_lance", "trp_nord_scout_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_lance", "trp_nord_scout_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tab_shield_small_round_a", "trp_nord_scout_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tab_shield_small_round_b", "trp_nord_scout_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tab_shield_small_round_c", "trp_nord_scout_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_nordic_archer_helmet", "trp_nord_scout_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_nordic_veteran_archer_helmet", "trp_nord_scout_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_nordic_footman_helmet", "trp_nord_scout_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_nordic_fighter_helmet", "trp_nord_scout_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_nordic_huscarl_helmet", "trp_nord_scout_multiplayer"),


      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_blue_tunic", "trp_nord_scout_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_leather_jerkin", "trp_nord_scout_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_mail_shirt", "trp_nord_scout_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_mail_hauberk", "trp_nord_scout_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_leather_boots", "trp_nord_scout_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_splinted_leather_greaves", "trp_nord_scout_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_mail_chausses", "trp_nord_scout_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_mail_boots", "trp_nord_scout_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_leather_gloves", "trp_nord_scout_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_mail_mittens", "trp_nord_scout_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_scale_gauntlets", "trp_nord_scout_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_saddle_horse", "trp_nord_scout_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_courser", "trp_nord_scout_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_hunter", "trp_nord_scout_multiplayer"),
            
      
      #5-Rhodok Warriors         
      #5a-Rhodok Veteran Crossbowman
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_crossbow", "trp_rhodok_veteran_crossbowman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_heavy_crossbow", "trp_rhodok_veteran_crossbowman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sniper_crossbow", "trp_rhodok_veteran_crossbowman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_bolts", "trp_rhodok_veteran_crossbowman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_steel_bolts", "trp_rhodok_veteran_crossbowman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_fighting_pick", "trp_rhodok_veteran_crossbowman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_military_pick", "trp_rhodok_veteran_crossbowman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_club_with_spike_head", "trp_rhodok_veteran_crossbowman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_maul", "trp_rhodok_veteran_crossbowman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sledgehammer", "trp_rhodok_veteran_crossbowman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sword_medieval_a", "trp_rhodok_veteran_crossbowman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sword_medieval_b", "trp_rhodok_veteran_crossbowman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sword_medieval_b_small", "trp_rhodok_veteran_crossbowman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tab_shield_pavise_a", "trp_rhodok_veteran_crossbowman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tab_shield_pavise_b", "trp_rhodok_veteran_crossbowman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tab_shield_pavise_c", "trp_rhodok_veteran_crossbowman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tab_shield_pavise_d", "trp_rhodok_veteran_crossbowman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_leather_cap", "trp_rhodok_veteran_crossbowman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_padded_coif", "trp_rhodok_veteran_crossbowman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_footman_helmet", "trp_rhodok_veteran_crossbowman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_kettle_hat", "trp_rhodok_veteran_crossbowman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tunic_with_green_cape", "trp_rhodok_veteran_crossbowman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_aketon_green", "trp_rhodok_veteran_crossbowman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_leather_armor", "trp_rhodok_veteran_crossbowman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_ankle_boots", "trp_rhodok_veteran_crossbowman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_leather_boots", "trp_rhodok_veteran_crossbowman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_splinted_greaves", "trp_rhodok_veteran_crossbowman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_leather_gloves", "trp_rhodok_veteran_crossbowman_multiplayer"),

	  #5b-Rhodok Sergeant
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_darts", "trp_rhodok_sergeant_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_war_darts", "trp_rhodok_sergeant_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_javelin", "trp_rhodok_sergeant_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_fighting_pick", "trp_rhodok_sergeant_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_military_pick", "trp_rhodok_sergeant_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_morningstar", "trp_rhodok_sergeant_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_club_with_spike_head", "trp_rhodok_sergeant_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_military_cleaver_b", "trp_rhodok_sergeant_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_military_cleaver_c", "trp_rhodok_sergeant_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_two_handed_cleaver", "trp_rhodok_sergeant_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_military_sickle_a", "trp_rhodok_sergeant_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_maul", "trp_rhodok_sergeant_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sledgehammer", "trp_rhodok_sergeant_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_warhammer", "trp_rhodok_sergeant_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_spear", "trp_rhodok_sergeant_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_pike", "trp_rhodok_sergeant_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_ashwood_pike", "trp_rhodok_sergeant_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_war_spear", "trp_rhodok_sergeant_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_glaive", "trp_rhodok_sergeant_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tab_shield_pavise_a", "trp_rhodok_sergeant_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tab_shield_pavise_b", "trp_rhodok_sergeant_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tab_shield_pavise_c", "trp_rhodok_sergeant_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tab_shield_pavise_d", "trp_rhodok_sergeant_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_leather_cap", "trp_rhodok_sergeant_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_padded_coif", "trp_rhodok_sergeant_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_footman_helmet", "trp_rhodok_sergeant_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_kettle_hat", "trp_rhodok_sergeant_multiplayer"),
	  (call_script, "script_multiplayer_set_item_available_for_troop", "itm_bascinet_2", "trp_rhodok_sergeant_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_full_helm", "trp_rhodok_sergeant_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_green_tunic", "trp_rhodok_sergeant_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_aketon_green", "trp_rhodok_sergeant_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_ragged_outfit", "trp_rhodok_sergeant_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_leather_armor", "trp_rhodok_sergeant_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_surcoat_over_mail", "trp_rhodok_sergeant_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_ankle_boots", "trp_rhodok_sergeant_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_leather_boots", "trp_rhodok_sergeant_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_splinted_greaves", "trp_rhodok_sergeant_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_iron_greaves", "trp_rhodok_sergeant_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_leather_gloves", "trp_rhodok_sergeant_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_mail_mittens", "trp_rhodok_sergeant_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_scale_gauntlets", "trp_rhodok_sergeant_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_gauntlets", "trp_rhodok_sergeant_multiplayer"),

	  #5c-Rhodok Horseman
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_darts", "trp_rhodok_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_war_darts", "trp_rhodok_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_javelin", "trp_rhodok_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sword_medieval_a", "trp_rhodok_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sword_medieval_b", "trp_rhodok_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sword_medieval_c", "trp_rhodok_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_fighting_pick", "trp_rhodok_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_military_pick", "trp_rhodok_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_morningstar", "trp_rhodok_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_military_cleaver_b", "trp_rhodok_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_military_cleaver_c", "trp_rhodok_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_two_handed_cleaver", "trp_rhodok_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_shortened_military_scythe", "trp_rhodok_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_light_lance", "trp_rhodok_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_lance", "trp_rhodok_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_heavy_lance", "trp_rhodok_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tab_shield_heater_cav_a", "trp_rhodok_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tab_shield_heater_cav_b", "trp_rhodok_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_padded_coif", "trp_rhodok_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_footman_helmet", "trp_rhodok_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_kettle_hat", "trp_rhodok_horseman_multiplayer"),
	  (call_script, "script_multiplayer_set_item_available_for_troop", "itm_bascinet_3", "trp_rhodok_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_green_tunic", "trp_rhodok_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_aketon_green", "trp_rhodok_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_ragged_outfit", "trp_rhodok_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_leather_armor", "trp_rhodok_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_surcoat_over_mail", "trp_rhodok_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_ankle_boots", "trp_rhodok_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_leather_boots", "trp_rhodok_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_splinted_greaves", "trp_rhodok_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_plate_boots", "trp_rhodok_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_leather_gloves", "trp_rhodok_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_mail_mittens", "trp_rhodok_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_scale_gauntlets", "trp_rhodok_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_gauntlets", "trp_rhodok_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_saddle_horse", "trp_rhodok_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_courser", "trp_rhodok_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_hunter", "trp_rhodok_horseman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_warhorse", "trp_rhodok_horseman_multiplayer"),
	  
	  
	  
      #6-Sarranid Warriors         
      #5a-Sarranid archer
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sarranid_cloth_robe", "trp_sarranid_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_skirmisher_armor", "trp_sarranid_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_archers_vest", "trp_sarranid_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_arabian_armor_b", "trp_sarranid_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sarranid_felt_hat", "trp_sarranid_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_turban", "trp_sarranid_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_desert_turban", "trp_sarranid_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sarranid_mail_coif", "trp_sarranid_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sarranid_horseman_helmet", "trp_sarranid_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sarranid_warrior_cap", "trp_sarranid_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sarranid_boots_b", "trp_sarranid_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sarranid_boots_c", "trp_sarranid_archer_multiplayer"),
	  
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_short_bow", "trp_sarranid_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_nomad_bow", "trp_sarranid_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_arrows", "trp_sarranid_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_barbed_arrows", "trp_sarranid_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_scimitar", "trp_sarranid_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_mace_1", "trp_sarranid_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_arabian_sword_a", "trp_sarranid_archer_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_arabian_sword_b", "trp_sarranid_archer_multiplayer"),
	  
	  (call_script, "script_multiplayer_set_item_available_for_troop", "itm_leather_gloves", "trp_sarranid_archer_multiplayer"),
     
	  
	  
	  #Sarranid footman
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sarranid_cloth_robe", "trp_sarranid_footman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_skirmisher_armor", "trp_sarranid_footman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_archers_vest", "trp_sarranid_footman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sarranid_leather_armor", "trp_sarranid_footman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_arabian_armor_b", "trp_sarranid_footman_multiplayer"),
	  
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sarranid_elite_armor", "trp_sarranid_footman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sarranid_felt_hat", "trp_sarranid_footman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_turban", "trp_sarranid_footman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_desert_turban", "trp_sarranid_footman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sarranid_mail_coif", "trp_sarranid_footman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sarranid_warrior_cap", "trp_sarranid_footman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sarranid_veiled_helmet", "trp_sarranid_footman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sarranid_boots_b", "trp_sarranid_footman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sarranid_boots_c", "trp_sarranid_footman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sarranid_boots_d", "trp_sarranid_footman_multiplayer"),
	  
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_arabian_sword_a", "trp_sarranid_footman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_arabian_sword_b", "trp_sarranid_footman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_arabian_sword_d", "trp_sarranid_footman_multiplayer"),

      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sarranid_mace_1", "trp_sarranid_footman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sarranid_axe_a", "trp_sarranid_footman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sarranid_axe_b", "trp_sarranid_footman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sarranid_two_handed_axe_a", "trp_sarranid_footman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sarranid_two_handed_axe_b", "trp_sarranid_footman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sarranid_two_handed_mace_1", "trp_sarranid_footman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_bamboo_spear", "trp_sarranid_footman_multiplayer"),
	  
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_spear", "trp_sarranid_footman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_jarid", "trp_sarranid_footman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_javelin", "trp_sarranid_footman_multiplayer"),
	  
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tab_shield_kite_a", "trp_sarranid_footman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tab_shield_kite_b", "trp_sarranid_footman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tab_shield_kite_c", "trp_sarranid_footman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tab_shield_kite_d", "trp_sarranid_footman_multiplayer"),
	  
	  (call_script, "script_multiplayer_set_item_available_for_troop", "itm_leather_gloves", "trp_sarranid_footman_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_mail_mittens", "trp_sarranid_footman_multiplayer"),
	  (call_script, "script_multiplayer_set_item_available_for_troop", "itm_scale_gauntlets", "trp_sarranid_footman_multiplayer"),
	  
	  
	  

	  #Sarranid mamluke
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sarranid_cloth_robe", "trp_sarranid_mamluke_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_skirmisher_armor", "trp_sarranid_mamluke_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_archers_vest", "trp_sarranid_mamluke_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sarranid_mail_shirt", "trp_sarranid_mamluke_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sarranid_cavalry_robe", "trp_sarranid_mamluke_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_mamluke_mail", "trp_sarranid_mamluke_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sarranid_elite_armor", "trp_sarranid_mamluke_multiplayer"),


      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_turban", "trp_sarranid_mamluke_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_desert_turban", "trp_sarranid_mamluke_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sarranid_horseman_helmet", "trp_sarranid_mamluke_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sarranid_mail_coif", "trp_sarranid_mamluke_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sarranid_veiled_helmet", "trp_sarranid_mamluke_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sarranid_boots_b", "trp_sarranid_mamluke_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sarranid_boots_c", "trp_sarranid_mamluke_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sarranid_boots_d", "trp_sarranid_mamluke_multiplayer"),
	  
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_arabian_sword_a", "trp_sarranid_mamluke_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_arabian_sword_b", "trp_sarranid_mamluke_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sarranid_cavalry_sword", "trp_sarranid_mamluke_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_arabian_sword_d", "trp_sarranid_mamluke_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sarranid_mace_1", "trp_sarranid_mamluke_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sarranid_axe_a", "trp_sarranid_mamluke_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sarranid_axe_b", "trp_sarranid_mamluke_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_sarranid_two_handed_axe_a", "trp_sarranid_mamluke_multiplayer"),
	  
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_lance", "trp_sarranid_mamluke_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_heavy_lance", "trp_sarranid_mamluke_multiplayer"),

      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_jarid", "trp_sarranid_mamluke_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_javelin", "trp_sarranid_mamluke_multiplayer"),
	  
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tab_shield_small_round_a", "trp_sarranid_mamluke_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tab_shield_small_round_b", "trp_sarranid_mamluke_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_tab_shield_small_round_c", "trp_sarranid_mamluke_multiplayer"),
	  
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_saddle_horse", "trp_sarranid_mamluke_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_arabian_horse_a", "trp_sarranid_mamluke_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_arabian_horse_b", "trp_sarranid_mamluke_multiplayer"),
      (call_script, "script_multiplayer_set_item_available_for_troop", "itm_warhorse_sarranid", "trp_sarranid_mamluke_multiplayer"),
	  
	  (call_script, "script_multiplayer_set_item_available_for_troop", "itm_leather_gloves", "trp_sarranid_mamluke_multiplayer"),
	  (call_script, "script_multiplayer_set_item_available_for_troop", "itm_mail_mittens", "trp_sarranid_mamluke_multiplayer"),
	  (call_script, "script_multiplayer_set_item_available_for_troop", "itm_scale_gauntlets", "trp_sarranid_mamluke_multiplayer"),


      ]),

  #script_get_army_size_from_slider_value
  # INPUT: arg1 = slider_value
  # OUTPUT: reg0 = army_size
  ("get_army_size_from_slider_value",
    [
     (store_script_param, ":slider_value", 1),
     (assign, ":army_size", ":slider_value"),
     (try_begin),
       (gt, ":slider_value", 25),
       (store_sub, ":adder_value", ":slider_value", 25),
       (val_add, ":army_size", ":adder_value"),
       (try_begin),
         (gt, ":slider_value", 50),
         (store_sub, ":adder_value", ":slider_value", 50),
         (val_mul, ":adder_value", 3),
         (val_add, ":army_size", ":adder_value"),
       (try_end),
     (try_end),
     (assign, reg0, ":army_size"),
  ]),
  
  #script_spawn_quick_battle_army
  # INPUT: arg1 = initial_entry_point, arg2 = faction_no, arg3 = infantry_ratio, arg4 = archers_ratio, arg5 = cavalry_ratio, arg6 = divide_archer_entry_points, arg7 = player_team
  # OUTPUT: none
  ("spawn_quick_battle_army",
   [
     (store_script_param, ":cur_entry_point", 1),
     (store_script_param, ":faction_no", 2),
     (store_script_param, ":infantry_ratio", 3),
     (store_script_param, ":archers_ratio", 4),
     (store_script_param, ":cavalry_ratio", 5),
     (store_script_param, ":divide_archer_entry_points", 6),
     (store_script_param, ":player_team", 7),

     (try_begin),
       (eq, ":player_team", 1),
       (call_script, "script_get_army_size_from_slider_value", "$g_quick_battle_army_1_size"),
       (assign, ":army_size", reg0),
       (set_player_troop, "$g_quick_battle_troop"),
       (set_visitor, ":cur_entry_point", "$g_quick_battle_troop"),
       (try_begin),
         (eq, ":cur_entry_point", 0),
         (try_begin),
           (is_between, ":faction_no", npc_kingdoms_begin, npc_kingdoms_end),
           (faction_get_slot, "$g_quick_battle_team_0_banner", ":faction_no", slot_faction_banner),
         (else_try),
           (assign, "$g_quick_battle_team_0_banner", "mesh_banners_default_b"),
         (try_end),
       (else_try),
         (try_begin),
           (is_between, ":faction_no", npc_kingdoms_begin, npc_kingdoms_end),
           (faction_get_slot, "$g_quick_battle_team_1_banner", ":faction_no", slot_faction_banner),
         (else_try),
           (assign, "$g_quick_battle_team_1_banner", "mesh_banners_default_b"),
         (try_end),
       (try_end),
       (val_add, ":cur_entry_point", 1),

     (else_try),
       (call_script, "script_get_army_size_from_slider_value", "$g_quick_battle_army_2_size"),
       (assign, ":army_size", reg0),
       (try_begin),
         (eq, ":cur_entry_point", 0),
         (assign, "$g_quick_battle_team_0_banner", "mesh_banners_default_a"),
       (else_try),
         (assign, "$g_quick_battle_team_1_banner", "mesh_banners_default_a"),
       (try_end),
       (val_add, ":cur_entry_point", 1),
     (try_end),

     (store_mul, ":num_infantry", ":infantry_ratio", ":army_size"),
     (val_div, ":num_infantry", 100),
     (store_mul, ":num_archers", ":archers_ratio", ":army_size"),
     (val_div, ":num_archers", 100),
     (store_mul, ":num_cavalry", ":cavalry_ratio", ":army_size"),
     (val_div, ":num_cavalry", 100),

     (try_begin),
       (store_add, ":num_total", ":num_infantry", ":num_archers"),
       (val_add, ":num_total", ":num_cavalry"),
       (neq, ":num_total", ":army_size"),
       (store_sub, ":leftover", ":army_size", ":num_total"),
       (try_begin),
         (gt, ":infantry_ratio", ":archers_ratio"),
         (gt, ":infantry_ratio", ":cavalry_ratio"),
         (val_add, ":num_infantry", ":leftover"),
       (else_try),
         (gt, ":archers_ratio", ":cavalry_ratio"),
         (val_add, ":num_archers", ":leftover"),
       (else_try),
         (val_add, ":num_cavalry", ":leftover"),
       (try_end),
     (try_end),

     (store_mul, ":rand_min", ":num_infantry", 15),
     (val_div, ":rand_min", 100),
     (store_mul, ":rand_max", ":num_infantry", 45),
     (val_div, ":rand_max", 100),
     (store_random_in_range, ":num_tier_2_infantry", ":rand_min", ":rand_max"),
     (store_sub, ":num_tier_1_infantry", ":num_infantry", ":num_tier_2_infantry"),
     (store_mul, ":rand_min", ":num_archers", 15),
     (val_div, ":rand_min", 100),
     (store_mul, ":rand_max", ":num_archers", 45),
     (val_div, ":rand_max", 100),
     (store_random_in_range, ":num_tier_2_archers", ":rand_min", ":rand_max"),
     (store_sub, ":num_tier_1_archers", ":num_archers", ":num_tier_2_archers"),
     (store_mul, ":rand_min", ":num_cavalry", 15),
     (val_div, ":rand_min", 100),
     (store_mul, ":rand_max", ":num_cavalry", 45),
     (val_div, ":rand_max", 100),
     (store_random_in_range, ":num_tier_2_cavalry", ":rand_min", ":rand_max"),
     (store_sub, ":num_tier_1_cavalry", ":num_cavalry", ":num_tier_2_cavalry"),

     (faction_get_slot, ":cur_troop", ":faction_no", slot_faction_quick_battle_tier_2_infantry),
     (set_visitors, ":cur_entry_point", ":cur_troop", ":num_tier_2_infantry"),
     (val_add, ":cur_entry_point", 1),
     (faction_get_slot, ":cur_troop", ":faction_no", slot_faction_quick_battle_tier_1_infantry),
     (set_visitors, ":cur_entry_point", ":cur_troop", ":num_tier_1_infantry"),
     (val_add, ":cur_entry_point", 1),
     (faction_get_slot, ":cur_troop", ":faction_no", slot_faction_quick_battle_tier_2_cavalry),
     (set_visitors, ":cur_entry_point", ":cur_troop", ":num_tier_2_cavalry"),
     (val_add, ":cur_entry_point", 1),
     (faction_get_slot, ":cur_troop", ":faction_no", slot_faction_quick_battle_tier_1_cavalry),
     (set_visitors, ":cur_entry_point", ":cur_troop", ":num_tier_1_cavalry"),
     (val_add, ":cur_entry_point", 1),

     (try_begin),
       (eq, ":divide_archer_entry_points", 0),
       (faction_get_slot, ":cur_troop", ":faction_no", slot_faction_quick_battle_tier_2_archer),
       (set_visitors, ":cur_entry_point", ":cur_troop", ":num_tier_2_archers"),
       (val_add, ":cur_entry_point", 1),
       (faction_get_slot, ":cur_troop", ":faction_no", slot_faction_quick_battle_tier_1_archer),
       (set_visitors, ":cur_entry_point", ":cur_troop", ":num_tier_1_archers"),
       (val_add, ":cur_entry_point", 1),
     (else_try),
       (assign, ":cur_entry_point", 40), #archer positions begin point
       (store_div, ":num_tier_1_archers_ceil_8", ":num_tier_1_archers", 8),
       (val_mul, ":num_tier_1_archers_ceil_8", 8),
       (try_begin),
         (neq, ":num_tier_1_archers_ceil_8", ":num_tier_1_archers"),
         (val_div, ":num_tier_1_archers_ceil_8", 8),
         (val_add, ":num_tier_1_archers_ceil_8", 1),
         (val_mul, ":num_tier_1_archers_ceil_8", 8),
       (try_end),
       (store_div, ":num_tier_2_archers_ceil_8", ":num_tier_2_archers", 8),
       (val_mul, ":num_tier_2_archers_ceil_8", 8),
       (try_begin),
         (neq, ":num_tier_2_archers_ceil_8", ":num_tier_2_archers"),
         (val_div, ":num_tier_2_archers_ceil_8", 8),
         (val_add, ":num_tier_2_archers_ceil_8", 1),
         (val_mul, ":num_tier_2_archers_ceil_8", 8),
       (try_end),
       (store_add, ":num_archers_ceil_8", ":num_tier_1_archers_ceil_8", ":num_tier_2_archers_ceil_8"),
       (store_div, ":num_archers_per_entry_point", ":num_archers_ceil_8", 8),
       (assign, ":left_tier_1_archers", ":num_tier_1_archers"),
       (assign, ":left_tier_2_archers", ":num_tier_2_archers"),
       (assign, ":end_cond", 1000),
       (try_for_range, ":unused", 0, ":end_cond"),
         (try_begin),
           (gt, ":left_tier_2_archers", 0),
           (assign, ":used_tier_2_archers", ":num_archers_per_entry_point"),
           (val_min, ":used_tier_2_archers", ":left_tier_2_archers"),
           (faction_get_slot, ":cur_troop", ":faction_no", slot_faction_quick_battle_tier_2_archer),
           (set_visitors, ":cur_entry_point", ":cur_troop", ":used_tier_2_archers"),
           (val_add, ":cur_entry_point", 1),
           (val_sub, ":left_tier_2_archers", ":used_tier_2_archers"),
         (else_try),
           (gt, ":left_tier_1_archers", 0),
           (assign, ":used_tier_1_archers", ":num_archers_per_entry_point"),
           (val_min, ":used_tier_1_archers", ":left_tier_1_archers"),
           (faction_get_slot, ":cur_troop", ":faction_no", slot_faction_quick_battle_tier_1_archer),
           (set_visitors, ":cur_entry_point", ":cur_troop", ":used_tier_1_archers"),
           (val_add, ":cur_entry_point", 1),
           (val_sub, ":left_tier_1_archers", ":used_tier_1_archers"),
         (else_try),
           (assign, ":end_cond", 0),
         (try_end),
       (try_end),
     (try_end),
     ]),

  ("player_arrived",
   [
      (assign, ":player_faction_culture", "fac_culture_1"),
      (faction_set_slot, "fac_player_supporters_faction",  slot_faction_culture, ":player_faction_culture"),
      (faction_set_slot, "fac_player_faction",  slot_faction_culture, ":player_faction_culture"),
	]),


  #script_game_set_multiplayer_mission_end
  # This script is called from the game engine when a multiplayer map is ended in clients (not in server).
  # INPUT:
  # none
  # OUTPUT:
  # none
  ("game_set_multiplayer_mission_end",
    [
      (assign, "$g_multiplayer_mission_end_screen", 1),
  ]),
  #script_game_enable_cheat_menu
  # This script is called from the game engine when user enters "cheatmenu from command console (ctrl+~).
  # INPUT:
  # none
  # OUTPUT:
  # none
  ("game_enable_cheat_menu",
    [
      (store_script_param, ":input", 1),
      (try_begin),
        (eq, ":input", 0),
        (assign, "$cheat_mode", 0),
      (else_try),
        (eq, ":input", 1),
        (assign, "$cheat_mode", 1),
      (try_end),
      ]),

  #script_game_get_console_command
  # This script is called from the game engine when a console command is entered from the dedicated server.
  # INPUT: anything
  # OUTPUT: s0 = result text
  ("game_get_console_command",
   [
     (store_script_param, ":input", 1),
     (store_script_param, ":val1", 2),
     (try_begin),
       #getting val2 for some commands
       (eq, ":input", 2),
       (store_script_param, ":val2", 3),
     (end_try),
     (try_begin),
       (eq, ":input", 1),
       (assign, reg0, ":val1"),
       (try_begin),
         (eq, ":val1", 1),
         (assign, reg1, "$g_multiplayer_num_bots_team_1"),
         (str_store_string, s0, "str_team_reg0_bot_count_is_reg1"),
       (else_try),
         (eq, ":val1", 2),
         (assign, reg1, "$g_multiplayer_num_bots_team_2"),
         (str_store_string, s0, "str_team_reg0_bot_count_is_reg1"),
       (else_try),
         (str_store_string, s0, "str_input_is_not_correct_for_the_command_type_help_for_more_information"),
       (try_end),
     (else_try),
       (eq, ":input", 2),
       (assign, reg0, ":val1"),
       (assign, reg1, ":val2"),
       (try_begin),
         (eq, ":val1", 1),
         (ge, ":val2", 0),
         (assign, "$g_multiplayer_num_bots_team_1", ":val2"),
         (str_store_string, s0, "str_team_reg0_bot_count_is_reg1"),
       (else_try),
         (eq, ":val1", 2),
         (ge, ":val2", 0),
         (assign, "$g_multiplayer_num_bots_team_2", ":val2"),
         (str_store_string, s0, "str_team_reg0_bot_count_is_reg1"),
       (else_try),
         (str_store_string, s0, "str_input_is_not_correct_for_the_command_type_help_for_more_information"),
       (try_end),
     (else_try),
       (eq, ":input", 3),
       (assign, reg0, "$g_multiplayer_round_max_seconds"),
       (str_store_string, s0, "str_maximum_seconds_for_round_is_reg0"),
     (else_try),
       (eq, ":input", 4),
       (assign, reg0, ":val1"),
       (try_begin),
         (is_between, ":val1", multiplayer_round_max_seconds_min, multiplayer_round_max_seconds_max),
         (assign, "$g_multiplayer_round_max_seconds", ":val1"),
         (str_store_string, s0, "str_maximum_seconds_for_round_is_reg0"),
         (get_max_players, ":num_players"),
         (try_for_range, ":cur_player", 1, ":num_players"),
           (player_is_active, ":cur_player"),
           (multiplayer_send_int_to_player, ":cur_player", multiplayer_event_return_round_max_seconds, ":val1"),
         (try_end),            
       (else_try),
         (str_store_string, s0, "str_input_is_not_correct_for_the_command_type_help_for_more_information"),
       (try_end),
     (else_try),
       (eq, ":input", 5),
       (assign, reg0, "$g_multiplayer_respawn_period"),
       (str_store_string, s0, "str_respawn_period_is_reg0_seconds"),
     (else_try),
       (eq, ":input", 6),
       (assign, reg0, ":val1"),
       (try_begin),
         (is_between, ":val1", multiplayer_respawn_period_min, multiplayer_respawn_period_max),
         (assign, "$g_multiplayer_respawn_period", ":val1"),
         (str_store_string, s0, "str_respawn_period_is_reg0_seconds"),
       (else_try),
         (str_store_string, s0, "str_input_is_not_correct_for_the_command_type_help_for_more_information"),
       (try_end),
     (else_try),
       (eq, ":input", 7),
       (assign, reg0, "$g_multiplayer_num_bots_voteable"),
       (str_store_string, s0, "str_bots_upper_limit_for_votes_is_reg0"),
     (else_try),
       (eq, ":input", 8),
       (try_begin),
         (is_between, ":val1", 0, 51),
         (assign, "$g_multiplayer_num_bots_voteable", ":val1"),
         (store_add, "$g_multiplayer_max_num_bots", ":val1", 1),
         (assign, reg0, "$g_multiplayer_num_bots_voteable"),
         (str_store_string, s0, "str_bots_upper_limit_for_votes_is_reg0"),
         (get_max_players, ":num_players"),
         (try_for_range, ":cur_player", 1, ":num_players"),
           (player_is_active, ":cur_player"),
           (multiplayer_send_int_to_player, ":cur_player", multiplayer_event_return_num_bots_voteable, ":val1"),
         (try_end),
       (else_try),
         (str_store_string, s0, "str_input_is_not_correct_for_the_command_type_help_for_more_information"),
       (try_end),
     (else_try),
       (eq, ":input", 9),
       (try_begin),
         (eq, "$g_multiplayer_maps_voteable", 1),
         (str_store_string, s0, "str_map_is_voteable"),
       (else_try),
         (str_store_string, s0, "str_map_is_not_voteable"),
       (try_end),
     (else_try),
       (eq, ":input", 10),
       (try_begin),
         (is_between, ":val1", 0, 2),
         (assign, "$g_multiplayer_maps_voteable", ":val1"),
         (try_begin),
           (eq, ":val1", 1),
           (str_store_string, s0, "str_map_is_voteable"),
         (else_try),
           (str_store_string, s0, "str_map_is_not_voteable"),
         (try_end),
         (get_max_players, ":num_players"),
         (try_for_range, ":cur_player", 1, ":num_players"),
           (player_is_active, ":cur_player"),
           (multiplayer_send_int_to_player, ":cur_player", multiplayer_event_return_maps_voteable, ":val1"),
         (try_end),
       (else_try),
         (str_store_string, s0, "str_input_is_not_correct_for_the_command_type_help_for_more_information"),
       (try_end),
     (else_try),
       (eq, ":input", 11),
       (try_begin),
         (eq, "$g_multiplayer_factions_voteable", 1),
         (str_store_string, s0, "str_factions_are_voteable"),
       (else_try),
         (str_store_string, s0, "str_factions_are_not_voteable"),
       (try_end),
     (else_try),
       (eq, ":input", 12),
       (try_begin),
         (is_between, ":val1", 0, 2),
         (assign, "$g_multiplayer_factions_voteable", ":val1"),
         (try_begin),
           (eq, ":val1", 1),
           (str_store_string, s0, "str_factions_are_voteable"),
         (else_try),
           (str_store_string, s0, "str_factions_are_not_voteable"),
         (try_end),
         (get_max_players, ":num_players"),
         (try_for_range, ":cur_player", 1, ":num_players"),
           (player_is_active, ":cur_player"),
           (multiplayer_send_int_to_player, ":cur_player", multiplayer_event_return_factions_voteable, ":val1"),
         (try_end),
       (else_try),
         (str_store_string, s0, "str_input_is_not_correct_for_the_command_type_help_for_more_information"),
       (try_end),
     (else_try),
       (eq, ":input", 13),
       (try_begin),
         (eq, "$g_multiplayer_player_respawn_as_bot", 1),
         (str_store_string, s0, "str_players_respawn_as_bot"),
       (else_try),
         (str_store_string, s0, "str_players_do_not_respawn_as_bot"),
       (try_end),
     (else_try),
       (eq, ":input", 14),
       (try_begin),
         (is_between, ":val1", 0, 2),
         (assign, "$g_multiplayer_player_respawn_as_bot", ":val1"),
         (try_begin),
           (eq, ":val1", 1),
           (str_store_string, s0, "str_players_respawn_as_bot"),
         (else_try),
           (str_store_string, s0, "str_players_do_not_respawn_as_bot"),
         (try_end),
         (get_max_players, ":num_players"),
         (try_for_range, ":cur_player", 1, ":num_players"),
           (player_is_active, ":cur_player"),
           (multiplayer_send_int_to_player, ":cur_player", multiplayer_event_return_player_respawn_as_bot, ":val1"),
         (try_end),            
       (else_try),
         (str_store_string, s0, "str_input_is_not_correct_for_the_command_type_help_for_more_information"),
       (try_end),
     (else_try),
       (eq, ":input", 15),
       (try_begin),
         (eq, "$g_multiplayer_kick_voteable", 1),
         (str_store_string, s0, "str_kicking_a_player_is_voteable"),
       (else_try),
         (str_store_string, s0, "str_kicking_a_player_is_not_voteable"),
       (try_end),
     (else_try),
       (eq, ":input", 16),
       (try_begin),
         (is_between, ":val1", 0, 2),
         (assign, "$g_multiplayer_kick_voteable", ":val1"),
         (try_begin),
           (eq, ":val1", 1),
           (str_store_string, s0, "str_kicking_a_player_is_voteable"),
         (else_try),
           (str_store_string, s0, "str_kicking_a_player_is_not_voteable"),
         (try_end),
         (get_max_players, ":num_players"),
         (try_for_range, ":cur_player", 1, ":num_players"),
           (player_is_active, ":cur_player"),
           (multiplayer_send_int_to_player, ":cur_player", multiplayer_event_return_kick_voteable, ":val1"),
         (try_end),
       (else_try),
         (str_store_string, s0, "str_input_is_not_correct_for_the_command_type_help_for_more_information"),
       (try_end),
     (else_try),
       (eq, ":input", 17),
       (try_begin),
         (eq, "$g_multiplayer_ban_voteable", 1),
         (str_store_string, s0, "str_banning_a_player_is_voteable"),
       (else_try),
         (str_store_string, s0, "str_banning_a_player_is_not_voteable"),
       (try_end),
     (else_try),
       (eq, ":input", 18),
       (try_begin),
         (is_between, ":val1", 0, 2),
         (assign, "$g_multiplayer_ban_voteable", ":val1"),
         (try_begin),
           (eq, ":val1", 1),
           (str_store_string, s0, "str_banning_a_player_is_voteable"),
         (else_try),
           (str_store_string, s0, "str_banning_a_player_is_not_voteable"),
         (try_end),
         (get_max_players, ":num_players"),
         (try_for_range, ":cur_player", 1, ":num_players"),
           (player_is_active, ":cur_player"),
           (multiplayer_send_int_to_player, ":cur_player", multiplayer_event_return_ban_voteable, ":val1"),
         (try_end),
       (else_try),
         (str_store_string, s0, "str_input_is_not_correct_for_the_command_type_help_for_more_information"),
       (try_end),
     (else_try),
       (eq, ":input", 19),
       (assign, reg0, "$g_multiplayer_valid_vote_ratio"),
       (str_store_string, s0, "str_percentage_of_yes_votes_required_for_a_poll_to_get_accepted_is_reg0"),
     (else_try),
       (eq, ":input", 20),
       (try_begin),
         (is_between, ":val1", 50, 101),
         (assign, "$g_multiplayer_valid_vote_ratio", ":val1"),
         (assign, reg0, ":val1"),
         (str_store_string, s0, "str_percentage_of_yes_votes_required_for_a_poll_to_get_accepted_is_reg0"),
       (else_try),
         (str_store_string, s0, "str_input_is_not_correct_for_the_command_type_help_for_more_information"),
       (try_end),
     (else_try),
       (eq, ":input", 21),
       (assign, reg0, "$g_multiplayer_auto_team_balance_limit"),
       (str_store_string, s0, "str_auto_team_balance_threshold_is_reg0"),
     (else_try),
       (eq, ":input", 22),
       (try_begin),
         (is_between, ":val1", 2, 7),
         (assign, "$g_multiplayer_auto_team_balance_limit", ":val1"),
         (assign, reg0, "$g_multiplayer_auto_team_balance_limit"),
         (str_store_string, s0, "str_auto_team_balance_threshold_is_reg0"),
         (get_max_players, ":num_players"),
         (try_for_range, ":cur_player", 1, ":num_players"),
           (player_is_active, ":cur_player"),
           (multiplayer_send_int_to_player, ":cur_player", multiplayer_event_return_auto_team_balance_limit, ":val1"),
         (try_end),
       (else_try),
         (ge, ":val1", 7),
         (assign, "$g_multiplayer_auto_team_balance_limit", 1000),
         (assign, reg0, "$g_multiplayer_auto_team_balance_limit"),
         (str_store_string, s0, "str_auto_team_balance_threshold_is_reg0"),
         (get_max_players, ":num_players"),
         (try_for_range, ":cur_player", 1, ":num_players"),
           (player_is_active, ":cur_player"),
           (multiplayer_send_int_to_player, ":cur_player", multiplayer_event_return_auto_team_balance_limit, ":val1"),
         (try_end),
       (else_try),
         (str_store_string, s0, "str_input_is_not_correct_for_the_command_type_help_for_more_information"),
       (try_end),
     (else_try),
       (eq, ":input", 23),
       (assign, reg0, "$g_multiplayer_initial_gold_multiplier"),
       (str_store_string, s0, "str_starting_gold_ratio_is_reg0"),
     (else_try),
       (eq, ":input", 24),
       (try_begin),
         (is_between, ":val1", 0, 1001),
         (assign, "$g_multiplayer_initial_gold_multiplier", ":val1"),
         (assign, reg0, "$g_multiplayer_initial_gold_multiplier"),
         (str_store_string, s0, "str_starting_gold_ratio_is_reg0"),
       (else_try),
         (str_store_string, s0, "str_input_is_not_correct_for_the_command_type_help_for_more_information"),
       (try_end),
     (else_try),
       (eq, ":input", 25),
       (assign, reg0, "$g_multiplayer_battle_earnings_multiplier"),
       (str_store_string, s0, "str_combat_gold_bonus_ratio_is_reg0"),
     (else_try),
       (eq, ":input", 26),
       (try_begin),
         (is_between, ":val1", 0, 1001),
         (assign, "$g_multiplayer_battle_earnings_multiplier", ":val1"),
         (assign, reg0, "$g_multiplayer_battle_earnings_multiplier"),
         (str_store_string, s0, "str_combat_gold_bonus_ratio_is_reg0"),
       (else_try),
         (str_store_string, s0, "str_input_is_not_correct_for_the_command_type_help_for_more_information"),
       (try_end),
     (else_try),
       (eq, ":input", 27),
       (assign, reg0, "$g_multiplayer_round_earnings_multiplier"),
       (str_store_string, s0, "str_round_gold_bonus_ratio_is_reg0"),
     (else_try),
       (eq, ":input", 28),
       (try_begin),
         (is_between, ":val1", 0, 1001),
         (assign, "$g_multiplayer_round_earnings_multiplier", ":val1"),
         (assign, reg0, "$g_multiplayer_round_earnings_multiplier"),
         (str_store_string, s0, "str_round_gold_bonus_ratio_is_reg0"),
       (else_try),
         (str_store_string, s0, "str_input_is_not_correct_for_the_command_type_help_for_more_information"),
       (try_end),
     (else_try),
       (eq, ":input", 29),
       (try_begin),
         (eq, "$g_multiplayer_allow_player_banners", 1),
         (str_store_string, s0, "str_player_banners_are_allowed"),
       (else_try),
         (str_store_string, s0, "str_player_banners_are_not_allowed"),
       (try_end),
     (else_try),
       (eq, ":input", 30),
       (try_begin),
         (is_between, ":val1", 0, 2),
         (assign, "$g_multiplayer_allow_player_banners", ":val1"),
         (try_begin),
           (eq, ":val1", 1),
           (str_store_string, s0, "str_player_banners_are_allowed"),
         (else_try),
           (str_store_string, s0, "str_player_banners_are_not_allowed"),
         (try_end),
       (else_try),
         (str_store_string, s0, "str_input_is_not_correct_for_the_command_type_help_for_more_information"),
       (try_end),
     (else_try),
       (eq, ":input", 31),
       (try_begin),
         (eq, "$g_multiplayer_force_default_armor", 1),
         (str_store_string, s0, "str_default_armor_is_forced"),
       (else_try),
         (str_store_string, s0, "str_default_armor_is_not_forced"),
       (try_end),
     (else_try),
       (eq, ":input", 32),
       (try_begin),
         (is_between, ":val1", 0, 2),
         (assign, "$g_multiplayer_force_default_armor", ":val1"),
         (try_begin),
           (eq, ":val1", 1),
           (str_store_string, s0, "str_default_armor_is_forced"),
         (else_try),
           (str_store_string, s0, "str_default_armor_is_not_forced"),
         (try_end),
       (else_try),
         (str_store_string, s0, "str_input_is_not_correct_for_the_command_type_help_for_more_information"),
       (try_end),
     (else_try),
       (eq, ":input", 33),
       (assign, reg0, "$g_multiplayer_point_gained_from_flags"),
       (str_store_string, s0, "str_point_gained_from_flags_is_reg0"),
     (else_try),
       (eq, ":input", 34),
       (try_begin),
         (is_between, ":val1", 25, 401),
         (assign, "$g_multiplayer_point_gained_from_flags", ":val1"),
         (assign, reg0, "$g_multiplayer_point_gained_from_flags"),
         (str_store_string, s0, "str_point_gained_from_flags_is_reg0"),
       (else_try),
         (str_store_string, s0, "str_input_is_not_correct_for_the_command_type_help_for_more_information"),
       (try_end),
     (else_try),
       (eq, ":input", 35),
       (assign, reg0, "$g_multiplayer_point_gained_from_capturing_flag"),
       (str_store_string, s0, "str_point_gained_from_capturing_flag_is_reg0"),
     (else_try),
       (eq, ":input", 36),
       (try_begin),
         (is_between, ":val1", 0, 11),
         (assign, "$g_multiplayer_point_gained_from_capturing_flag", ":val1"),
         (assign, reg0, "$g_multiplayer_point_gained_from_capturing_flag"),
         (str_store_string, s0, "str_point_gained_from_capturing_flag_is_reg0"),
       (else_try),
         (str_store_string, s0, "str_input_is_not_correct_for_the_command_type_help_for_more_information"),
       (try_end),
     (else_try),
       (eq, ":input", 37),
       (assign, reg0, "$g_multiplayer_game_max_minutes"),
       (str_store_string, s0, "str_map_time_limit_is_reg0"),
     (else_try),
       (eq, ":input", 38),
       (try_begin),
         (is_between, ":val1", 5, 121),
         (assign, "$g_multiplayer_game_max_minutes", ":val1"),
         (assign, reg0, "$g_multiplayer_game_max_minutes"),
         (str_store_string, s0, "str_map_time_limit_is_reg0"),
       (else_try),
         (str_store_string, s0, "str_input_is_not_correct_for_the_command_type_help_for_more_information"),
       (try_end),
     (else_try),
       (eq, ":input", 39),
       (assign, reg0, "$g_multiplayer_game_max_points"),
       (str_store_string, s0, "str_team_points_limit_is_reg0"),
     (else_try),
       (eq, ":input", 40),
       (try_begin),
         (is_between, ":val1", 3, 1001),
         (assign, "$g_multiplayer_game_max_points", ":val1"),
         (assign, reg0, "$g_multiplayer_game_max_points"),
         (str_store_string, s0, "str_team_points_limit_is_reg0"),
       (else_try),
         (str_store_string, s0, "str_input_is_not_correct_for_the_command_type_help_for_more_information"),
       (try_end),
     (else_try),
       (eq, ":input", 41),
       (assign, reg0, "$g_multiplayer_number_of_respawn_count"),
       (try_begin),
         (eq, reg0, 0),
         (str_store_string, s1, "str_unlimited"),
       (else_try),
         (str_store_string, s1, "str_reg0"),
       (try_end),
       (str_store_string, s0, "str_defender_spawn_count_limit_is_s1"),
     (else_try),
       (eq, ":input", 42),
       (try_begin),
         (is_between, ":val1", 0, 6),
         (assign, "$g_multiplayer_number_of_respawn_count", ":val1"),
         (assign, reg0, "$g_multiplayer_number_of_respawn_count"),
         (try_begin),
           (eq, reg0, 0),
           (str_store_string, s1, "str_unlimited"),
         (else_try),
           (str_store_string, s1, "str_reg0"),
         (try_end),
         (str_store_string, s0, "str_defender_spawn_count_limit_is_s1"),
         (get_max_players, ":num_players"),
         (try_for_range, ":cur_player", 1, ":num_players"),
           (player_is_active, ":cur_player"),
           (multiplayer_send_int_to_player, ":cur_player", multiplayer_event_return_respawn_count, ":val1"),
         (try_end),                  
       (else_try),
         (str_store_string, s0, "str_input_is_not_correct_for_the_command_type_help_for_more_information"),
       (try_end),
     (else_try),
       (eq, ":input", 43),
       (try_begin),
         (eq, "$g_multiplayer_disallow_ranged_weapons", 1),
         (str_store_string, s0, "str_ranged_weapons_are_disallowed"),
       (else_try),
         (str_store_string, s0, "str_ranged_weapons_are_allowed"),
       (try_end),
     (else_try),
       (eq, ":input", 44),
       (try_begin),
         (is_between, ":val1", 0, 2),
         (assign, "$g_multiplayer_disallow_ranged_weapons", ":val1"),
         (try_begin),
           (eq, ":val1", 1),
           (str_store_string, s0, "str_ranged_weapons_are_disallowed"),
         (else_try),
           (str_store_string, s0, "str_ranged_weapons_are_allowed"),
         (try_end),
       (else_try),
         (str_store_string, s0, "str_input_is_not_correct_for_the_command_type_help_for_more_information"),
       (try_end),
     (else_try),
       (str_store_string, s0, "@{!}DEBUG : SYSTEM ERROR!"),
     (try_end),
  ]),
  

  # 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),

#NPC companion changes begin
       (call_script, "script_party_count_fit_regulars", "p_main_party"),
       (assign, "$playerparty_prebattle_regulars", reg0),

#        (try_begin),
#            (assign, "$player_party__regulars", 0),
#            (call_script, "script_party_count_fit_regulars", "p_main_party"),
#            (gt, reg0, 0),
#            (assign, "$player_party_contains_regulars", 1),
#        (try_end),
#NPC companion changes 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),
       (try_begin),
         (neg|is_between, "$g_encountered_party", centers_begin, centers_end),
         (rest_for_hours, 0), #stop waiting
         (assign, "$g_infinite_camping", 0),
       (try_end),
#       (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),
           (party_slot_eq, "$g_encountered_party", slot_party_type, spt_cattle_herd),
           (jump_to_menu, "mnu_cattle_herd"),
         (else_try),
           (is_between, "$g_encountered_party", training_grounds_begin, training_grounds_end),
           (jump_to_menu, "mnu_training_ground"),
		 (else_try),  
		   (party_get_template_id, ":template", "$g_encountered_party"),
		   (ge, ":template", "pt_steppe_bandit_lair"),
		   (lt, ":template", "pt_bandit_lair_templates_end"),
		   (assign, "$loot_screen_shown", 0),
#		   (call_script, "script_encounter_init_variables"),
		   (jump_to_menu, "mnu_bandit_lair"),
         (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_battlefields"),
           (jump_to_menu, "mnu_battlefields"),
         (else_try),
           (eq, "$g_encountered_party", "p_training_ground"),
           (jump_to_menu, "mnu_tutorial"),
         (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"),

      (assign, "$marshall_defeated_in_battle", -1),

      (store_current_hours, ":hours"),
      
      (try_for_parties, ":party"),
        (party_get_battle_opponent, ":opponent", ":party"),
        (gt, ":opponent", 0),
        (party_set_slot, ":party", slot_party_last_in_combat, ":hours"),
      (try_end),

      (assign, ":trigger_result", 1),
      (try_begin),
        (ge, ":root_defender_party", 0),
        (ge, ":root_attacker_party", 0),
        (party_is_active, ":root_defender_party"),
        (party_is_active, ":root_attacker_party"),
        (store_faction_of_party, ":defender_faction", ":root_defender_party"),
        (store_faction_of_party, ":attacker_faction", ":root_attacker_party"),
        (neq, ":defender_faction", "fac_player_faction"),
        (neq, ":attacker_faction", "fac_player_faction"),
        (store_relation, ":reln", ":defender_faction", ":attacker_faction"),
		# NE assassin
		 # Josef v586 - mercenary attacks on player's enemies
         # this sets the relation with the target lord to a minus number, so that the mercs 
		 # can close with the lord without being attacked. At that point we want to
		 # set the mercs to head for the nearest town, so they are removed from map
		 # if they survive. Say 2 days later
		 (try_begin), 
		   (eq, ":defender_faction", "fac_robber_knights"),
		   (assign, ":reln", -1),
		   (assign, "$merc_retreat", 1), 
		   (else_try),
		   (eq, ":attacker_faction", "fac_robber_knights"),
		   (assign, ":reln", -1),
		   (assign, "$merc_retreat", 1), 
           (try_end), 		 
		 # end Josef 586
		 # NE end assassin
        #(ge, ":reln", 0),
        #(set_trigger_result, 1),
        #(else_try),
        (lt, ":reln", 0),
        (assign, ":trigger_result", 0),


        (try_begin),
          (this_or_next|eq, "$g_battle_simulation_cancel_for_party", ":root_defender_party"),
          (eq, "$g_battle_simulation_cancel_for_party", ":root_attacker_party"),
          (assign, "$g_battle_simulation_cancel_for_party", -1),
          (assign, "$auto_enter_town", "$g_battle_simulation_auto_enter_town_after_battle"),
          (assign, ":trigger_result", 1),
        (else_try),
          (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),
            (assign, ":trigger_result", 1), #End battle!
          (try_end),
          (party_set_slot, ":root_attacker_party", slot_party_retreat_flag, 0),

          #(assign, ":cancel_attack", 0),

          (party_collect_attachments_to_party, ":root_defender_party", "p_collective_ally"),
          (party_collect_attachments_to_party, ":root_attacker_party", "p_collective_enemy"),
		 # NE kt0
		 # only want kt0's script to trigger when the DKs are involved
         (try_begin),            
 
         (this_or_next|eq, ":defender_faction", "fac_dark_knights"),
           (eq, ":attacker_faction", "fac_dark_knights"),
            ### start kt0
           (assign, ":is_siege", 0),
           (try_begin),             
             (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),
             (assign, ":is_siege", 1),
           (try_end),
           
           (call_script, "script_kt_party_calculate_strength", "p_collective_ally", 0, ":is_siege"),
           (assign, ":defender_strength", reg0),
           (assign, ":defender_defense", reg1),
           (call_script, "script_kt_party_calculate_strength", "p_collective_enemy", 0, ":is_siege"),
           (assign, ":attacker_strength", reg0),
           (assign, ":attacker_defense", reg1),
                                 
           ## For sieges increase attacker casualties and reduce defender casualties.
           (try_begin),             
             (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", 3),
             (val_div, ":defender_strength", 2),
             (val_div, ":attacker_strength", 2),
           (try_end),
                     
          # calculate damage values given average defense
           (store_mul, ":defender_adjusted_damage", ":attacker_defense", ":defender_strength"),
           (store_mul, ":attacker_adjusted_damage", ":defender_defense", ":attacker_strength"),
           (val_div, ":defender_adjusted_damage", 100),
           (val_div, ":attacker_adjusted_damage", 100),
           
           ## normalize values to make battles go more slowly
           ## a normal party with ~100 guys typically generates an attack
           ## value around 5000.  this should be twice what Native was
           ## with the added bonus that we don't cap the upper bound.
		   # battle speed - this was 50
           (val_div, ":attacker_adjusted_damage", 200),
           (val_div, ":defender_adjusted_damage", 200),
           (val_max, ":attacker_adjusted_damage", 1),
           (val_max, ":defender_adjusted_damage", 1),
           
           (try_begin),
             (inflict_casualties_to_party_group, ":root_attacker_party", ":defender_adjusted_damage", "p_temp_casualties"),
             (party_collect_attachments_to_party, ":root_attacker_party", "p_collective_enemy"),
           (try_end),
           (call_script, "script_party_count_fit_for_battle", "p_collective_enemy", 0),
           (assign, ":new_attacker_strength", reg0),

           (try_begin),
             (gt, ":new_attacker_strength", 0),
             (inflict_casualties_to_party_group, ":root_defender_party", ":attacker_adjusted_damage", "p_temp_casualties"),
             (party_collect_attachments_to_party, ":root_defender_party", "p_collective_ally"),
           (try_end),
           (call_script, "script_party_count_fit_for_battle", "p_collective_ally", 0),
           (assign, ":new_defender_strength", reg0),

           ### end kt0
           (else_try), #we want the normal autoresolve function for all other battles - eg Lord Vs Lord, all Player battles
           # reason for this is that the player could steamroll the AI by autoresolving all the time 
		   # NE End kt0
          #(call_script, "script_party_count_fit_for_battle", "p_collective_ally"),
          (call_script, "script_party_calculate_strength", "p_collective_ally", 0),
          (assign, ":defender_strength", reg0),
          #(call_script, "script_party_count_fit_for_battle", "p_collective_enemy"),
          (call_script, "script_party_calculate_strength", "p_collective_enemy", 0),
          (assign, ":attacker_strength", reg0),

          (store_div, ":defender_strength", ":defender_strength", 20),
          (val_min, ":defender_strength", 50),
          (val_max, ":defender_strength", 1),
          (store_div, ":attacker_strength", ":attacker_strength", 20),
          (val_min, ":attacker_strength", 50),
          (val_add, ":attacker_strength", 1),
          (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", 123), #it was 1.5 in old version, now it is only 1.23
            (val_div, ":defender_strength", 100),
      
            (val_mul, ":attacker_strength", 100), #it was 0.5 in old version, now it is only 1 / 1.23
            (val_div, ":attacker_strength", 123),
          (try_end),

          (call_script, "script_party_count_fit_for_battle", "p_collective_ally", 0),
          (assign, ":old_defender_strength", reg0),

          (try_begin),
            #(neg|is_currently_night), #Don't fight at night - Why not? - Jinnai
            (inflict_casualties_to_party_group, ":root_attacker_party", ":defender_strength", "p_temp_casualties"),
            (party_collect_attachments_to_party, ":root_attacker_party", "p_collective_enemy"),
          (try_end),
          (call_script, "script_party_count_fit_for_battle", "p_collective_enemy", 0),
          (assign, ":new_attacker_strength", reg0),

          (try_begin),
            (gt, ":new_attacker_strength", 0),
            #(neg|is_currently_night), #Don't fight at night
            (inflict_casualties_to_party_group, ":root_defender_party", ":attacker_strength", "p_temp_casualties"),
            (party_collect_attachments_to_party, ":root_defender_party", "p_collective_ally"),
          (try_end),
          (call_script, "script_party_count_fit_for_battle", "p_collective_ally", 0),
          (assign, ":new_defender_strength", reg0),
		  
		  # NE kt0
		  (try_end), # end of DK specific code
		  # NE END kt0
		  

          (try_begin),
            (this_or_next|eq, ":new_attacker_strength", 0),
            (eq, ":new_defender_strength", 0),
            # Battle concluded! determine winner
            
            (assign, ":do_not_end_battle", 0),
            (try_begin),
              (neg|troop_is_wounded, "trp_player"),
              (eq, ":new_defender_strength", 0),              
              (eq, "$auto_enter_town", "$g_encountered_party"),
              (eq, ":old_defender_strength", ":new_defender_strength"),
              (assign, ":do_not_end_battle", 1),
            (try_end),            
            (eq, ":do_not_end_battle", 0),

            (try_begin),
              (eq, ":new_attacker_strength", 0),
              (eq, ":new_defender_strength", 0),
              (assign, ":root_winner_party", -1),
              (assign, ":root_defeated_party", -1),
              (assign, ":collective_casualties", -1),
            (else_try),
              (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),

            (try_begin),
              (ge, ":root_winner_party", 0),
              (call_script, "script_get_nonempty_party_in_group", ":root_winner_party"),
              (assign, ":nonempty_winner_party", reg0),
              (store_faction_of_party, ":faction_receiving_prisoners", ":nonempty_winner_party"),
              (store_faction_of_party, ":defeated_faction", ":root_defeated_party"),
            (else_try),
              (assign, ":nonempty_winner_party", -1),
            (try_end),

            (try_begin),
              (ge, ":collective_casualties", 0),
              (party_get_num_companion_stacks, ":num_stacks", ":collective_casualties"),
            (else_try),
              (assign, ":num_stacks", 0),
            (try_end),
                                                                         
            (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"),
              
              (try_begin),
                #abort quest if troop loses a battle during rest time
                (check_quest_active, "qst_lend_surgeon"),
                (quest_slot_eq, "qst_lend_surgeon", slot_quest_giver_troop, ":cur_troop_id"),
                (call_script, "script_abort_quest", "qst_lend_surgeon", 0),
              (try_end),
              
              (call_script, "script_remove_troop_from_prison", ":cur_troop_id"),
                              
              (troop_set_slot, ":cur_troop_id", slot_troop_leaded_party, -1),
               
              (store_random_in_range, ":rand", 0, 100),
              (str_store_troop_name_link, s1, ":cur_troop_id"),
              (str_store_faction_name_link, s2, ":faction_receiving_prisoners"),
              (store_troop_faction, ":defeated_troop_faction", ":cur_troop_id"),
              (str_store_faction_name_link, s3, ":defeated_troop_faction"),
              (try_begin),
                (ge, ":rand", hero_escape_after_defeat_chance),
                (party_stack_get_troop_id, ":leader_troop_id", ":nonempty_winner_party", 0),
                (is_between, ":leader_troop_id", active_npcs_begin, active_npcs_end), #disable non-kingdom parties capturing enemy lords
                (party_add_prisoners, ":nonempty_winner_party", ":cur_troop_id", 1),
                (gt, reg0, 0),
                #(troop_set_slot, ":cur_troop_id", slot_troop_is_prisoner, 1),
                (troop_set_slot, ":cur_troop_id", slot_troop_prisoner_of_party, ":nonempty_winner_party"),
				# NE prisoner
				(troop_set_slot, ":cur_troop_id", slot_troop_requested_duel, 0), # Allow the captured lord to request a duel - Jinnai
				# NE prisoner end			 
                (display_log_message, "str_hero_taken_prisoner"),
				 
                (try_begin),
                  (call_script, "script_cf_prisoner_offered_parole", ":cur_troop_id"),

                  (try_begin),
                    (eq, "$cheat_mode", 1),
                    (display_message, "@{!}DEBUG : Prisoner granted parole"),
                  (try_end),

                  (call_script, "script_troop_change_relation_with_troop", ":leader_troop_id", ":cur_troop_id", 3),
				  (val_add, "$total_battle_enemy_changes", 3),
                (else_try),			 
                  (try_begin),
                    (eq, "$cheat_mode", 1),
                    (display_message, "@{!}DEBUG : Prisoner not offered parole"),
		          (try_end),

		          (call_script, "script_troop_change_relation_with_troop", ":leader_troop_id", ":cur_troop_id", -5),
				  (val_add, "$total_battle_enemy_changes", -5),
		        (try_end),
				 				 				 				 			
				(store_faction_of_party, ":capturer_faction", ":nonempty_winner_party"),
                (call_script, "script_update_troop_location_notes_prisoned", ":cur_troop_id", ":capturer_faction"),
              (else_try),
                (display_message,"@{s1} of {s3} was defeated in battle but managed to escape."),
              (try_end),
              
              (try_begin),
                (store_troop_faction, ":cur_troop_faction", ":cur_troop_id"),
                (is_between, ":cur_troop_faction", kingdoms_begin, kingdoms_end),
                (faction_slot_eq, ":cur_troop_faction", slot_faction_marshall, ":cur_troop_id"),
                (is_between, ":cur_troop_faction", kingdoms_begin, kingdoms_end),
                (assign, "$marshall_defeated_in_battle", ":cur_troop_id"),
                #Marshall is defeated, refresh ai.
                (assign, "$g_recalculate_ais", 1),
              (try_end),
            (try_end),
			 
             (try_begin),
               (ge, ":collective_casualties", 0),
               (party_get_num_prisoner_stacks, ":num_stacks", ":collective_casualties"),
             (else_try),
               (assign, ":num_stacks", 0),
             (try_end),
             (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"),
               (call_script, "script_remove_troop_from_prison", ":cur_troop_id"),
               (store_troop_faction, ":cur_troop_faction", ":cur_troop_id"),
               (str_store_troop_name_link, s1, ":cur_troop_id"),
               (str_store_faction_name_link, s2, ":faction_receiving_prisoners"),
               (str_store_faction_name_link, s3, ":cur_troop_faction"),
               (display_log_message,"str_hero_freed"),
             (try_end),

             (try_begin),
               (ge, ":collective_casualties", 0),
               (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_battle_political_consequences", ":root_defeated_party", ":root_winner_party"),
			
               (call_script, "script_clear_party_group", ":root_defeated_party"),
             (try_end),
             (assign, ":trigger_result", 1), #End battle!

             #Center captured
             (try_begin),
               (ge, ":collective_casualties", 0),
               (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),

               (assign, "$g_recalculate_ais", 1),

               (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"),
			
			   (store_current_hours, ":hours"),
			   (faction_set_slot, ":winner_faction", slot_faction_ai_last_decisive_event, ":hours"),
			
               (try_begin),
                 (eq, "$g_encountered_party", ":root_defeated_party"),
                 (call_script, "script_add_log_entry", logent_player_participated_in_siege, "trp_player",  "$g_encountered_party", 0, "$g_encountered_party_faction"),
               (try_end),

               (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", active_npcs_begin, active_npcs_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_lift_siege", ":root_defeated_party", 0),
			   (store_faction_of_party, ":fortress_faction", ":root_defeated_party"),			   
			   (try_begin),
			     (is_between, ":root_defeated_party", towns_begin, towns_end),
			     (assign, ":damage", 40),
			   (else_try),
			     (assign, ":damage", 20),
			   (try_end),
			   (call_script, "script_faction_inflict_war_damage_on_faction", ":winner_faction", ":fortress_faction", ":damage"),
			   
               (call_script, "script_give_center_to_faction", ":root_defeated_party", ":winner_faction"),
               (try_begin),
                 (eq, ":defeated_faction", "fac_player_supporters_faction"),
                 (call_script, "script_add_notification_menu", "mnu_notification_center_lost", ":root_defeated_party", ":winner_faction"),
               (try_end),
               
               (party_get_num_attached_parties, ":num_attached_parties",  ":root_attacker_party"),
                 (try_for_range, ":attached_party_rank", 0, ":num_attached_parties"),
                 (party_get_attached_party_with_rank, ":attached_party", ":root_attacker_party", ":attached_party_rank"),
                                                                                                       
                 (party_get_num_companion_stacks, ":num_stacks", ":attached_party"),                 
                 (assign, ":total_size", 0),
                 (try_for_range, ":i_stack", 0, ":num_stacks"),
                   (party_stack_get_size, ":stack_size", ":attached_party", ":i_stack"),
                   (val_add, ":total_size", ":stack_size"),
                 (try_end),  
                 
                 (try_begin),
                   (ge, ":total_size", 10),
                   
                   (assign, ":stacks_added", 0),
                   (assign, ":last_random_stack", -1),
                   
                   (assign, ":end_condition", 10),
                   (try_for_range, ":unused", 0, ":end_condition"),
                     (store_random_in_range, ":random_stack", 1, ":num_stacks"),
                     (party_stack_get_troop_id, ":random_stack_troop", ":attached_party", ":random_stack"),
                     (party_stack_get_size, ":stack_size", ":attached_party", ":random_stack"),
                     (ge, ":stack_size", 4),
                     (neq, ":random_stack", ":last_random_stack"),
                   
                     (store_mul, ":total_size_mul_2", ":total_size", 2),
                     (assign, ":percentage", ":total_size_mul_2"),
                     (val_min, ":percentage", 100),                   
                   
                     (val_mul, ":stack_size", ":percentage"),
                     (val_div, ":stack_size", 100),
                   
                     (party_stack_get_troop_id, ":party_leader", ":attached_party", 0),

                     (try_begin),
                       (this_or_next|troop_slot_eq, ":party_leader", slot_lord_reputation_type, lrep_goodnatured),
                       (this_or_next|troop_slot_eq, ":party_leader", slot_lord_reputation_type, lrep_upstanding),
                       (troop_slot_eq, ":party_leader", slot_lord_reputation_type, lrep_martial),
                       (assign, reg2, 0),
                       (store_random_in_range, ":random_percentage", 40, 50), #average 45%
                     (else_try),  
                       (this_or_next|troop_slot_eq, ":party_leader", slot_lord_reputation_type, lrep_quarrelsome),
                       (troop_slot_eq, ":party_leader", slot_lord_reputation_type, lrep_cunning),
                       (assign, reg2, 1),
                       (store_random_in_range, ":random_percentage", 30, 40), #average 35%
                     (else_try),  
                       (this_or_next|troop_slot_eq, ":party_leader", slot_lord_reputation_type, lrep_selfrighteous),
                       (this_or_next|troop_slot_eq, ":party_leader", slot_lord_reputation_type, lrep_roguish),
                       (troop_slot_eq, ":party_leader", slot_lord_reputation_type, lrep_debauched),
                       (assign, reg2, 2),
                       (store_random_in_range, ":random_percentage", 20, 30), #average 25%
                     (else_try),  
                       (this_or_next|troop_slot_eq, ":party_leader", slot_lord_reputation_type, lrep_benefactor),
                       (troop_slot_eq, ":party_leader", slot_lord_reputation_type, lrep_custodian),
                       (assign, reg2, 3),
                       (store_random_in_range, ":random_percentage", 50, 60), #average 55%
                     (try_end),                   
                   
                     (val_min, ":random_percentage", 100),                   
                     (val_mul, ":stack_size", ":random_percentage"),
                     (val_div, ":stack_size", 100),
                                                    
                     (party_add_members, ":root_defender_party", ":random_stack_troop", ":stack_size"),
                     (party_remove_members, ":attached_party", ":random_stack_troop", ":stack_size"),
                     
                     (val_add, ":stacks_added", 1),
                     (assign, ":last_random_stack", ":random_stack"),
                     
                     (try_begin),
                       #if troops from three different stack is already added then break
                       (eq, ":stacks_added", 3),
                       (assign, ":end_condition", 0),
                     (try_end),
                   (try_end),  
                 (try_end),  
               (try_end),
               
               #Reduce prosperity of the center by 5
			   (try_begin),
			     (neg|is_between, ":root_defeated_party", castles_begin, castles_end),
			     (call_script, "script_change_center_prosperity", ":root_defeated_party", -5),
			     (val_add, "$newglob_total_prosperity_from_townloot", -5),
			   (try_end),
               (call_script, "script_order_best_besieger_party_to_guard_center", ":root_defeated_party", ":winner_faction"),
               (call_script, "script_cf_reinforce_party", ":root_defeated_party"),
               (call_script, "script_cf_reinforce_party", ":root_defeated_party"),			   
             (try_end),
           (try_end),

           #ADD XP
           (try_begin),
             (party_slot_eq, ":root_attacker_party", slot_party_type, spt_kingdom_hero_party),
                          
             (assign, ":xp_gained_attacker", 200),
             (game_get_reduce_campaign_ai, ":reduce_campaign_ai"),
             (store_faction_of_party, ":root_attacker_party_faction", ":root_attacker_party"),
             (try_begin),
               (this_or_next|eq, ":root_attacker_party", "p_main_party"),
               (this_or_next|eq, ":root_attacker_party_faction", "fac_player_supporters_faction"),
               (eq, ":root_attacker_party_faction", "$players_kingdom"),               
               #same
             (else_try),
               (eq, ":reduce_campaign_ai", 0), #hard (1.5x)
               (val_mul, ":xp_gained_attacker", 3),
               (val_div, ":xp_gained_attacker", 2),
             (else_try),
               (eq, ":reduce_campaign_ai", 1), #moderate (1.0x)
               #same
             (else_try),                        
               (eq, ":reduce_campaign_ai", 2), #easy (0.5x)
               (val_div, ":xp_gained_attacker", 2),
             (try_end),           
             
             (gt, ":new_attacker_strength", 0),             
             (call_script, "script_upgrade_hero_party", ":root_attacker_party", ":xp_gained_attacker"),
           (try_end),
           (try_begin),
             (party_slot_eq, ":root_defender_party", slot_party_type, spt_kingdom_hero_party),
                          
             (assign, ":xp_gained_defender", 200),
             (store_faction_of_party, ":root_defender_party_faction", ":root_defender_party"),             
             (game_get_reduce_campaign_ai, ":reduce_campaign_ai"),
             (try_begin),
               (this_or_next|eq, ":root_defender_party", "p_main_party"),
               (this_or_next|eq, ":root_defender_party_faction", "fac_player_supporters_faction"),
               (eq, ":root_defender_party_faction", "$players_kingdom"),               
               #same
             (else_try),
               (eq, ":reduce_campaign_ai", 0), #hard (1.5x)
               (val_mul, ":xp_gained_defender", 3),
               (val_div, ":xp_gained_defender", 2),
             (else_try),
               (eq, ":reduce_campaign_ai", 1), #moderate (1.0x)
               #same
             (else_try),         
               (eq, ":reduce_campaign_ai", 2), #easy (0.5x)
               (val_div, ":xp_gained_defender", 2),
             (try_end),           

             (gt, ":new_defender_strength", 0),
             (call_script, "script_upgrade_hero_party", ":root_defender_party", ":xp_gained_defender"),
           (try_end),

           (try_begin),         
             #ozan - do not randomly end battles aganist towns or castles.
             (neg|party_slot_eq, ":root_defender_party", slot_party_type, spt_castle), #added by ozan
             (neg|party_slot_eq, ":root_defender_party", slot_party_type, spt_town),   #added by ozan        
             #end ozan
                          
             (party_get_slot, ":attacker_root_strength", ":root_attacker_party", slot_party_cached_strength),
             (party_get_slot, ":attacker_nearby_friend_strength", ":root_attacker_party", slot_party_nearby_friend_strength),
             (party_get_slot, ":strength_of_attacker_followers", ":root_attacker_party", slot_party_follower_strength),
             (store_add, ":total_attacker_strength", ":attacker_root_strength", ":attacker_nearby_friend_strength"),
             (val_add, ":total_attacker_strength", ":strength_of_attacker_followers"),

             (party_get_slot, ":defender_root_strength", ":root_defender_party", slot_party_cached_strength),
             (party_get_slot, ":defender_nearby_friend_strength", ":root_defender_party", slot_party_nearby_friend_strength),
             (party_get_slot, ":strength_of_defender_followers", ":root_defender_party", slot_party_follower_strength),
             (store_add, ":total_defender_strength", ":defender_root_strength", ":defender_nearby_friend_strength"),
             (val_add, ":total_attacker_strength", ":strength_of_defender_followers"),

             #Players can make save loads and change history because these random values are not determined from random_slots of troops
             (store_random_in_range, ":random_num", 0, 100),
                          
             (try_begin),
               (lt, ":random_num", 10),
               (assign, ":trigger_result", 1), #End battle!
             (try_end),
           (else_try),
             (party_get_slot, ":attacker_root_strength", ":root_attacker_party", slot_party_cached_strength),
             (party_get_slot, ":attacker_nearby_friend_strength", ":root_attacker_party", slot_party_nearby_friend_strength),
             (party_get_slot, ":strength_of_followers", ":root_attacker_party", slot_party_follower_strength),
             (store_add, ":total_attacker_strength", ":attacker_root_strength", ":attacker_nearby_friend_strength"),
             (val_add, ":total_attacker_strength", ":strength_of_followers"),

             (party_get_slot, ":defender_root_strength", ":root_defender_party", slot_party_cached_strength),
             (party_get_slot, ":defender_nearby_friend_strength", ":root_defender_party", slot_party_nearby_friend_strength),
             (store_add, ":total_defender_strength", ":defender_root_strength", ":defender_nearby_friend_strength"),

             (val_mul, ":total_defender_strength", 13), #multiply defender strength with 1.3
             (val_div, ":total_defender_strength", 10),

             (gt, ":total_defender_strength", ":total_attacker_strength"),
             (gt, ":total_defender_strength", 3),

             #Players can make save loads and change history because these random values are not determined from random_slots of troops
             (store_random_in_range, ":random_num", 0, 100),

             (try_begin),
               (lt, ":random_num", 15), #15% is a bit higher than 10% (which is open area escape probability)
               (assign, ":trigger_result", 1), #End battle!
                                             
               (assign, "$g_recalculate_ais", 1), #added new
                              
               (try_begin),
                 (eq, "$cheat_mode", 1),
                 (display_message, "@{!}DEBUG : Siege attackers are running away"),
               (try_end),
             (try_end),      
           (try_end),
         (try_end),  
       (try_end),
       (set_trigger_result, ":trigger_result"),
  ]),

  #script_game_event_battle_end:
  # This script is called whenever the game ends the battle between two parties on the map.
  # INPUT:
  # param1: Defender Party
  # param2: Attacker Party
  ("game_event_battle_end",
    [
##       (store_script_param_1, ":root_defender_party"),
##       (store_script_param_2, ":root_attacker_party"),
        
      #Fixing deleted heroes
      (try_for_range, ":cur_troop", active_npcs_begin, active_npcs_end),
		(troop_slot_eq, ":cur_troop", slot_troop_occupation, slto_kingdom_hero),
        (troop_get_slot, ":cur_party", ":cur_troop", slot_troop_leaded_party),
        (troop_get_slot, ":cur_prisoner_of_party", ":cur_troop", slot_troop_prisoner_of_party),
        (try_begin),
          (ge, ":cur_party", 0),
          (assign, ":continue", 0),
          (try_begin),
            (neg|party_is_active, ":cur_party"),
            (assign, ":continue", 1),
          (else_try),
            (party_count_companions_of_type, ":amount", ":cur_party", ":cur_troop"),
            (le, ":amount", 0),
            (assign, ":continue", 1),
          (try_end),
          (eq, ":continue", 1),
          (try_begin),
            (eq, "$cheat_mode", 1),
            (str_store_troop_name, s1, ":cur_troop"),
            (display_message, "@{!}DEBUG: {s1} no longer leads a party."),
          (try_end),
         
          (troop_set_slot, ":cur_troop", slot_troop_leaded_party, -1),
          #(str_store_troop_name, s5, ":cur_troop"),
          #(display_message, "@{!}DEBUG : {s5}'s troop_leaded_party set to -1"),
        (try_end),
        (try_begin),
          (ge, ":cur_prisoner_of_party", 0),
          (assign, ":continue", 0),
          (try_begin),
            (neg|party_is_active, ":cur_prisoner_of_party"),
            (assign, ":continue", 1),
          (else_try),
            (party_count_prisoners_of_type, ":amount", ":cur_prisoner_of_party", ":cur_troop"),
            (le, ":amount", 0),
            (assign, ":continue", 1),
          (try_end),
          (eq, ":continue", 1),
          (try_begin),
            (eq, "$cheat_mode", 1),
            (str_store_troop_name, s1, ":cur_troop"),
            (display_message, "@{!}DEBUG: {s1} is no longer a prisoner."),
          (try_end),
          (call_script, "script_remove_troop_from_prison", ":cur_troop"),
          #searching player
          (try_begin),
            (party_count_prisoners_of_type, ":amount", "p_main_party", ":cur_troop"),
            (gt, ":amount", 0),
            (troop_set_slot, ":cur_troop", slot_troop_prisoner_of_party, "p_main_party"),
            (assign, ":continue", 0),
            (try_begin),
              (eq, "$cheat_mode", 1),
              (str_store_troop_name, s1, ":cur_troop"),
              (display_message, "@{!}DEBUG: {s1} is now a prisoner of player."),                         
            (try_end),
          (try_end),
          (eq, ":continue", 1),
          #searching kingdom heroes
          (try_for_range, ":cur_troop_2", active_npcs_begin, active_npcs_end),
			(troop_slot_eq, ":cur_troop_2", slot_troop_occupation, slto_kingdom_hero),
			(eq, ":continue", 1),
            (troop_get_slot, ":cur_prisoner_of_party_2", ":cur_troop_2", slot_troop_leaded_party),
            (party_is_active, ":cur_prisoner_of_party_2"),
            (party_count_prisoners_of_type, ":amount", ":cur_prisoner_of_party_2", ":cur_troop"),
            (gt, ":amount", 0),
            (troop_set_slot, ":cur_troop", slot_troop_prisoner_of_party, ":cur_prisoner_of_party_2"),
            (assign, ":continue", 0),
            (try_begin),
              (eq, "$cheat_mode", 1),
              (str_store_troop_name, s1, ":cur_troop"),
              (str_store_party_name, s2, ":cur_prisoner_of_party_2"),
              (display_message, "@{!}DEBUG: {s1} is now a prisoner of {s2}."),
            (try_end),
          (try_end),
          #searching walled centers
          (try_for_range, ":cur_prisoner_of_party_2", walled_centers_begin, walled_centers_end),
            (eq, ":continue", 1),
            (party_count_prisoners_of_type, ":amount", ":cur_prisoner_of_party_2", ":cur_troop"),
            (gt, ":amount", 0),
            (troop_set_slot, ":cur_troop", slot_troop_prisoner_of_party, ":cur_prisoner_of_party_2"),
            (assign, ":continue", 0),
            (try_begin),
              (eq, "$cheat_mode", 1),
              (str_store_troop_name, s1, ":cur_troop"),
              (str_store_party_name, s2, ":cur_prisoner_of_party_2"),
              (display_message, "@{!}DEBUG: {s1} is now a prisoner of {s2}."),
            (try_end),
          (try_end),
        (try_end),
      (try_end),
  ]),   
  
  #script_order_best_besieger_party_to_guard_center:
  # INPUT:
  # param1: defeated_center, param2: winner_faction
  # OUTPUT:
  # none
  ("order_best_besieger_party_to_guard_center",
    [
      (store_script_param, ":defeated_center", 1),
      (store_script_param, ":winner_faction", 2),
      (assign, ":best_party", -1),
      (assign, ":best_party_strength", 0),
      (try_for_range, ":kingdom_hero", active_npcs_begin, active_npcs_end),
        (troop_get_slot, ":kingdom_hero_party", ":kingdom_hero", slot_troop_leaded_party),
        (gt, ":kingdom_hero_party", 0),
        (party_is_active, ":kingdom_hero_party"),
        (store_faction_of_party, ":kingdom_hero_party_faction", ":kingdom_hero_party"),
        (eq, ":winner_faction", ":kingdom_hero_party_faction"),
        (store_distance_to_party_from_party, ":dist", ":kingdom_hero_party", ":defeated_center"),
        (lt, ":dist", 5),
        #If marshall has captured the castle, then do not leave him behind.
        (neg|faction_slot_eq, ":winner_faction", slot_faction_marshall, ":kingdom_hero"),
        (assign, ":has_besiege_ai", 0),
        (try_begin),
          (party_slot_eq, ":kingdom_hero_party", slot_party_ai_state, spai_besieging_center),
          (party_slot_eq, ":kingdom_hero_party", slot_party_ai_object, ":defeated_center"),
          (assign, ":has_besiege_ai", 1),
        (else_try),
          (party_slot_eq, ":kingdom_hero_party", slot_party_ai_state, spai_accompanying_army),
          (party_get_slot, ":kingdom_hero_party_commander_party", ":kingdom_hero_party", slot_party_ai_object),
          (party_slot_eq, ":kingdom_hero_party_commander_party", slot_party_ai_state, spai_besieging_center),
          (party_slot_eq, ":kingdom_hero_party_commander_party", slot_party_ai_object, ":defeated_center"),
          (assign, ":has_besiege_ai", 1),
        (try_end),
        (eq, ":has_besiege_ai", 1),
        (party_get_slot, ":kingdom_hero_party_strength", ":kingdom_hero_party", slot_party_cached_strength),#recently calculated
        (gt, ":kingdom_hero_party_strength", ":best_party_strength"),
        (assign, ":best_party_strength", ":kingdom_hero_party_strength"),
        (assign, ":best_party", ":kingdom_hero_party"),
      (try_end),
      (try_begin),
        (gt, ":best_party", 0),
        (call_script, "script_party_set_ai_state", ":best_party", spai_holding_center, ":defeated_center"),
        #(party_set_slot, ":best_party", slot_party_commander_party, -1),
        (party_set_flags, ":best_party", pf_default_behavior, 1),
      (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, "$g_encountered_party", centers_begin, centers_end),
        (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"),
		
		(try_begin),
			(is_between, "$g_encountered_party", villages_begin, villages_end),
			(party_get_slot, ":market_town", "$g_encountered_party", slot_village_market_town),
			(party_get_slot, ":price_in_market_town", ":market_town", ":item_slot_no"),
			(val_max, ":price_factor", ":price_in_market_town"),
		(try_end),
		
		#For villages, the good will be sold no cheaper than in the market town
		#This represents the absence of a permanent market -- ie, the peasants retain goods to sell on their journeys to town, and are not about to do giveaway deals with passing adventurers
		
		
        (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, "$g_encountered_party", centers_begin, centers_end),
        (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 weapons, armor, and horses
        (val_mul, ":trade_penalty", 4),
      (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",15), #reduced slightly
        (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),

      (assign, ":penalty_multiplier", 1000),
##       # Apply penalty if player is hostile to merchants faction
##      (store_relation, ":merchants_reln", "fac_merchants", "fac_player_supporters_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, ":penalty_multiplier", ":merchants_relation_penalty"),
##      (try_end),

       # Apply penalty if player is on bad terms with the town
      (try_begin),
        (is_between, "$g_encountered_party", centers_begin, centers_end),
        (party_get_slot, ":center_relation", "$g_encountered_party", slot_center_player_relation),
        (store_mul, ":center_relation_penalty", ":center_relation", -3),
        (val_add, ":penalty_multiplier", ":center_relation_penalty"),
        (try_begin),
          (lt, ":center_relation", 0),
          (store_sub, ":center_penalty_multiplier", 100, ":center_relation"),
          (val_mul, ":penalty_multiplier", ":center_penalty_multiplier"),
          (val_div, ":penalty_multiplier", 100),
        (try_end),
      (try_end),

       # Apply penalty if player is on bad terms with the merchant (not currently used)
      (call_script, "script_troop_get_player_relation", "$g_talk_troop"),
      (assign, ":troop_reln", reg0),
      #(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, ":penalty_multiplier", ":troop_relation_penalty"),
      (try_end),
      
	  
	  (try_begin),
		(is_between, "$g_encountered_party", villages_begin, villages_end),
	    (val_mul, ":penalty", 2),
	  (try_end),
	  
	  (try_begin),
            (is_between, "$g_encountered_party", centers_begin, centers_end),
	    #Double trade penalty if no local production or consumption
	    (is_between, ":item_kind_id", trade_goods_begin, trade_goods_end),
	    (call_script, "script_center_get_production", "$g_encountered_party", ":item_kind_id"),
	    (eq, reg0, 0),
	    (call_script, "script_center_get_consumption", "$g_encountered_party", ":item_kind_id"),
	    (eq, reg0, 0),
	    (val_mul, ":penalty", 2),
	  (try_end),
	  
      (val_mul, ":penalty",  ":penalty_multiplier"),
      (val_div, ":penalty", 1000),
      (val_max, ":penalty", 1),
      (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_start_wedding_cutscene
  # INPUT: arg1 = groom_troop, arg2 = bride_troop
  # OUTPUT: none
  ("start_wedding_cutscene",
   [
     (store_script_param, "$g_wedding_groom_troop", 1),
     (store_script_param, "$g_wedding_bride_troop", 2),

     (assign, "$g_wedding_bishop_troop", "trp_temporary_minister"),
     (try_begin),
       (is_between, "$players_kingdom", kingdoms_begin, kingdoms_end),
       (neg|faction_slot_eq, "$players_kingdom", slot_faction_leader, "$g_wedding_groom_troop"),
       (neg|faction_slot_eq, "$players_kingdom", slot_faction_leader, "$g_wedding_bride_troop"),
       (faction_get_slot, ":players_king", "$players_kingdom", slot_faction_leader),
       (troop_get_type, ":troop_type", ":players_king"),
       (eq, ":troop_type", 0), #male
       (neq, ":players_king", "$g_wedding_groom_troop"),
       (assign, "$g_wedding_bishop_troop", ":players_king"),
     (else_try),
       (eq, "$players_kingdom", "fac_player_supporters_faction"),
       (faction_slot_eq, "$players_kingdom", slot_faction_leader, "trp_player"),
       (gt, "$g_player_minister", 0),
       (troop_get_type, ":troop_type", "$g_player_minister"),
       (eq, ":troop_type", 0), #male
       (neq, "$g_player_minister", "$g_wedding_groom_troop"),
       (assign, "$g_wedding_bishop_troop", "$g_player_minister"),
     (try_end),

     (assign, "$g_wedding_brides_dad_troop", "trp_temporary_minister"),
     (try_begin),
       (neq, "$g_wedding_bride_troop", "trp_player"),
       (try_begin),
         (troop_get_slot, ":father", "$g_wedding_bride_troop", slot_troop_father),
         (gt, ":father", 0),
         (troop_get_type, ":troop_type", ":father"), #just to make sure
         (eq, ":troop_type", 0), #male
         (neq, ":father", "$g_wedding_groom_troop"), #this might be 0 due to an error
         (neq, ":father", "$g_wedding_bishop_troop"),
         (assign, "$g_wedding_brides_dad_troop", ":father"),
       (else_try),
         (troop_get_slot, ":guardian", "$g_wedding_bride_troop", slot_troop_guardian),
         (gt, ":guardian", 0),
         (troop_get_type, ":troop_type", ":guardian"), #just to make sure
         (eq, ":troop_type", 0), #male
         (neq, ":guardian", "$g_wedding_groom_troop"), #this might be 0 due to an error
         (neq, ":guardian", "$g_wedding_bishop_troop"),
         (assign, "$g_wedding_brides_dad_troop", ":guardian"),
       (try_end),
     (else_try),
       (try_for_range, ":cur_companion", companions_begin, companions_end),
         (this_or_next|troop_slot_eq, ":cur_companion", slot_troop_occupation, slto_player_companion),
         (troop_slot_eq, ":cur_companion", slot_troop_occupation, slto_kingdom_hero),
         (troop_get_type, ":troop_type", ":cur_companion"), #just to make sure
         (eq, ":troop_type", 0), #male
         (neq, ":cur_companion", "$g_wedding_groom_troop"),
         (neq, ":cur_companion", "$g_wedding_bishop_troop"),
         (assign, "$g_wedding_brides_dad_troop", ":cur_companion"),
       (try_end),
     (try_end),

     (modify_visitors_at_site,"scn_wedding"),
     (reset_visitors,0),
     (set_visitor, 0, "$g_wedding_groom_troop"),
     (set_visitor, 1, "$g_wedding_bride_troop"),
     (set_visitor, 2, "$g_wedding_brides_dad_troop"),
     (set_visitor, 3, "$g_wedding_bishop_troop"),
     (assign, ":num_visitors", 4),
     (assign, ":num_male_visitors", 0),
     (try_for_range, ":cur_npc", active_npcs_begin, kingdom_ladies_end),
       (lt, ":num_visitors", 32),
       (neq, ":cur_npc", "$g_wedding_groom_troop"),
       (neq, ":cur_npc", "$g_wedding_bride_troop"),
       (neq, ":cur_npc", "$g_wedding_brides_dad_troop"),
       (neq, ":cur_npc", "$g_wedding_bishop_troop"),
       (store_troop_faction, ":npc_faction", ":cur_npc"),
       (is_between, ":npc_faction", kingdoms_begin, kingdoms_end),
       (eq, ":npc_faction", "$players_kingdom"),
       (this_or_next|troop_slot_eq, ":cur_npc", slot_troop_occupation, slto_player_companion),
       (this_or_next|troop_slot_eq, ":cur_npc", slot_troop_occupation, slto_kingdom_hero),
       (troop_slot_eq, ":cur_npc", slot_troop_occupation, slto_kingdom_lady),
       (troop_get_type, ":troop_type", ":cur_npc"),
       (assign, ":continue_adding", 1),
       (try_begin),
         (eq, ":troop_type", 0),
         (assign, ":continue_adding", 0),
         (lt, ":num_male_visitors", 16), #limit number of male visitors
         (assign, ":continue_adding", 1),
         (val_add, ":num_male_visitors", 1),
       (try_end),
       (eq, ":continue_adding", 1),
       (set_visitor, ":num_visitors", ":cur_npc"),
       (val_add, ":num_visitors", 1),
     (try_end),
     (set_jump_mission,"mt_wedding"),
     (jump_to_scene,"scn_wedding"),
     (change_screen_mission),
    ]),
	
  
  # 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),
        (this_or_next|eq, ":troop_id", "trp_player"),
        (eq, ":troop_id", "trp_kidnapped_girl"),
      (else_try),
        (is_between, ":troop_id", pretenders_begin, pretenders_end),
      (else_try),
        (store_character_level, ":troop_level", ":troop_id"),
        (assign, ":wage", ":troop_level"),
        (val_add, ":wage", 3),
        (val_mul, ":wage", ":wage"),
        (val_div, ":wage", 25),
      (try_end),

      # NE 600 Series - Cavalary costs 3x more than normal
      (try_begin), #mounted troops cost 65% more than the normal cost
        (neg|is_between, ":troop_id", companions_begin, companions_end),
        (troop_is_mounted, ":troop_id"),
        (val_mul, ":wage", 2),
      #  (val_div, ":wage", 3),
      (try_end),

      # NE 600 Series - Raising merc cost to 3x kingdom troop wage
      (try_begin), #mercenaries cost %50 more than the normal cost
        (is_between, ":troop_id", mercenary_troops_begin, mercenary_troops_end),
        (val_mul, ":wage", 3),
      #  (val_div, ":wage", 2),
      (try_end),

      # NE 600 Series - Companions cost 6x normal
      (try_begin),
        (is_between, ":troop_id", companions_begin, companions_end),
        (val_mul, ":wage", 6),
      (try_end),

      # NE 600 Series - Increase troop wage cost by 50% when in brutality mode
      (try_begin),
        (eq,"$setting_brutality_mode",1),
        (val_mul, ":wage", 3),
        (val_div, ":wage", 2),
      (try_end),
      
      (store_skill_level, ":leadership_level", "skl_leadership", "trp_player"),
      (store_mul, ":leadership_bonus", 5, ":leadership_level"),
      (store_sub, ":leadership_factor", 100, ":leadership_bonus"), 
      (val_mul, ":wage", ":leadership_factor"),  #wage = wage * (100 - 5*leadership)/100
      (val_div, ":wage", 100),

      (try_begin),
        (neq, ":troop_id", "trp_player"),
        (neq, ":troop_id", "trp_kidnapped_girl"),
		# NE quests 
				# v585 Josef kidnapped wife
		(neq, ":troop_id", "trp_kidnapped_wife"),
		# end v585 Josef
		# NE end quests 
        (neg|is_between, ":troop_id", pretenders_begin, pretenders_end),
        (val_max, ":wage", 1),
      (try_end),
       
      (assign, reg0, ":wage"),
      (set_trigger_result, reg0),
  ]),

  # script_game_get_total_wage
  # This script is called from the game engine for calculating total wage of the player party which is shown at the party window.
  # Input: none
  # Output: reg0: weekly wage
  
  ("game_get_total_wage",
    [
      (assign, ":total_wage", 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"),
        (party_stack_get_size, ":stack_size", "p_main_party", ":i_stack"),
        (call_script, "script_game_get_troop_wage", ":stack_troop", 0),
        (val_mul, reg0, ":stack_size"),
        (val_add, ":total_wage", reg0),
      (try_end),
      (assign, reg0, ":total_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),
        # NE 600 Series - mounted troops cost 3x more to recruit
        (try_begin), #mounted troops cost %100 more than the normal cost
          (troop_is_mounted, ":troop_id"),
          (val_mul, ":join_cost", 3),
        (try_end),
      (try_end),
      (assign, reg0, ":join_cost"),
      (set_trigger_result, reg0),
  ]),
  
  # script_game_get_upgrade_xp
  # This script is called from game engine for calculating needed troop upgrade exp
  # Input:
  # param1: troop_id,
  # Output: reg0 = needed exp for upgrade 
  ("game_get_upgrade_xp",
    [
      (store_script_param_1, ":troop_id"),
      
      (assign, ":needed_upgrade_xp", 0),
      #formula : int needed_upgrade_xp = 2 * (30 + 0.006f * level_boundaries[troops[troop_id].level + 3]);
      (store_character_level, ":troop_level", ":troop_id"),
      (store_add, ":needed_upgrade_xp", ":troop_level", 3),
      (get_level_boundary, reg0, ":needed_upgrade_xp"),        
      (val_mul, reg0, 6),
      (val_div, reg0, 1000),
      (val_add, reg0, 30),

      (try_begin),               
        (ge, ":troop_id", bandits_begin),
        (lt, ":troop_id", bandits_end),
        (val_mul, reg0, 2),
      (try_end),

      (set_trigger_result, reg0),
  ]),
  
  # script_game_get_upgrade_cost
  # This script is called from game engine for calculating needed troop upgrade exp
  # Input:
  # param1: troop_id,
  # Output: reg0 = needed cost for upgrade
  ("game_get_upgrade_cost",
    [
      (store_script_param_1, ":troop_id"),
      
      (store_character_level, ":troop_level", ":troop_id"),
      
      (try_begin),
        (is_between, ":troop_level", 0, 6),
        (assign, reg0, 10),
      (else_try),  
        (is_between, ":troop_level", 6, 11),
        (assign, reg0, 20),
      (else_try),  
        (is_between, ":troop_level", 11, 16),
        (assign, reg0, 40),
      (else_try),  
        (is_between, ":troop_level", 16, 21),
        (assign, reg0, 80),
      (else_try),  
        (is_between, ":troop_level", 21, 26),
        (assign, reg0, 120),
      (else_try),  
        (is_between, ":troop_level", 26, 31),
        (assign, reg0, 160),
      (else_try),  
        (assign, reg0, 200),
      (try_end),  
        
      (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"),
            
      (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),
      (else_try),  
        (assign, ":ransom_amount", 50),
      (try_end),
      
      (assign, reg0, ":ransom_amount"),
      
      (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= cannot 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_get_morale_of_troops_from_faction
  # This script is called from the game engine 
  # Input: 
  # param1: faction_no,
  # Output: reg0: extra morale x 100
  
  ("game_get_morale_of_troops_from_faction",
    [
      (store_script_param_1, ":troop_no"),            
      
      (store_troop_faction, ":faction_no", ":troop_no"),
      
      (try_begin),
        (ge, ":faction_no", npc_kingdoms_begin),
        (lt, ":faction_no", npc_kingdoms_end),
        
        (faction_get_slot, reg0, ":faction_no",  slot_faction_morale_of_player_troops),

        #(assign, reg1, ":faction_no"),
        #(assign, reg2, ":troop_no"),
        #(assign, reg3, reg0),
        #(display_message, "@extra morale for troop {reg2} of faction {reg1} is {reg3}"),
      (else_try),
        (assign, reg0, 0),
      (try_end),
            
      (val_div, reg0, 100),
      
      (party_get_morale, reg1, "p_main_party"),
      
      (val_add, reg0, reg1),
      
      (set_trigger_result, reg0),
  ]),
  
  #script_game_event_detect_party:
  # This script is called from the game engine when player party inspects another party.
  # INPUT:
  # param1: Party-id
  ("game_event_detect_party",
    [
        (store_script_param_1, ":party_id"),
        (try_begin),
          (party_slot_eq, ":party_id", slot_party_type, spt_kingdom_hero_party),
          (party_stack_get_troop_id, ":leader", ":party_id", 0),
          (is_between, ":leader", active_npcs_begin, active_npcs_end),
          (call_script, "script_update_troop_location_notes", ":leader", 0),
        (else_try),
          (is_between, ":party_id", walled_centers_begin, walled_centers_end),
          (party_get_num_attached_parties, ":num_attached_parties",  ":party_id"),
          (try_for_range, ":attached_party_rank", 0, ":num_attached_parties"),
            (party_get_attached_party_with_rank, ":attached_party", ":party_id", ":attached_party_rank"),
            (party_stack_get_troop_id, ":leader", ":attached_party", 0),
            (is_between, ":leader", active_npcs_begin, active_npcs_end),
            (call_script, "script_update_troop_location_notes", ":leader", 0),
          (try_end),
        (try_end),
  ]),

  #script_game_event_undetect_party:
  # This script is called from the game engine when player party inspects another party.
  # INPUT:
  # param1: Party-id
  ("game_event_undetect_party",
    [
        (store_script_param_1, ":party_id"),
        (try_begin),
          (party_slot_eq, ":party_id", slot_party_type, spt_kingdom_hero_party),
          (party_stack_get_troop_id, ":leader", ":party_id", 0),
          (is_between, ":leader", active_npcs_begin, active_npcs_end),
          (call_script, "script_update_troop_location_notes", ":leader", 0),
        (try_end),
  ]),

  #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_2, ":num_hours"),
      (store_div, ":num_days", ":num_hours", 24),
      (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", 30),
      (store_skill_level, ":skill", "skl_leadership", ":troop_no"),
      (store_attribute_level, ":charisma", ":troop_no", ca_charisma),
	  # NE skill
      #(val_mul, ":skill", 5),
	  (val_mul, ":skill", 10),
	  # NE end skill
      (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"),
	  
	  # NE kingdom
	    (try_begin), #Give the player 100 slots for free if they're a monarch - Jinnai
        (faction_slot_eq, "fac_player_supporters_faction", slot_faction_state, sfs_active),
        (faction_slot_eq, "fac_player_supporters_faction", slot_faction_leader, "trp_player"),
        (val_add, ":limit", 100),
      (try_end),
	  # NE end kingdom

      (assign, reg0, ":limit"),
      (set_trigger_result, reg0),
  ]),


  #script_game_reset_player_party_name:
  # This script is called from the game engine when the player name is changed.
  # INPUT: none
  # OUTPUT: none
  ("game_reset_player_party_name",
    [(str_store_troop_name, s5, "trp_player"),
     (party_set_name, "p_main_party", s5),
     ]),

  #script_game_get_troop_note
  # This script is called from the game engine when the notes of a troop is needed.
  # INPUT: arg1 = troop_no, arg2 = note_index
  # OUTPUT: s0 = note
  ("game_get_troop_note",
    [
      (store_script_param_1, ":troop_no"),
      (store_script_param_2, ":note_index"),
      (set_trigger_result, 0),

      (str_store_troop_name, s54, ":troop_no"),
      (try_begin),
        (eq, ":troop_no", "trp_player"),
        (this_or_next|eq, "$player_has_homage", 1),
        (eq, "$players_kingdom", "fac_player_supporters_faction"),
        (assign, ":troop_faction", "$players_kingdom"),
      (else_try),
        (store_troop_faction, ":troop_faction", ":troop_no"),
		

		
      (try_end),
      (str_clear, s49),
	  
	  #Family notes
      (try_begin),
        (this_or_next|is_between, ":troop_no", lords_begin, kingdom_ladies_end),
        (eq, ":troop_no", "trp_player"),
        (neg|is_between, ":troop_no", pretenders_begin, pretenders_end),
        (assign, ":num_relations", 0),

        (try_begin),
          (call_script, "script_troop_get_family_relation_to_troop", "trp_player", ":troop_no"),
          (gt, reg0, 0),
          (val_add, ":num_relations", 1),
        (try_end),
        (try_for_range, ":aristocrat", lords_begin, kingdom_ladies_end),
          (call_script, "script_troop_get_family_relation_to_troop", ":aristocrat", ":troop_no"),
          (gt, reg0, 0),
          (val_add, ":num_relations", 1),
        (try_end),
        (try_begin),
          (gt, ":num_relations", 0),
          (try_begin),
            (eq, ":troop_no", "trp_player"),
            (str_store_string, s49, "str__family_"),
          (else_try),
            (troop_get_slot, reg1, ":troop_no", slot_troop_age),
            (str_store_string, s49, "str__age_reg1_family_"),
          (try_end),
          (try_begin),
            (call_script, "script_troop_get_family_relation_to_troop", "trp_player", ":troop_no"),
            (gt, reg0, 0),
            (str_store_troop_name_link, s12, "trp_player"),
            (val_sub, ":num_relations", 1),
            (try_begin),
              (eq, ":num_relations", 0),
              (str_store_string, s49, "str_s49_s12_s11_end"),
            (else_try),
              (str_store_string, s49, "str_s49_s12_s11"),
            (try_end),
          (try_end),
          (try_for_range, ":aristocrat", lords_begin, kingdom_ladies_end),
            (call_script, "script_troop_get_family_relation_to_troop", ":aristocrat", ":troop_no"),
            (gt, reg0, 0),
            (try_begin),
              (neg|is_between, ":aristocrat", kingdom_ladies_begin, kingdom_ladies_end),
              (eq, "$cheat_mode", 1),
              (str_store_troop_name_link, s12, ":aristocrat"),
              (call_script, "script_troop_get_relation_with_troop", ":aristocrat", ":troop_no"),
              (str_store_string, s49, "str_s49_s12_s11_rel_reg0"),
            (else_try),
              (str_store_troop_name_link, s12, ":aristocrat"),
              (val_sub, ":num_relations", 1),
              (try_begin),
                (eq, ":num_relations", 0),
                (str_store_string, s49, "str_s49_s12_s11_end"),
              (else_try),
                (str_store_string, s49, "str_s49_s12_s11"),
              (try_end),
            (try_end),
          (try_end),
        (try_end),
      (try_end),
      
      (try_begin),
        (neq, ":troop_no", "trp_player"),
        (neg|is_between, ":troop_faction", kingdoms_begin, kingdoms_end),
        (neg|is_between, ":troop_no", companions_begin, companions_end),
        (neg|is_between, ":troop_no", pretenders_begin, pretenders_end),

        (try_begin),
          (eq, ":note_index", 0),
          (str_store_string, s0, "str_s54_has_left_the_realm"),
          (set_trigger_result, 1),
        (else_try),
          (str_clear, s0),
          (this_or_next|eq, ":note_index", 1),
          (eq, ":note_index", 2),
          (set_trigger_result, 1),
        (try_end),

      (else_try),
        (is_between, ":troop_no", companions_begin, companions_end),
        (neg|troop_slot_eq, ":troop_no", slot_troop_occupation, slto_kingdom_hero),
        (eq, ":note_index", 0),
        (set_trigger_result, 1),
        (str_clear, s0),
        (assign, ":companion", ":troop_no"),
        (str_store_troop_name, s4, ":companion"),
        (try_begin),
			(troop_get_slot, ":days_left", ":companion", slot_troop_days_on_mission),

			(this_or_next|main_party_has_troop, ":companion"),
			(this_or_next|troop_slot_ge, ":companion", slot_troop_current_mission, 1),
				(eq, "$g_player_minister", ":companion"),

			(try_begin),
				(troop_slot_eq, ":companion", slot_troop_current_mission, npc_mission_kingsupport),
				(str_store_string, s8, "str_gathering_support"),
				(try_begin),
					(eq, ":days_left", 1),
					(str_store_string, s5, "str_expected_back_imminently"),
				(else_try),	
					(assign, reg3, ":days_left"),
					(str_store_string, s5, "str_expected_back_in_approximately_reg3_days"),
				(try_end),
			(else_try),
				(troop_slot_eq, ":companion", slot_troop_current_mission, npc_mission_gather_intel),
				(troop_get_slot, ":town_with_contacts", ":companion", slot_troop_town_with_contacts),
				(str_store_party_name, s11, ":town_with_contacts"),
				
				(str_store_string, s8, "str_gathering_intelligence"),
				(try_begin),
					(eq, ":days_left", 1),
					(str_store_string, s5, "str_expected_back_imminently"),
				(else_try),	
					(assign, reg3, ":days_left"),
					(str_store_string, s5, "str_expected_back_in_approximately_reg3_days"),
				(try_end),
			(else_try),	
				
				(troop_slot_ge, ":companion", slot_troop_current_mission, npc_mission_peace_request),
				(neg|troop_slot_ge, ":companion", slot_troop_current_mission, 8),

				(troop_get_slot, ":faction", ":companion", slot_troop_mission_object),
				(str_store_faction_name, s9, ":faction"),
				(str_store_string, s8, "str_diplomatic_embassy_to_s9"),
				(try_begin),
					(eq, ":days_left", 1),
					(str_store_string, s5, "str_expected_back_imminently"),
				(else_try),	
					(assign, reg3, ":days_left"),
					(str_store_string, s5, "str_expected_back_in_approximately_reg3_days"),
				(try_end),
			(else_try),
				(eq, ":companion", "$g_player_minister"),
				(str_store_string, s8, "str_serving_as_minister"),
				(str_store_party_name, s9, "$g_player_court"),
				(is_between, "$g_player_court", centers_begin, centers_end),
				(str_store_string, s5, "str_in_your_court_at_s9"),
			(else_try),
				(eq, ":companion", "$g_player_minister"),
				(str_store_string, s8, "str_serving_as_minister"),
				(str_store_string, s5, "str_awaiting_the_capture_of_a_fortress_which_can_serve_as_your_court"),
			(else_try),
				(main_party_has_troop, ":companion"),
				(str_store_string, s8, "str_under_arms"),
				(str_store_string, s5, "str_in_your_party"),
			(try_end),	
			
			(str_store_string, s0, "str_s4_s8_s5"),
			
		(else_try),
			(str_store_string, s0, "str_whereabouts_unknown"),
		(try_end),
		
	  
	  (else_try),
        (is_between, ":troop_no", pretenders_begin, pretenders_end),
        (neg|troop_slot_eq, ":troop_no", slot_troop_occupation, slto_kingdom_hero),
        (neq, ":troop_no", "$supported_pretender"),

		
        (troop_get_slot, ":orig_faction", ":troop_no", slot_troop_original_faction),
        (try_begin),
          (faction_slot_eq, ":orig_faction", slot_faction_state, sfs_active),
          (faction_slot_eq, ":orig_faction", slot_faction_has_rebellion_chance, 1),
          (try_begin),
            (eq, ":note_index", 0),
            (str_store_faction_name_link, s56, ":orig_faction"),
            (str_store_string, s0, "@{s54} is a claimant to the throne of {s56}.", 0),
            (set_trigger_result, 1),
          (try_end),
        (else_try),
          (try_begin),
            (str_clear, s0),
            (this_or_next|eq, ":note_index", 0),
            (this_or_next|eq, ":note_index", 1),
            (eq, ":note_index", 2),
            (set_trigger_result, 1),
          (try_end),
        (try_end),
		
      (else_try),
        (try_begin),
          (eq, ":note_index", 0),
          (faction_get_slot, ":faction_leader", ":troop_faction", slot_faction_leader),
          (str_store_troop_name_link, s55, ":faction_leader"),
          (str_store_faction_name_link, s56, ":troop_faction"),
          (assign, ":troop_is_player_faction", 0),
          (assign, ":troop_is_faction_leader", 0),
          (try_begin),
            (eq, ":troop_faction", "fac_player_faction"),
            (assign, ":troop_is_player_faction", 1),
          (else_try),
            (eq, ":faction_leader", ":troop_no"),
            (assign, ":troop_is_faction_leader", 1),
          (try_end),
          (assign, ":num_centers", 0),
          (str_store_string, s58, "@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, s58, ":cur_center"),
            (else_try),
              (eq, ":num_centers", 1),
              (str_store_party_name_link, s57, ":cur_center"),
              (str_store_string, s58, "@{s57} and {s58}"),
            (else_try),
              (str_store_party_name_link, s57, ":cur_center"),
              (str_store_string, s58, "@{!}{s57}, {s58}"),
            (try_end),
            (val_add, ":num_centers", 1),
          (try_end),
          (troop_get_type, reg3, ":troop_no"),
          (troop_get_slot, reg5, ":troop_no", slot_troop_renown),
          (troop_get_slot, reg15, ":troop_no", slot_troop_controversy),
		  
          (str_clear, s59),
          (try_begin),   
            (call_script, "script_troop_get_player_relation", ":troop_no"),
            (assign, ":relation", reg0),
            (store_add, ":normalized_relation", ":relation", 100),
            (val_add, ":normalized_relation", 5),
            (store_div, ":str_offset", ":normalized_relation", 10),
            (val_clamp, ":str_offset", 0, 20),
            (store_add, ":str_id", "str_relation_mnus_100_ns",  ":str_offset"),
            (neq, ":str_id", "str_relation_plus_0_ns"),
            (str_store_string, s60, "@{reg3?She:He}"),
            (str_store_string, s59, ":str_id"),
            (str_store_string, s59, "@{!}^{s59}"),
          (try_end),
          #lord recruitment changes begin
          #This sends a bunch of political information to s47.
    
          #refresh registers
          (assign, reg9, ":num_centers"),
          (troop_get_type, reg3, ":troop_no"),
          (troop_get_slot, reg5, ":troop_no", slot_troop_renown),
          (assign, reg4, ":troop_is_faction_leader"),
          (assign, reg6, ":troop_is_player_faction"),
          
          (troop_get_slot, reg17, ":troop_no", slot_troop_wealth), #DEBUGS
          (str_store_string, s0, "str_lord_info_string", 0),
          #lord recruitment changes end
          (add_troop_note_tableau_mesh, ":troop_no", "tableau_troop_note_mesh"),
          (set_trigger_result, 1),
        (try_end),
      (try_end),
     ]),
  
  #script_game_get_center_note
  # This script is called from the game engine when the notes of a center is needed.
  # INPUT: arg1 = center_no, arg2 = note_index
  # OUTPUT: s0 = note
  ("game_get_center_note",
    [
      (store_script_param_1, ":center_no"),
      (store_script_param_2, ":note_index"),

      (set_trigger_result, 0),
      (try_begin),
        (eq, ":note_index", 0),
        (party_get_slot, ":lord_troop", ":center_no", slot_town_lord),
        (try_begin),
          (ge, ":lord_troop", 0),
          (store_troop_faction, ":lord_faction", ":lord_troop"),
          (str_store_troop_name_link, s1, ":lord_troop"),
          (try_begin),
            (eq, ":lord_troop", "trp_player"),
            (gt, "$players_kingdom", 0),
            (str_store_faction_name_link, s2, "$players_kingdom"),
          (else_try),
            (str_store_faction_name_link, s2, ":lord_faction"),
          (try_end),
          (str_store_party_name, s50, ":center_no"),
          (try_begin),
            (party_slot_eq, ":center_no", slot_party_type, spt_town),
            (str_store_string, s51, "@The town of {s50}"),
          (else_try),
            (party_slot_eq, ":center_no", slot_party_type, spt_village),
            (party_get_slot, ":bound_center", ":center_no", slot_village_bound_center),
            (str_store_party_name_link, s52, ":bound_center"),
            (str_store_string, s51, "@The village of {s50} near {s52}"),
          (else_try),
            (str_store_string, s51, "@{!}{s50}"),
          (try_end),
          (str_store_string, s2, "@{s51} belongs to {s1} of {s2}.^"),
        (else_try),
          (str_clear, s2),
        (try_end),
        (try_begin),
          (is_between, ":center_no", villages_begin, villages_end),
        (else_try),
          (assign, ":num_villages", 0),
          (try_for_range_backwards, ":village_no", villages_begin, villages_end),
            (party_slot_eq, ":village_no", slot_village_bound_center, ":center_no"),
            (try_begin),
              (eq, ":num_villages", 0),
              (str_store_party_name_link, s8, ":village_no"),
            (else_try),
              (eq, ":num_villages", 1),
              (str_store_party_name_link, s7, ":village_no"),
              (str_store_string, s8, "@{s7} and {s8}"),
            (else_try),
              (str_store_party_name_link, s7, ":village_no"),
              (str_store_string, s8, "@{!}{s7}, {s8}"),
            (try_end),
            (val_add, ":num_villages", 1),
          (try_end),
          (try_begin),
            (eq, ":num_villages", 0),
            (str_store_string, s2, "@{s2}It has no villages.^"),
          (else_try),
            (store_sub, reg0, ":num_villages", 1),
            (str_store_string, s2, "@{s2}{reg0?Its villages are:Its village is} {s8}.^"),
          (try_end),
        (try_end),
        (call_script, "script_get_prosperity_text_to_s50", ":center_no"),
        #(party_get_slot, reg7, ":center_no", slot_town_prosperity),
        (str_store_string, s0, "@{s2}Its prosperity is: {s50}", 0),

        (set_trigger_result, 1),
      (try_end),
     ]),

  #script_game_get_faction_note
  # This script is called from the game engine when the notes of a faction is needed.
  # INPUT: arg1 = faction_no, arg2 = note_index
  # OUTPUT: s0 = note
  ("game_get_faction_note",
    [
      (store_script_param_1, ":faction_no"),
      (store_script_param_2, ":note_index"),
      (set_trigger_result, 0),
      
##      (try_begin),
##        (eq, 2, 1),
##        (str_store_faction_name, s14, ":faction_no"),
##        (assign, reg4, "$temp"),
##        (display_message, "str_updating_faction_notes_for_s14_temp_=_reg4"),
##      (try_end),

      (try_begin),
        (is_between, ":faction_no", kingdoms_begin, kingdoms_end),
        (faction_slot_eq, ":faction_no", slot_faction_state, sfs_active),
        #conditions end
        (try_begin),
            (eq, ":note_index", 0),
          (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, "@nowhere"),
          (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, ":loop_var", "trp_kingdom_heroes_including_player_begin", active_npcs_end),
            (assign, ":cur_troop", ":loop_var"),
            (try_begin),
              (eq, ":loop_var", "trp_kingdom_heroes_including_player_begin"),
              (assign, ":cur_troop", "trp_player"),
              (assign, ":troop_faction", "$players_kingdom"),
            (else_try),
              (store_troop_faction, ":troop_faction", ":cur_troop"),
            (try_end),
            (eq, ":troop_faction", ":faction_no"),
            (neq, ":cur_troop", ":faction_leader"),
            (troop_slot_eq, ":cur_troop", slot_troop_occupation, slto_kingdom_hero),
            (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),
              
              #wars
          (str_store_string, s12, "@noone"),
   #       (assign, ":num_enemies", 0),
   #       (try_for_range_backwards, ":cur_faction", kingdoms_begin, kingdoms_end),
   #         (faction_slot_eq, ":cur_faction", slot_faction_state, sfs_active),
   #         (store_relation, ":cur_relation", ":cur_faction", ":faction_no"),
   #         (lt, ":cur_relation", 0),
   #         (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, "@the {s11} and the {s12}"),
   #         (else_try),
   #           (str_store_faction_name_link, s11, ":cur_faction"),
   #           (str_store_string, s12, "@the {s11}, the {s12}"),
   #         (try_end),
   #         (val_add, ":num_enemies", 1),
   #       (try_end),
              
          (str_store_string, s21, "str_foreign_relations__"),
              
              #other foreign relations
          (try_for_range, ":cur_faction", kingdoms_begin, kingdoms_end),
            (faction_slot_eq, ":cur_faction", slot_faction_state, sfs_active),
            (neq, ":faction_no", ":cur_faction"),
            (str_store_faction_name_link, s14, ":cur_faction"),
            (call_script, "script_diplomacy_faction_get_diplomatic_status_with_faction", ":faction_no", ":cur_faction"),
            (assign, ":diplomatic_status", reg0),
			(assign, ":duration_of_status", reg1),
			
            (call_script, "script_diplomacy_faction_get_diplomatic_status_with_faction", ":cur_faction", ":faction_no"),
            (assign, ":reverse_diplomatic_status", reg0),
#			(assign, ":reverse_diplomatic_duration", reg1),

            (try_begin),
              (eq, ":diplomatic_status", -2),
              (str_store_string, s21, "str_s21__the_s5_is_at_war_with_the_s14"),
              (store_add, ":slot_war_damage_inflicted", ":cur_faction", slot_faction_war_damage_inflicted_on_factions_begin),
              (val_sub, ":slot_war_damage_inflicted", kingdoms_begin),
              (faction_get_slot, ":war_damage_inflicted", ":faction_no", ":slot_war_damage_inflicted"),
              (store_mul, ":war_damage_inflicted_x_2", ":war_damage_inflicted", 2),

              (store_add, ":slot_war_damage_suffered", ":faction_no", slot_faction_war_damage_inflicted_on_factions_begin),
              (val_sub, ":slot_war_damage_suffered", kingdoms_begin),
              (faction_get_slot, ":war_damage_suffered", ":cur_faction", ":slot_war_damage_suffered"),
              (store_mul, ":war_damage_suffered_x_2", ":war_damage_suffered", 2),
			  
			  
			  (assign, ":war_cause", 0),
			  (assign, ":attacker", 0),
			  (try_for_range, ":log_entry", 0, "$num_log_entries"),
				(troop_get_slot, ":type", "trp_log_array_entry_type", ":log_entry"),
				(is_between, ":type", logent_faction_declares_war_out_of_personal_enmity, logent_war_declaration_types_end),
				(troop_get_slot, ":actor", "trp_log_array_actor", ":log_entry"),
				(troop_get_slot, ":object", "trp_log_array_faction_object", ":log_entry"),

				(try_begin),
					(eq, ":actor", ":cur_faction"),
					(eq, ":object", ":faction_no"),
					(assign, ":war_cause", ":type"),
					(assign, ":attacker", ":actor"),
				(else_try),	
					(eq, ":actor", ":faction_no"),
					(eq, ":object", ":cur_faction"),
					(assign, ":war_cause", ":type"),
					(assign, ":attacker", ":actor"),
				(try_end),
			  (try_end),	

			  #bug fix! backing up s8 to somewhere else
                          (str_store_string, s25, s8),
			  (try_begin),
			    (gt, ":war_cause", 0),
				(str_store_faction_name, s8, ":attacker"),
				(try_begin),
					(eq, ":war_cause", logent_faction_declares_war_out_of_personal_enmity),
					(str_store_string, s21, "str_s21_the_s8_declared_war_out_of_personal_enmity"),
				(else_try),			
					(eq, ":war_cause", logent_faction_declares_war_to_respond_to_provocation),
					(str_store_string, s21, "str_s21_the_s8_declared_war_in_response_to_border_provocations"),
				(else_try),			
					(eq, ":war_cause", logent_faction_declares_war_to_curb_power),
					(str_store_string, s21, "str_s21_the_s8_declared_war_to_curb_the_other_realms_power"),
				(else_try),	
					(eq, ":war_cause", logent_faction_declares_war_to_regain_territory),
					(str_store_string, s21, "str_s21_the_s8_declared_war_to_regain_lost_territory"),
				(else_try),
					(eq, ":war_cause", logent_player_faction_declares_war),
					(neq, ":attacker", "fac_player_supporters_faction"),
					(str_store_string, s21, "str_s21_the_s8_declared_war_as_part_of_a_bid_to_conquer_all_calradia"),
				(try_end),
			  (try_end),
			  #bug fix! restoring the back up to s8
                          (str_store_string, s8, s25),

              (try_begin),
                (gt, ":war_damage_inflicted", ":war_damage_suffered_x_2"),
                (str_store_string, s21, "str_s21_the_s5_has_had_the_upper_hand_in_the_fighting"),
              (else_try),
                (gt, ":war_damage_suffered", ":war_damage_inflicted_x_2"),
                (str_store_string, s21, "str_s21_the_s5_has_gotten_the_worst_of_the_fighting"),
              (else_try),
                (gt, ":war_damage_inflicted", 100),
                (gt, ":war_damage_inflicted", 100),
                (str_store_string, s21, "str_s21_the_fighting_has_gone_on_for_some_time_and_the_war_may_end_soon_with_a_truce"),
              (else_try),
                (str_store_string, s21, "str_s21_the_fighting_has_begun_relatively_recently_and_the_war_may_continue_for_some_time"),
              (try_end),
              (try_begin),
                (eq, "$cheat_mode", 1),
                (assign, reg4, ":war_damage_inflicted"),
                (assign, reg5, ":war_damage_suffered"),
                (str_store_string, s21, "str_s21_reg4reg5"),
              (try_end),
            (else_try),
              (eq, ":diplomatic_status", 1),
              (str_clear, s18),
              (try_begin),
                (neq, ":reverse_diplomatic_status", 1),
                (str_store_string, s18, "str__however_the_truce_is_no_longer_binding_on_the_s14"),
              (try_end),
			  (assign, reg1, ":duration_of_status"),
              (str_store_string, s21, "str_s21__the_s5_is_bound_by_truce_not_to_attack_the_s14s18_the_truce_will_expire_in_reg1_days"),
            (else_try),
              (eq, ":diplomatic_status", -1),
              (str_store_string, s21, "str_s21__the_s5_has_recently_suffered_provocation_by_subjects_of_the_s14_and_there_is_a_risk_of_war"),
            (else_try),
              (eq, ":diplomatic_status", 0),
              (str_store_string, s21, "str_s21__the_s5_has_no_outstanding_issues_with_the_s14"),
            (try_end),
            (try_begin),
              (eq, ":reverse_diplomatic_status", -1),
              (str_store_string, s21, "str_s21_the_s14_was_recently_provoked_by_subjects_of_the_s5_and_there_is_a_risk_of_war_"),
            (try_end),
            (try_begin),
              (eq, "$cheat_mode", 1),
              (call_script, "script_npc_decision_checklist_peace_or_war", ":faction_no", ":cur_faction", -1),
			  (str_store_string, s21, "@{!}DEBUG : {s21}.^CHEAT MODE ASSESSMENT: {s14}^"), 
            (try_end),
          (try_end),
          (str_store_string, s0, "str_the_s5_is_ruled_by_s6_it_occupies_s8_its_vassals_are_s10__s21", 0),
          (set_trigger_result, 1),
        (try_end),
      (else_try),
        (is_between, ":faction_no", kingdoms_begin, kingdoms_end),
        (faction_slot_eq, ":faction_no", slot_faction_state, sfs_defeated),
        (try_begin),
          (eq, ":note_index", 0),
          (str_store_faction_name, s5, ":faction_no"),
          (str_store_string, s0, "@{s5} has been defeated!", 0),
          (set_trigger_result, 1),
        (else_try),
          (eq, ":note_index", 1),
          (str_clear, s0),
          (set_trigger_result, 1),
        (try_end),
      (else_try),
        (try_begin),
          (this_or_next|eq, ":note_index", 0),
          (eq, ":note_index", 1),
          (str_clear, s0),
          (set_trigger_result, 1),
        (try_end),
      (try_end),
     ]),

  #script_game_get_quest_note
  # This script is called from the game engine when the notes of a quest is needed.
  # INPUT: arg1 = quest_no, arg2 = note_index
  # OUTPUT: s0 = note
  ("game_get_quest_note",
    [
##      (store_script_param_1, ":quest_no"),
##      (store_script_param_2, ":note_index"),
      (set_trigger_result, 0), # set it to 1 if this script is wanted to be used rather than static notes
     ]),

  #script_game_get_info_page_note
  # This script is called from the game engine when the notes of a info_page is needed.
  # INPUT: arg1 = info_page_no, arg2 = note_index
  # OUTPUT: s0 = note
  ("game_get_info_page_note",
    [
      (store_script_param_1, ":info_page_no"),
      (store_script_param_2, ":note_index"),
      (set_trigger_result, 0),

      (try_begin),
        (neq, ":note_index", 0),

      (else_try),
        (eq, ":info_page_no", "ip_relations"),

        (try_for_range, ":active_npc", active_npcs_begin, active_npcs_end),
          (troop_slot_eq, ":active_npc", slot_troop_occupation, slto_kingdom_hero),
          (troop_slot_ge, ":active_npc", slot_troop_met, 1),
          (call_script, "script_troop_get_player_relation", ":active_npc"),
          (troop_set_slot, ":active_npc", slot_troop_tmp1, reg0),
        (else_try),
          (troop_set_slot, ":active_npc", slot_troop_tmp1, -200),
        (try_end),
        (str_clear, s0),
        (try_for_range_backwards, ":cur_kingdom", kingdoms_begin, kingdoms_end),
          (faction_slot_eq, ":cur_kingdom", slot_faction_state, sfs_active),
          (assign, ":know_any_lords", 0),
          (str_clear, s1),
          (str_clear, s5),

          (assign, ":not_know_any_lords", 0),
          (try_for_range_backwards, ":stranger_npc", active_npcs_begin, active_npcs_end),
            (troop_slot_eq, ":stranger_npc", slot_troop_tmp1, -200),
            (troop_slot_eq, ":stranger_npc", slot_troop_occupation, slto_kingdom_hero),
            (store_troop_faction, ":npc_faction", ":stranger_npc"),
            (eq, ":npc_faction", ":cur_kingdom"),
            (str_store_troop_name_link, s6, ":stranger_npc"),
            (try_begin),
              (eq, ":not_know_any_lords", 0),
              (str_store_string_reg, s5, s6),
            (else_try),
              (eq, ":not_know_any_lords", 1),
              (str_store_string, s5, "@{s6} and {s5}"),
            (else_try),
              (str_store_string, s5, "@{s6}, {s5}"),
            (try_end),
            (val_add, ":not_know_any_lords", 1),
          (try_end),
          (try_begin),
            (eq, ":not_know_any_lords", 0),
            (str_clear, s5),
          (else_try),
            (str_store_string, s5, "@^^   You have never met {s5}."),
          (try_end),

          (try_for_range, ":unused", active_npcs_begin, active_npcs_end),
            (assign, ":score_to_beat", -100),
            (assign, ":best_relation_remaining_npc", -1),
            (try_for_range, ":active_npc", active_npcs_begin, active_npcs_end),
              (troop_slot_eq, ":active_npc", slot_troop_occupation, slto_kingdom_hero),
              (neg|troop_slot_eq, ":active_npc", slot_troop_tmp1, -200),
              (store_troop_faction, ":npc_faction", ":active_npc"),
              (eq, ":npc_faction", ":cur_kingdom"),
              (troop_get_slot, ":relation_with_player", ":active_npc", slot_troop_tmp1),
              (ge, ":relation_with_player", ":score_to_beat"),
              (assign, ":score_to_beat", ":relation_with_player"),
              (assign, ":best_relation_remaining_npc", ":active_npc"),
            (try_end),
            (gt, ":best_relation_remaining_npc", -1),
            (str_store_troop_name_link, s4, ":best_relation_remaining_npc"),
            (assign, reg4, ":score_to_beat"),
            (assign, reg5, 0),
            (try_begin),
              (gt, reg4, 0), # Positive
              (assign, reg5, 1),
            (try_end),
            (try_begin),
              (troop_slot_eq, ":best_relation_remaining_npc", slot_troop_location_status, tls_garrisoned),
              (troop_get_slot, ":center", ":best_relation_remaining_npc", slot_troop_location_center),
              (str_store_party_name_link, s7, ":center"),
              (str_store_string, s7, "@is stationed at {s7}"),
            (else_try),
              (troop_slot_eq, ":best_relation_remaining_npc", slot_troop_location_status, tls_nearby),
              (troop_get_slot, ":center", ":best_relation_remaining_npc", slot_troop_location_center),
              (str_store_party_name_link, s7, ":center"),
              (str_store_string, s7, "@is in the vicinity of {s7}"),
            (else_try),
              (troop_slot_eq, ":best_relation_remaining_npc", slot_troop_location_status, tls_imprisoned),
              (troop_get_slot, ":center", ":best_relation_remaining_npc", slot_troop_location_center),
              (is_between, ":center", walled_centers_begin, walled_centers_end),
              (str_store_party_name_link, s7, ":center"),
              (str_store_string, s7, "@is imprisoned at {s7}"),
            (else_try),
              (troop_slot_eq, ":best_relation_remaining_npc", slot_troop_location_status, tls_imprisoned),
              (str_store_string, s7, "@is taken captive by enemies"),
            (else_try),
              (str_store_string, s7, "@whereabouts are unknown"),
            (try_end),
            (str_store_string, s1, "@{s1}^      {s4} ({reg5?+:}{reg4}) {s7}."),
            (troop_set_slot, ":best_relation_remaining_npc", slot_troop_tmp1, -200),
            (assign, ":know_any_lords", 1),
          (try_end),
          (try_begin),
            (eq, ":know_any_lords", 1),
            (str_store_string, s1, "@^^   Known lords:{s1}"),
          (else_try),
            (str_clear, s1),
          (try_end),

          (try_begin),
            (eq, ":cur_kingdom", "fac_player_supporters_faction"),
            (str_clear, s3),
          (else_try),
            (store_relation, ":cur_relation", "fac_player_supporters_faction", ":cur_kingdom"),
            (call_script, "script_relation_text_to_s3", ":cur_relation"),
            (assign, reg1, ":cur_relation"),
            (assign, reg2, 0),
            (try_begin),
              (gt, reg1, 0),
              (assign, reg2, 1),
            (try_end),
            (str_store_string, s3, "@ is {s3} you ({reg2?+:}{reg1})"),
          (try_end),
          (str_store_faction_name_link, s4, ":cur_kingdom"),
          (str_store_string, s2, "@{s4}{s3}"),

          (str_store_string, s0, "@{s2}{s1}{s5}^^{s0}"),

        (try_end),

        (set_trigger_result, 1),

      (else_try),
        (eq, ":info_page_no", "ip_party"),

        # Party Size

        (call_script, "script_game_get_party_companion_limit"),
        (assign, reg10, reg0), # Final value
        (store_skill_level, reg11, "skl_leadership", "trp_player"), # Leadership score
        (store_mul, reg12, reg11, 10), # Leadership bonus
        (store_attribute_level, reg13, "trp_player", ca_charisma), # Charisma score
        (assign, reg14, reg13), # Charisma bonus
        (troop_get_slot, reg15, "trp_player", slot_troop_renown), # Renown score
        (store_div, reg16, reg15, 25), # Renown bonus
        (str_store_string, s1, "@Maximum party size: {reg10} = 30 (base value) + {reg12} (leadership {reg11}) + {reg14} (charisma {reg13}) + {reg16} ({reg15} renown)"),
	    (try_begin), #Give the player 100 slots for free if they're a monarch - Jinnai
          (faction_slot_eq, "fac_player_supporters_faction", slot_faction_state, sfs_active),
          (faction_slot_eq, "fac_player_supporters_faction", slot_faction_leader, "trp_player"),
          (str_store_string, s1, "@{s1} + 100 (faction leader bonus)"),
        (try_end),

        # Party Max Prizoners

        (store_skill_level, reg17, "skl_prisoner_management", "trp_player"),
        (call_script, "script_game_get_party_prisoner_limit"),
        (str_store_string, s2, "@Maximum party prisoners: {reg0} (prisoner management {reg17})"),

        # Party Morale

        (call_script, "script_get_player_party_morale_values"),
        (assign, reg33, reg0), # Calculated value
        (party_get_morale, reg20, "p_main_party"), # Actual party morale

        (assign, reg21, 50), # Base
        (assign, reg22, "$g_player_party_morale_modifier_leadership"), # Leadership
        (assign, reg23, "$g_player_party_morale_modifier_party_size"), # NEG: party size
        (assign, reg24, "$g_player_party_morale_modifier_food"), # Food
        (assign, reg25, "$g_player_party_morale_modifier_no_food"), # NEG: no food
        (assign, reg26, "$g_player_party_morale_modifier_debt"), # NEG: debt
        (assign, reg27, "$g_player_party_morale_modifier_booze"), # Booze
        (assign, reg28, 1), # Food present
        (try_begin),
          (eq, reg24, 0),
          (assign, reg28, 0),
        (try_end),
        (assign, reg29, 1), # Party morale positive
        (try_begin),
          (lt, reg20, 0),
          (assign, reg29, 0),
        (try_end),
        (assign, reg30, 0), # Debt factor present
        (try_begin),
          (neq, reg26, 0),
          (assign, reg30, 1),
        (try_end),
        (assign, reg31, 0), # Booze factor present
        (try_begin),
          (neq, reg27, 0),
          (assign, reg31, 1),
        (try_end),
        (party_get_num_companions, reg32, "p_main_party"), # Party size
        (val_sub, reg32, 1), # Ignore player himself

        (store_sub, reg34, reg20, reg33), # Final bonus - recent events
        (assign, reg35, 1), # Modifiers positive
        (try_begin),
          (lt, reg34, 0),
          (assign, reg35, 0),
          (val_abs, reg34),
        (try_end),

        (str_store_string, s3, "@Party morale:{reg29? +: }{reg20} = {reg21} (base) + {reg22} (leadership {reg11}) - {reg23} ({reg32} companions) {reg28?+ {reg24} (food):- {reg25} (no food)}{reg30? - {reg26} (debt):{!}}{reg31? + {reg27} (booze):{!}} {reg35?+:-} {reg34} (recent events)"),

        # Troops Morale

        (str_clear, s4),
        (assign, ":extras", 0),
        (try_for_range, ":kingdom_no", npc_kingdoms_begin, npc_kingdoms_end),
          (faction_get_slot, ":faction_morale", ":kingdom_no",  slot_faction_morale_of_player_troops),
          (val_div, ":faction_morale", 100),
          (neq, ":faction_morale", 0),
          (assign, reg1, ":faction_morale"),
          (assign, reg2, 0),
          (try_begin),
            (ge, reg1, 0),
            (assign, reg2, 1),
          (try_end),
          (str_store_faction_name_link, s5, ":kingdom_no"),
          (str_store_string, s4, "@{s4}^    For {s5} troops:{reg2? +: }{reg1}."),
          (assign, ":extras", 1),
        (try_end),
        (try_begin),
          (eq, ":extras", 1),
          (str_store_string, s4, "@^^Extra morale modifiers for faction troops:{s4}"),
        (try_end),

        # Final Output

        (str_store_string, s0, "@{s1}.^^{s2}.^^{s3}.{s4}^^Party food reserves calculation is not available yet.^^Party speed calculation is not available yet."),
        (set_trigger_result, 1),

      (else_try),
        (eq, ":info_page_no", "ip_fiefs"),

        # Fief: prosperity, siege status, buildings, current construction/time, recruit availability, merc availability, tournament, garrison
        # Town: prosperity, relation, enterprise (if any), buildings, construction, mercenaries, nobles, elites, ransom broker available, npc available, tournament, garrison, prisoners, siege status
        # Castle: buildings, construction, garrison, prisoners, siege status
        # Village: prosperity, cattle, relation, buildings, construction, volunteers available, raid status, bandit attack
        #(try_begin, ":cur_center", towns_begin, towns_end),
        #(try_end),
        #(try_begin, ":cur_center", castles_begin, castles_end),
        #(try_end),
        #(try_begin, ":cur_center", villages_begin, villages_end),
        #(try_end),

      (else_try),
        (eq, ":info_page_no", "ip_characters"),

        # Hero and Companions Report
        #
        # Lav, lord/lady/king/queen/mercenary of <kingdom>/the free-roaming adventurer.
        # Renown 600, Honour 50, Right to Rule 10, Controversy 15. Reading Essays of Logic at 24%.

        # Player name and status
        (str_store_troop_name_link, s2, "trp_player"),
        (try_begin),
          (gt, "$players_kingdom", 0),
          (str_store_faction_name_link, s3, "$players_kingdom"),
          (try_begin),
            (this_or_next|is_between, "$players_kingdom", npc_kingdoms_begin, npc_kingdoms_end),
            (neg|faction_slot_eq, "fac_player_supporters_faction", slot_faction_leader, "trp_player"),
            (str_store_string, s3, "@{lord/lady} of {s3}"),
          (else_try),  
            (str_store_string, s3, "@{king/queen} of {s3}"),      
          (try_end),
        (else_try),
          (str_store_string, s3, "@free-roaming adventurer"),
        (try_end),

        # Player renown and honor
        (assign, reg3, "$player_honor"),
        (troop_get_slot, reg2, "trp_player", slot_troop_renown),
        (str_store_string, s4, "@Renown {reg2}, honour {reg3}"),

        # Player right to rule
        (str_clear, s5),
        (try_begin),
          (gt, "$player_right_to_rule", 0),
          (assign, reg1, "$player_right_to_rule"),
          (str_store_string, s5, "@, right to rule {reg1}"),
        (try_end),

        # Player controversy
        (str_clear, s6),
        (troop_get_slot, reg4, "trp_player", slot_troop_controversy),
        (try_begin),
            (neq, reg4, 0),
            (str_store_string, s6, "@, controversy {reg4}"),
        (try_end),

        # Player reading books
        (str_clear, s7),
        (try_begin),
          (gt, "$g_player_reading_book", 0),
          (player_has_item, "$g_player_reading_book"),
          (str_store_item_name, s7, "$g_player_reading_book"),
          (item_get_slot, reg1, "$g_player_reading_book", slot_item_book_reading_progress),
          (val_div, reg1, 10),
          (str_store_string, s7, "@^You are reading {s7} at {reg1}%."),
        (else_try),
          (assign, "$g_player_reading_book", 0),
          (str_store_string, s7, "@^You are not reading any books."),
        (try_end),

        # Player ruling claims
        (str_clear, s8),
        (try_begin),
          (this_or_next|gt, "$claim_arguments_made", 0),
          (this_or_next|gt, "$ruler_arguments_made", 0),
          (this_or_next|gt, "$victory_arguments_made", 0),
          (this_or_next|gt, "$lords_arguments_made", 0),
          (eq, 1, 0),
          (assign, reg3, "$claim_arguments_made"),
          (assign, reg4, "$ruler_arguments_made"),
          (assign, reg5, "$victory_arguments_made"),
          (assign, reg6, "$lords_arguments_made"),
          (assign, reg7, "$benefit_arguments_made"),
          (str_store_string, s8, "str_political_arguments_made_legality_reg3_rights_of_lords_reg4_unificationpeace_reg5_rights_of_commons_reg6_fief_pledges_reg7"),
          (str_store_string, s8, "@^{s8}"),
        (try_end),

        # Player wounds
        (call_script, "script_describe_hero_wounds_to_s9", "trp_player"),

        # Player description
        (str_store_string, s0, "@{s2}, {s3}.^{s4}{s5}{s6}.{s7}{s8}{s9}"),

        # Spouse/betrothed description
        (try_begin),
          (troop_get_slot, ":spouse_or_betrothed", "trp_player", slot_troop_spouse),
          (try_begin),
            (troop_get_type, ":is_female", "trp_player"),
            (eq, ":is_female", 1),
            (str_store_string, s2, "str_husband"),
          (else_try),
            (str_store_string, s2, "str_wife"),
          (try_end),
          (try_begin),
            (le, ":spouse_or_betrothed", 0),
            (troop_get_slot, ":spouse_or_betrothed", "trp_player", slot_troop_betrothed),
            (str_store_string, s2, "str_betrothed"),
          (try_end),	
          (gt, ":spouse_or_betrothed", 0),	
          (str_store_troop_name_link, s1, ":spouse_or_betrothed"),
          (troop_get_slot, ":cur_center", ":spouse_or_betrothed", slot_troop_cur_center),
          (try_begin),
            (is_between, ":cur_center", centers_begin, centers_end),
            (str_store_party_name_link, s3, ":cur_center"),
            (str_store_string, s3, "@resides in {s3}"),
          (else_try),
            (troop_slot_eq, ":spouse_or_betrothed", slot_troop_occupation, slto_kingdom_hero),
            (str_store_string, s3, "@is leading a party"),
          (else_try),	
            (str_store_string, s3, "@ has disappeared"),
          (try_end),
          (troop_get_slot, reg2, ":spouse_or_betrothed", slot_troop_renown),
          (troop_get_slot, reg3, ":spouse_or_betrothed", slot_troop_controversy),
          (str_store_string, s0, "@{s0}^^{s1}, your {s2}, {s3}.^Renown {reg2}, controversy {reg3}."),
        (try_end),

        # NPCs description
        # Baheshtur, free-roaming adventurer. Renown 150, controversy 10.
        # Alyssa, follower of Lav, currently on a mission.
        # Achilles, lord/lady/minister of <kingdom>.

        (try_for_range, ":companion", companions_begin, companions_end),
          (troop_slot_eq, ":companion", slot_troop_met, 1),
          (str_store_troop_name, s1, ":companion"),
          (try_begin),
            (troop_slot_eq, ":companion", slot_troop_occupation, slto_kingdom_hero),
            (str_store_troop_name_link, s1, ":companion"),
            (str_store_string, s2, "@your faithful vassal"),
          (else_try),
            (troop_slot_eq, ":companion", slot_troop_occupation, slto_player_companion),
            (str_store_string, s2, "@your follower"),
          (else_try),
            (str_store_string, s2, "@free-roaming adventurer"),
          (try_end),
          # Mission
          (str_clear, s3),
          (troop_get_slot, reg2, ":companion", slot_troop_days_on_mission),
          (try_begin),
            (gt, reg2, 1),
            (str_store_string, s4, "@in {reg2} days"),
          (else_try),
            (str_store_string, s4, "@imminently"),
          (try_end),
          (try_begin),
            (troop_slot_eq, ":companion", slot_troop_current_mission, npc_mission_kingsupport),
            (str_store_string, s3, "@is gathering support and is expected back {s4}"),
          (else_try),
            (troop_slot_eq, ":companion", slot_troop_current_mission, npc_mission_gather_intel),
            (str_store_string, s3, "@is gathering intelligence and is expected back {s4}"),
          (else_try),
            (troop_slot_ge, ":companion", slot_troop_current_mission, npc_mission_peace_request),
            (neg|troop_slot_ge, ":companion", slot_troop_current_mission, 8),
            (troop_get_slot, ":faction", ":companion", slot_troop_mission_object),
            (str_store_faction_name_link, s5, ":faction"),
            (str_store_string, s3, "@is on a diplomatic mission to {s5} and is expected back {s4}"),
          (else_try),
            (eq, ":companion", "$g_player_minister"),
            (str_store_party_name_link, s5, "$g_player_court"),
            (str_store_string, s3, "@is at your court in {s5}"),
          (else_try),
            (troop_slot_eq, ":companion", slot_troop_current_mission, npc_mission_rejoin_when_possible),
            (str_store_string, s3, "@is trying to rejoin your party"),
          (try_end),
          (troop_get_slot, reg2, ":companion", slot_troop_renown),
          (troop_get_slot, reg3, ":companion", slot_troop_controversy),
          (call_script, "script_describe_hero_wounds_to_s9", ":companion"),

          (str_store_string, s0, "@{s0}^^{s1}, {s2}{s3}.^Renown {reg2}, controversy {reg3}.{s9}"),
        (try_end),

        (set_trigger_result, 1),

      (try_end),
     ]),

  #script_game_get_scene_name
  # This script is called from the game engine when a name for the scene is needed.
  # INPUT: arg1 = scene_no
  # OUTPUT: s0 = name
  ("game_get_scene_name",
    [
      (store_script_param, ":scene_no", 1),
      (try_begin),
        (is_between, ":scene_no", multiplayer_scenes_begin, multiplayer_scenes_end),
        (store_sub, ":string_id", ":scene_no", multiplayer_scenes_begin),
        (val_add, ":string_id", multiplayer_scene_names_begin),
        (str_store_string, s0, ":string_id"),
      (try_end),
     ]),
  
  #script_game_get_mission_template_name
  # This script is called from the game engine when a name for the mission template is needed.
  # INPUT: arg1 = mission_template_no
  # OUTPUT: s0 = name
  ("game_get_mission_template_name",
    [
      (store_script_param, ":mission_template_no", 1),
      (call_script, "script_multiplayer_get_mission_template_game_type", ":mission_template_no"),
      (assign, ":game_type", reg0),
      (try_begin),
        (is_between, ":game_type", 0, multiplayer_num_game_types),
        (store_add, ":string_id", ":game_type", multiplayer_game_type_names_begin),
        (str_store_string, s0, ":string_id"),
      (try_end),
     ]),

  #script_add_kill_death_counts
  # INPUT: arg1 = killer_agent_no, arg2 = dead_agent_no
  # OUTPUT: none
  ("add_kill_death_counts",
   [
      (store_script_param, ":killer_agent_no", 1),
      (store_script_param, ":dead_agent_no", 2),
      
      (try_begin),
        (ge, ":killer_agent_no", 0),
        (agent_get_team, ":killer_agent_team", ":killer_agent_no"),
      (else_try),
        (assign, ":killer_agent_team", -1),
      (try_end),

      (try_begin),
        (ge, ":dead_agent_no", 0),
        (agent_get_team, ":dead_agent_team", ":dead_agent_no"),
      (else_try),
        (assign, ":dead_agent_team", -1),
      (try_end),
      
      #adjusting kill counts of players/bots
      (try_begin), 
        (try_begin), 
          (ge, ":killer_agent_no", 0),
          (ge, ":dead_agent_no", 0),
          (agent_is_human, ":killer_agent_no"),
          (agent_is_human, ":dead_agent_no"),
          (neq, ":killer_agent_no", ":dead_agent_no"),
          
          (this_or_next|neq, ":killer_agent_team", ":dead_agent_team"),
          (this_or_next|eq, "$g_multiplayer_game_type", multiplayer_game_type_deathmatch),
          (eq, "$g_multiplayer_game_type", multiplayer_game_type_duel),
          
          (agent_get_player_id, ":killer_agent_player", ":killer_agent_no"),
          (try_begin),
            (agent_is_non_player, ":killer_agent_no"), #if killer agent is bot then increase bot kill counts of killer agent's team by one.
            (agent_get_team, ":killer_agent_team", ":killer_agent_no"),
            (team_get_bot_kill_count, ":killer_agent_team_bot_kill_count", ":killer_agent_team"),
            (val_add, ":killer_agent_team_bot_kill_count", 1),
            (team_set_bot_kill_count, ":killer_agent_team", ":killer_agent_team_bot_kill_count"),            
          (else_try), #if killer agent is not bot then increase kill counts of killer agent's player by one.
            (player_is_active, ":killer_agent_player"),
            (player_get_kill_count, ":killer_agent_player_kill_count", ":killer_agent_player"),
            (val_add, ":killer_agent_player_kill_count", 1),
            (player_set_kill_count, ":killer_agent_player", ":killer_agent_player_kill_count"),
          (try_end),
        (try_end),           

        (try_begin), 
          (ge, ":dead_agent_no", 0),
          (agent_is_human, ":dead_agent_no"),
          (try_begin),
            (agent_is_non_player, ":dead_agent_no"), #if dead agent is bot then increase bot kill counts of dead agent's team by one.
            (agent_get_team, ":dead_agent_team", ":dead_agent_no"),
            (team_get_bot_death_count, ":dead_agent_team_bot_death_count", ":dead_agent_team"),
            (val_add, ":dead_agent_team_bot_death_count", 1),
            (team_set_bot_death_count, ":dead_agent_team", ":dead_agent_team_bot_death_count"),
          (else_try), #if dead agent is not bot then increase death counts of dead agent's player by one.
            (agent_get_player_id, ":dead_agent_player", ":dead_agent_no"),
            (player_is_active, ":dead_agent_player"),
            (player_get_death_count, ":dead_agent_player_death_count", ":dead_agent_player"),
            (val_add, ":dead_agent_player_death_count", 1),
            (player_set_death_count, ":dead_agent_player", ":dead_agent_player_death_count"),
          (try_end),

          (try_begin),
            (assign, ":continue", 0),
      
            (try_begin),
              (this_or_next|lt, ":killer_agent_no", 0), #if he killed himself (1a(team change) or 1b(self kill)) then decrease kill counts of killer player by one.
              (eq, ":killer_agent_no", ":dead_agent_no"),
              (assign, ":continue", 1),
            (try_end),

            (try_begin),
              (eq, ":killer_agent_team", ":dead_agent_team"), #if he killed a teammate and game mod is not deathmatch then decrease kill counts of killer player by one.
              (neq, "$g_multiplayer_game_type", multiplayer_game_type_deathmatch),
              (neq, "$g_multiplayer_game_type", multiplayer_game_type_duel),
              (assign, ":continue", 1),
            (try_end),

            (eq, ":continue", 1),
                    
            (try_begin),
              (ge, ":killer_agent_no", 0),
              (assign, ":responsible_agent", ":killer_agent_no"),                
            (else_try),
              (assign, ":responsible_agent", ":dead_agent_no"),
            (try_end),

            (try_begin),
              (ge, ":responsible_agent", 0),
              (neg|agent_is_non_player, ":responsible_agent"),
              (agent_get_player_id, ":responsible_player", ":responsible_agent"),
              (ge, ":responsible_player", 0),
              (player_get_kill_count, ":dead_agent_player_kill_count", ":responsible_player"),
              (val_add, ":dead_agent_player_kill_count", -1),
              (player_set_kill_count, ":responsible_player", ":dead_agent_player_kill_count"),
            (try_end),
          (try_end),               
        (try_end),
      (try_end),
    ]),

  #script_warn_player_about_auto_team_balance
  # INPUT: none
  # OUTPUT: none
  ("warn_player_about_auto_team_balance",
   [
     (assign, "$g_multiplayer_message_type", multiplayer_message_type_auto_team_balance_next),
     (start_presentation, "prsnt_multiplayer_message_2"),
     ]),

  #script_check_team_balance
  # INPUT: none
  # OUTPUT: none
  ("check_team_balance",
   [
     (try_begin),
       (multiplayer_is_server),
  
       (assign, ":number_of_players_at_team_1", 0),
       (assign, ":number_of_players_at_team_2", 0),
       (get_max_players, ":num_players"),
       (try_for_range, ":cur_player", 0, ":num_players"),
         (player_is_active, ":cur_player"),
         (player_get_team_no, ":player_team", ":cur_player"),
         (try_begin),
           (eq, ":player_team", 0),
           (val_add, ":number_of_players_at_team_1", 1),
         (else_try),
           (eq, ":player_team", 1),
           (val_add, ":number_of_players_at_team_2", 1),
         (try_end),         
       (try_end),
 
       (store_sub, ":difference_of_number_of_players", ":number_of_players_at_team_1", ":number_of_players_at_team_2"),
       (assign, ":number_of_players_will_be_moved", 0),
       (try_begin),
         (try_begin),
           (store_mul, ":checked_value", "$g_multiplayer_auto_team_balance_limit", -1),
           (le, ":difference_of_number_of_players", ":checked_value"),
           (store_div, ":number_of_players_will_be_moved", ":difference_of_number_of_players", -2),
           (assign, ":team_with_more_players", 1),
           (assign, ":team_with_less_players", 0),
         (else_try),
           (ge, ":difference_of_number_of_players", "$g_multiplayer_auto_team_balance_limit"),
           (store_div, ":number_of_players_will_be_moved", ":difference_of_number_of_players", 2),
           (assign, ":team_with_more_players", 0),
           (assign, ":team_with_less_players", 1),
         (try_end),          
       (try_end),         
       #team balance checks are done
       (try_begin),
         (gt, ":number_of_players_will_be_moved", 0),
         (try_begin),
           (eq, "$g_team_balance_next_round", 1), #if warning is given
           
           #auto team balance starts
           (try_for_range, ":unused", 0, ":number_of_players_will_be_moved"), 
             (assign, ":max_player_join_time", 0),
             (assign, ":latest_joined_player_no", -1),
             (get_max_players, ":num_players"),                               
             (try_for_range, ":player_no", 0, ":num_players"),
               (player_is_active, ":player_no"),
               (player_get_team_no, ":player_team", ":player_no"),
               (eq, ":player_team", ":team_with_more_players"),
               (player_get_slot, ":player_join_time", ":player_no", slot_player_join_time),
               (try_begin),
                 (gt, ":player_join_time", ":max_player_join_time"),
                 (assign, ":max_player_join_time", ":player_join_time"),
                 (assign, ":latest_joined_player_no", ":player_no"),
               (try_end),
             (try_end),
             (try_begin),
               (ge, ":latest_joined_player_no", 0),
               (try_begin),
                 #if player is living add +1 to his kill count because he will get -1 because of team change while living.
                 (player_get_agent_id, ":latest_joined_agent_id", ":latest_joined_player_no"), 
                 (ge, ":latest_joined_agent_id", 0),
                 (agent_is_alive, ":latest_joined_agent_id"),

                 (player_get_kill_count, ":player_kill_count", ":latest_joined_player_no"), #adding 1 to his kill count, because he will lose 1 undeserved kill count for dying during team change
                 (val_add, ":player_kill_count", 1),
                 (player_set_kill_count, ":latest_joined_player_no", ":player_kill_count"),

                 (player_get_death_count, ":player_death_count", ":latest_joined_player_no"), #subtracting 1 to his death count, because he will gain 1 undeserved death count for dying during team change
                 (val_sub, ":player_death_count", 1),
                 (player_set_death_count, ":latest_joined_player_no", ":player_death_count"),

                 (player_get_score, ":player_score", ":latest_joined_player_no"), #adding 1 to his score count, because he will lose 1 undeserved score for dying during team change
                 (val_add, ":player_score", 1),
                 (player_set_score, ":latest_joined_player_no", ":player_score"),

                 (try_for_range, ":player_no", 1, ":num_players"), #0 is server so starting from 1
                   (player_is_active, ":player_no"),
                   (multiplayer_send_4_int_to_player, ":player_no", multiplayer_event_set_player_score_kill_death, ":latest_joined_player_no", ":player_score", ":player_kill_count", ":player_death_count"),
                 (try_end),

                 (player_get_value_of_original_items, ":old_items_value", ":latest_joined_player_no"),
                 (player_get_gold, ":player_gold", ":latest_joined_player_no"),
                 (val_add, ":player_gold", ":old_items_value"),
                 (player_set_gold, ":latest_joined_player_no", ":player_gold", multi_max_gold_that_can_be_stored),
               (end_try),

               (player_set_troop_id, ":latest_joined_player_no", -1),
               (player_set_team_no, ":latest_joined_player_no", ":team_with_less_players"),
               (multiplayer_send_message_to_player, ":latest_joined_player_no", multiplayer_event_force_start_team_selection),
             (try_end),
           (try_end),
     
           #for only server itself-----------------------------------------------------------------------------------------------
           (call_script, "script_show_multiplayer_message", multiplayer_message_type_auto_team_balance_done, 0), #0 is useless here
           #for only server itself-----------------------------------------------------------------------------------------------     
           (get_max_players, ":num_players"),                               
           (try_for_range, ":player_no", 1, ":num_players"),
             (player_is_active, ":player_no"),
             (multiplayer_send_int_to_player, ":player_no", multiplayer_event_show_multiplayer_message, multiplayer_message_type_auto_team_balance_done), 
           (try_end),
           (assign, "$g_team_balance_next_round", 0),
           #auto team balance done
         (else_try),
           #tutorial message (next round there will be auto team balance)
           (assign, "$g_team_balance_next_round", 1),
     
           #for only server itself-----------------------------------------------------------------------------------------------
           (call_script, "script_show_multiplayer_message", multiplayer_message_type_auto_team_balance_next, 0), #0 is useless here
           #for only server itself-----------------------------------------------------------------------------------------------     
           (get_max_players, ":num_players"),                               
           (try_for_range, ":player_no", 1, ":num_players"),
             (player_is_active, ":player_no"),
             (multiplayer_send_int_to_player, ":player_no", multiplayer_event_show_multiplayer_message, multiplayer_message_type_auto_team_balance_next), 
           (try_end),
         (try_end),
       (else_try),
         (assign, "$g_team_balance_next_round", 0),
       (try_end),
     (try_end),
   ]),

  #script_check_creating_ladder_dust_effect
  # INPUT: arg1 = instance_id, arg2 = remaining_time
  # OUTPUT: none
  ("check_creating_ladder_dust_effect",
   [
      (store_trigger_param_1, ":instance_id"),
      (store_trigger_param_2, ":remaining_time"),

      (try_begin),
        (lt, ":remaining_time", 15), #less then 0.15 seconds
        (gt, ":remaining_time", 3), #more than 0.03 seconds
      
        (scene_prop_get_slot, ":smoke_effect_done", ":instance_id", scene_prop_smoke_effect_done),
        (scene_prop_get_slot, ":opened_or_closed", ":instance_id", scene_prop_open_or_close_slot),

        (try_begin),
          (eq, ":smoke_effect_done", 0),
          (eq, ":opened_or_closed", 0),
      
          (prop_instance_get_position, pos0, ":instance_id"),

          (assign, ":smallest_dist", -1),
          (try_for_range, ":entry_point_no", multi_entry_points_for_usable_items_start, multi_entry_points_for_usable_items_end),
            (entry_point_get_position, pos1, ":entry_point_no"),
            (get_sq_distance_between_positions, ":dist", pos0, pos1),
            (this_or_next|eq, ":smallest_dist", -1),
            (lt, ":dist", ":smallest_dist"),
            (assign, ":smallest_dist", ":dist"),
            (assign, ":nearest_entry_point", ":entry_point_no"),
          (try_end),

          (try_begin),
            (set_fixed_point_multiplier, 100),

            (ge, ":smallest_dist", 0),
            (lt, ":smallest_dist", 22500), #max 15m distance
      
            (entry_point_get_position, pos1, ":nearest_entry_point"),
            (position_rotate_x, pos1, -90),

            (prop_instance_get_scene_prop_kind, ":scene_prop_kind", ":instance_id"),
            (try_begin),
              (eq, ":scene_prop_kind", "spr_siege_ladder_move_6m"),              
              (init_position, pos2),
              (position_set_z, pos2, 300),
              (position_transform_position_to_parent, pos3, pos1, pos2),
              (particle_system_burst, "psys_ladder_dust_6m", pos3, 100),
              (particle_system_burst, "psys_ladder_straw_6m", pos3, 100),
            (else_try),
              (eq, ":scene_prop_kind", "spr_siege_ladder_move_8m"),
              (init_position, pos2),
              (position_set_z, pos2, 400),
              (position_transform_position_to_parent, pos3, pos1, pos2),
              (particle_system_burst, "psys_ladder_dust_8m", pos3, 100),
              (particle_system_burst, "psys_ladder_straw_8m", pos3, 100),
            (else_try),
              (eq, ":scene_prop_kind", "spr_siege_ladder_move_10m"),
              (init_position, pos2),
              (position_set_z, pos2, 500),
              (position_transform_position_to_parent, pos3, pos1, pos2),
              (particle_system_burst, "psys_ladder_dust_10m", pos3, 100),
              (particle_system_burst, "psys_ladder_straw_10m", pos3, 100),
            (else_try),
              (eq, ":scene_prop_kind", "spr_siege_ladder_move_12m"),
              (init_position, pos2),
              (position_set_z, pos2, 600),
              (position_transform_position_to_parent, pos3, pos1, pos2),
              (particle_system_burst, "psys_ladder_dust_12m", pos3, 100),
              (particle_system_burst, "psys_ladder_straw_12m", pos3, 100),
            (else_try),
              (eq, ":scene_prop_kind", "spr_siege_ladder_move_14m"),
              (init_position, pos2),
              (position_set_z, pos2, 700),
              (position_transform_position_to_parent, pos3, pos1, pos2),
              (particle_system_burst, "psys_ladder_dust_14m", pos3, 100),
              (particle_system_burst, "psys_ladder_straw_14m", pos3, 100),
            (try_end),

            (scene_prop_set_slot, ":instance_id", scene_prop_smoke_effect_done, 1),
          (try_end),
        (try_end),
      (try_end),
      ]),

  #script_money_management_after_agent_death
  # INPUT: arg1 = killer_agent_no, arg2 = dead_agent_no
  # OUTPUT: none
  ("money_management_after_agent_death",
   [
     (store_script_param, ":killer_agent_no", 1),
     (store_script_param, ":dead_agent_no", 2),

     (assign, ":dead_agent_player_id", -1),

     (try_begin),
       (multiplayer_is_server),
       (ge, ":killer_agent_no", 0),
       (ge, ":dead_agent_no", 0),
       (agent_is_human, ":dead_agent_no"), #if dead agent is not horse
       (agent_is_human, ":killer_agent_no"), #if killer agent is not horse
       (agent_get_team, ":killer_agent_team", ":killer_agent_no"),
       (agent_get_team, ":dead_agent_team", ":dead_agent_no"),
     
       (this_or_next|eq, "$g_multiplayer_game_type", multiplayer_game_type_deathmatch),
       (this_or_next|eq, "$g_multiplayer_game_type", multiplayer_game_type_duel),
       (neq, ":killer_agent_team", ":dead_agent_team"), #if these agents are enemies

       (neq, ":dead_agent_no", ":killer_agent_no"), #if agents are different, do not remove it is needed because in deathmatch mod, self killing passes here because of this or next.
     
       (try_begin),
         (neg|agent_is_non_player, ":dead_agent_no"), 
         (agent_get_player_id, ":dead_player_no", ":dead_agent_no"),
         (player_get_slot, ":dead_agent_equipment_value", ":dead_player_no", slot_player_total_equipment_value),             
       (else_try),
         (assign, ":dead_agent_equipment_value", 0),
       (try_end),

       (assign, ":dead_agent_team_human_players_count", 0),
       (get_max_players, ":num_players"),
       (try_for_range, ":player_no", 0, ":num_players"),
         (player_is_active, ":player_no"),
         (player_get_team_no, ":player_team", ":player_no"),
         (eq, ":player_team", ":dead_agent_team"),
         (val_add, ":dead_agent_team_human_players_count", 1),
       (try_end),
         
       (try_for_range, ":player_no", 0, ":num_players"),
         (player_is_active, ":player_no"),
          
         (try_begin), 
           (this_or_next|eq, "$g_multiplayer_game_type", multiplayer_game_type_battle),
           (eq, "$g_multiplayer_game_type", multiplayer_game_type_destroy),
           (assign, ":one_spawn_per_round_game_type", 1),            
         (else_try),
           (assign, ":one_spawn_per_round_game_type", 0),
         (try_end),
         
         (this_or_next|eq, ":one_spawn_per_round_game_type", 0),
         (this_or_next|player_slot_eq, ":player_no", slot_player_spawned_this_round, 0),
         (player_slot_eq, ":player_no", slot_player_spawned_this_round, 1),
         
         (player_get_agent_id, ":agent_no", ":player_no"),
         (try_begin),
           (eq, ":agent_no", ":dead_agent_no"), #if this agent is dead agent then get share from total loot. (20% of total equipment value)                 
           (player_get_gold, ":player_gold", ":player_no"),

           (assign, ":dead_agent_player_id", ":player_no"),
          
           #dead agent loot share (32%-48%-64%, norm : 48%)
           (store_mul, ":share_of_dead_agent", ":dead_agent_equipment_value", multi_dead_agent_loot_percentage_share),
           (val_div, ":share_of_dead_agent", 100),
           (val_mul, ":share_of_dead_agent", "$g_multiplayer_battle_earnings_multiplier"),
           (val_div, ":share_of_dead_agent", 100),
           (try_begin),
             (this_or_next|eq, "$g_multiplayer_game_type", multiplayer_game_type_deathmatch), #(4/3x) share if current mod is deathmatch
             (this_or_next|eq, "$g_multiplayer_game_type", multiplayer_game_type_duel), #(4/3x) share if current mod is duel
             (this_or_next|eq, "$g_multiplayer_game_type", multiplayer_game_type_team_deathmatch), #(4/3x) share if current mod is team_deathmatch
             (this_or_next|eq, "$g_multiplayer_game_type", multiplayer_game_type_capture_the_flag), #(4/3x) share if current mod is capture the flag
             (eq, "$g_multiplayer_game_type", multiplayer_game_type_headquarters), #(4/3x) share if current mod is headquarters
             (val_mul, ":share_of_dead_agent", 4),
             (val_div, ":share_of_dead_agent", 3),
             (val_add, ":player_gold", ":share_of_dead_agent"), 
           (else_try),
             (this_or_next|eq, "$g_multiplayer_game_type", multiplayer_game_type_battle), #(2/3x) share if current mod is battle 
             (eq, "$g_multiplayer_game_type", multiplayer_game_type_destroy), #(2/3x) share if current mod is fight and destroy
             (val_mul, ":share_of_dead_agent", 2),
             (val_div, ":share_of_dead_agent", 3),
             (val_add, ":player_gold", ":share_of_dead_agent"),
           (else_try),
             (val_add, ":player_gold", ":share_of_dead_agent"), #(3/3x) share if current mod is siege
           (try_end),
           (player_set_gold, ":player_no", ":player_gold", multi_max_gold_that_can_be_stored),
         (else_try),
           (eq, ":agent_no", ":killer_agent_no"), #if this agent is killer agent then get share from total loot. (10% of total equipment value)
           (player_get_gold, ":player_gold", ":player_no"),           

           #killer agent standart money (100-150-200, norm : 150)
           (assign, ":killer_agent_standard_money_addition", multi_killer_agent_standard_money_add),
           (val_mul, ":killer_agent_standard_money_addition", "$g_multiplayer_battle_earnings_multiplier"),
           (val_div, ":killer_agent_standard_money_addition", 100),
           (try_begin),
             (this_or_next|eq, "$g_multiplayer_game_type", multiplayer_game_type_deathmatch), #(4/3x) share if current mod is deathmatch
             (this_or_next|eq, "$g_multiplayer_game_type", multiplayer_game_type_duel), #(4/3x) share if current mod is duel
             (this_or_next|eq, "$g_multiplayer_game_type", multiplayer_game_type_team_deathmatch), #(4/3x) share if current mod is team_deathmatch
             (this_or_next|eq, "$g_multiplayer_game_type", multiplayer_game_type_capture_the_flag), #(4/3x) share if current mod is capture the flag
             (eq, "$g_multiplayer_game_type", multiplayer_game_type_headquarters), #(4/3x) share if current mod is headquarters
             (val_mul, ":killer_agent_standard_money_addition", 4),
             (val_div, ":killer_agent_standard_money_addition", 3),
             (val_add, ":player_gold", ":killer_agent_standard_money_addition"), 
           (else_try),
             (this_or_next|eq, "$g_multiplayer_game_type", multiplayer_game_type_battle), #(2/3x) share if current mod is battle 
             (eq, "$g_multiplayer_game_type", multiplayer_game_type_destroy), #(2/3x) share if current mod is fight and destroy
             (val_mul, ":killer_agent_standard_money_addition", 2),
             (val_div, ":killer_agent_standard_money_addition", 3),
             (val_add, ":player_gold", ":killer_agent_standard_money_addition"),
           (else_try),
             (val_add, ":player_gold", ":killer_agent_standard_money_addition"), #(3/3x) share if current mod is siege
           (try_end),

           #killer agent loot share (8%-12%-16%, norm : 12%)
           (store_mul, ":share_of_killer_agent", ":dead_agent_equipment_value", multi_killer_agent_loot_percentage_share),
           (val_div, ":share_of_killer_agent", 100),
           (val_mul, ":share_of_killer_agent", "$g_multiplayer_battle_earnings_multiplier"),
           (val_div, ":share_of_killer_agent", 100),
           (try_begin),
             (this_or_next|eq, "$g_multiplayer_game_type", multiplayer_game_type_deathmatch), #(4/3x) share if current mod is deathmatch
             (this_or_next|eq, "$g_multiplayer_game_type", multiplayer_game_type_duel), #(4/3x) share if current mod is duel
             (this_or_next|eq, "$g_multiplayer_game_type", multiplayer_game_type_team_deathmatch), #(4/3x) share if current mod is team_deathmatch
             (this_or_next|eq, "$g_multiplayer_game_type", multiplayer_game_type_capture_the_flag), #(4/3x) share if current mod is capture the flag
             (eq, "$g_multiplayer_game_type", multiplayer_game_type_headquarters), #(4/3x) share if current mod is headquarters
             (val_mul, ":share_of_killer_agent", 4),
             (val_div, ":share_of_killer_agent", 3),
             (val_add, ":player_gold", ":share_of_killer_agent"), 
           (else_try),
             (this_or_next|eq, "$g_multiplayer_game_type", multiplayer_game_type_battle), #(2/3x) share if current mod is battle 
             (eq, "$g_multiplayer_game_type", multiplayer_game_type_destroy), #(2/3x) share if current mod is fight and destroy
             (val_mul, ":share_of_killer_agent", 2),
             (val_div, ":share_of_killer_agent", 3),
             (val_add, ":player_gold", ":share_of_killer_agent"),
           (else_try),
             (val_add, ":player_gold", ":share_of_killer_agent"), #(3/3x) share if current mod is siege
           (try_end),
           (player_set_gold, ":player_no", ":player_gold", multi_max_gold_that_can_be_stored),
         (try_end),
       (try_end),
     (try_end),

     #(below lines added new at 25.11.09 after Armagan decided new money system)
     (try_begin),
       (multiplayer_is_server),
       (neq, "$g_multiplayer_game_type", multiplayer_game_type_battle),
       (neq, "$g_multiplayer_game_type", multiplayer_game_type_destroy),

       (ge, ":dead_agent_no", 0),
       (agent_is_human, ":dead_agent_no"), #if dead agent is not horse
       (agent_get_player_id, ":dead_agent_player_id", ":dead_agent_no"),
       (ge, ":dead_agent_player_id", 0),
     
       (player_get_gold, ":player_gold", ":dead_agent_player_id"),
       (try_begin),
         (store_mul, ":minimum_gold", "$g_multiplayer_initial_gold_multiplier", 10),
         (lt, ":player_gold", ":minimum_gold"),
         (assign, ":player_gold", ":minimum_gold"),
       (try_end),
       (player_set_gold, ":dead_agent_player_id", ":player_gold"),
     (try_end),
     #new money system addition end          
     ]),

	("initialize_aristocracy",
	[
	  #LORD OCCUPATIONS, BLOOD RELATIONSHIPS, RENOWN AND REPUTATIONS
	  
	  #King ages
	  (try_for_range, ":cur_troop", kings_begin, kings_end),
		(troop_set_slot, ":cur_troop", slot_troop_occupation, slto_kingdom_hero),
		(store_random_in_range, ":age", 50, 60),
		(troop_set_slot, ":cur_troop", slot_troop_age, ":age"),
		(eq, ":cur_troop", "trp_kingdom_5_lord"),
		(troop_set_slot, ":cur_troop", slot_troop_age, 47),	
	  (try_end),
	  	  
	  #The first thing - family structure
	  #lords 1 to 8 are patriarchs with one live-at-home son and one daughter. They come from one of six possible ancestors, thus making it likely that there will be two sets of siblings
	  #lords 9 to 12 are unmarried landowners with sisters
	  #lords 13 to 20 are sons who still live in their fathers' houses
	  #For the sake of simplicity, we can assume that all male aristocrats in prior generations either married commoners or procured their brides from the Old Country, thus discounting intermarriage 

	  (try_for_range, ":cur_troop", kingdom_ladies_begin, kingdom_ladies_end),
		(troop_set_slot, ":cur_troop", slot_troop_occupation, slto_kingdom_lady),
	  (try_end),
	  
	  (assign, ":cur_lady", "trp_kingdom_1_lady_1"),

	  (try_for_range, ":cur_troop", lords_begin, lords_end),  
	  
	    # NE test for family relations 
		(neq, ":cur_troop", "trp_dark_knight_lord"), 
		(neq, ":cur_troop", "trp_dark_knight_lord1"), 
		(neq, ":cur_troop", "trp_dark_knight_lord2"), 
		(neq, ":cur_troop", "trp_dark_knight_lord3"), 
		(neq, ":cur_troop", "trp_dark_knight_lord4"), 
		# Ne end 
	  
	  
		(troop_set_slot, ":cur_troop", slot_troop_occupation, slto_kingdom_hero),
		
		(store_random_in_range, ":father_age_at_birth", 23, 26),
#		(store_random_in_range, ":mother_age_at_birth", 19, 22),
		
		(try_begin),
			(is_between, ":cur_troop", "trp_knight_1_1", "trp_knight_2_1"),
			(store_sub, ":npc_seed", ":cur_troop", "trp_knight_1_1"),
			(assign, ":ancestor_seed", 1),

		(else_try),
			(is_between, ":cur_troop", "trp_knight_2_1", "trp_knight_3_1"),
			(store_sub, ":npc_seed", ":cur_troop", "trp_knight_2_1"),
			(assign, ":ancestor_seed", 7),
			
		(else_try),
			(is_between, ":cur_troop", "trp_knight_3_1", "trp_knight_4_1"),
			(store_sub, ":npc_seed", ":cur_troop", "trp_knight_3_1"),
			(assign, ":ancestor_seed", 13),
			
		(else_try),
			(is_between, ":cur_troop", "trp_knight_4_1", "trp_knight_5_1"),
			(store_sub, ":npc_seed", ":cur_troop", "trp_knight_4_1"),
			(assign, ":ancestor_seed", 19),

		(else_try),
			(is_between, ":cur_troop", "trp_knight_5_1", "trp_knight_6_1"),
			(store_sub, ":npc_seed", ":cur_troop", "trp_knight_5_1"),
			(assign, ":ancestor_seed", 25),
			
		(else_try),
			(is_between, ":cur_troop", "trp_knight_6_1", "trp_kingdom_1_pretender"),
			(store_sub, ":npc_seed", ":cur_troop", "trp_knight_6_1"),
			(assign, ":ancestor_seed", 31),
			
		(try_end),
		
		
		(try_begin),
			(lt, ":npc_seed", 8), #NPC seed is the order in the faction
			(assign, ":reputation", ":npc_seed"),
			(store_random_in_range, ":age", 45, 64),
			
			(store_random_in_range, ":father", 0, 6), #six possible fathers
			(val_add, ":father", ":ancestor_seed"),
			(troop_set_slot, ":cur_troop", slot_troop_father, ":father"),
			
			#wife
			(troop_set_slot, ":cur_troop", slot_troop_spouse, ":cur_lady"),
			(troop_set_slot, ":cur_lady", slot_troop_spouse, ":cur_troop"),
			(store_random_in_range, ":wife_reputation", 20, 26),
			(try_begin),
				(eq, ":wife_reputation", 20),
				(assign, ":wife_reputation", lrep_conventional),
			(try_end),
			(troop_set_slot, ":cur_lady", slot_lord_reputation_type, ":wife_reputation"),
			
			
			(call_script, "script_init_troop_age", ":cur_lady", 49),
			(call_script, "script_add_lady_items", ":cur_lady"),
			
			(val_add, ":cur_lady", 1),

			#daughter
			(troop_set_slot, ":cur_lady", slot_troop_father, ":cur_troop"),
			(store_sub, ":mother", ":cur_lady", 1),
			(call_script, "script_init_troop_age", ":cur_lady", 19),
			(troop_set_slot, ":cur_lady", slot_troop_mother, ":cur_lady"),
			(store_random_in_range, ":lady_reputation", lrep_conventional, 34), #33% chance of father-derived
			(try_begin),
				(le, ":lady_reputation", 25),
				(troop_set_slot, ":cur_lady", slot_lord_reputation_type, ":lady_reputation"),
			(else_try),	
				(eq, ":lady_reputation", 26),
				(troop_set_slot, ":cur_lady", slot_lord_reputation_type, lrep_conventional),
			(else_try),	
				(eq, ":lady_reputation", 27),
				(troop_set_slot, ":cur_lady", slot_lord_reputation_type, lrep_moralist),
			(else_try),
				(assign, ":guardian_reputation", ":reputation"),
				(try_begin),
					(this_or_next|eq, ":guardian_reputation", lrep_martial),
						(eq, ":guardian_reputation", 0),
					(troop_set_slot, ":cur_lady", slot_lord_reputation_type, lrep_conventional),
				(else_try),		
					(eq, ":guardian_reputation", lrep_quarrelsome),
					(troop_set_slot, ":cur_lady", slot_lord_reputation_type, lrep_otherworldly),
				(else_try),		
					(eq, ":guardian_reputation", lrep_selfrighteous),
					(troop_set_slot, ":cur_lady", slot_lord_reputation_type, lrep_ambitious),
				(else_try),		
					(eq, ":guardian_reputation", lrep_cunning),
					(troop_set_slot, ":cur_lady", slot_lord_reputation_type, lrep_adventurous),
				(else_try),		
					(eq, ":guardian_reputation", lrep_goodnatured),
					(troop_set_slot, ":cur_lady", slot_lord_reputation_type, lrep_adventurous),
				(else_try),		
					(eq, ":guardian_reputation", lrep_debauched),
					(troop_set_slot, ":cur_lady", slot_lord_reputation_type, lrep_ambitious),
				(else_try),		
					(eq, ":guardian_reputation", lrep_upstanding),
					(troop_set_slot, ":cur_lady", slot_lord_reputation_type, lrep_moralist),
				(try_end),
			(try_end),
			
			(call_script, "script_add_lady_items", ":cur_lady"),
			(val_add, ":cur_lady", 1),
			#high renown

		(else_try),	#Older unmarried lords
			(is_between, ":npc_seed", 8, 12),
			
			(store_random_in_range, ":age", 25, 36),			
			(store_random_in_range, ":reputation", 0, 8),			
			
			(store_random_in_range, ":sister_reputation", 20, 26),
			(try_begin),
				(eq, ":sister_reputation", 20),
				(assign, ":sister_reputation", lrep_conventional),
			(try_end),
			(troop_set_slot, ":cur_lady", slot_lord_reputation_type, ":sister_reputation"),
			
			(troop_set_slot, ":cur_lady", slot_troop_guardian, ":cur_troop"),

			(call_script, "script_init_troop_age", ":cur_lady", 21),
			(call_script, "script_add_lady_items", ":cur_lady"),
			
			(val_add, ":cur_lady", 1),
			
		(else_try),	#Younger unmarried lords 
			#age is father's minus 20 to 25
			(store_sub, ":father", ":cur_troop", 12),
			(troop_set_slot, ":cur_troop", slot_troop_father, ":father"),
			(troop_get_slot, ":mother", ":father", slot_troop_spouse),
			(troop_set_slot, ":cur_troop", slot_troop_mother, ":mother"),
			
			(troop_get_slot, ":father_age", ":father", slot_troop_age),
			(store_sub, ":age", ":father_age", ":father_age_at_birth"),

			(try_begin), #50% chance of having father's rep
				(store_random_in_range, ":reputation", 0, 16),

				(gt, ":reputation", 7),
				(troop_get_slot, ":reputation", ":father", slot_lord_reputation_type),
			(try_end),
		(try_end),
		
		(try_begin),
			(eq, ":reputation", 0),
			(assign, ":reputation", 1),
		(try_end),
		
        (troop_set_slot, ":cur_troop", slot_lord_reputation_type, ":reputation"),

		(call_script, "script_init_troop_age", ":cur_troop", ":age"),
	  (try_end),
	  
	  (try_begin),
	    (eq, "$cheat_mode", 1),
	    (assign, reg3, "$cheat_mode"),
	    (display_message, "@{!}DEBUG -- Assigned lord reputation and relations"),
		
#	    (display_message, "str_assigned_lord_reputation_and_relations_cheat_mode_reg3"), #This string can be removed
	  (try_end),
	  
	  (try_for_range, ":cur_troop", pretenders_begin, pretenders_end),
		(troop_set_slot, ":cur_troop", slot_troop_occupation, slto_inactive_pretender),
		(store_random_in_range, ":age", 25, 30),
		(troop_set_slot, ":cur_troop", slot_troop_age, ":age"),
		(eq, ":cur_troop", "trp_kingdom_5_pretender"),
		(troop_set_slot, ":cur_troop", slot_troop_age, 45),		
	  (try_end),
	]),

	  
	
	

	("initialize_trade_routes",
	[
	  #SARGOTH - 10 routes
      (call_script, "script_set_trade_route_between_centers", "p_town_1", "p_town_2"), #Sargoth - Tihr
      (call_script, "script_set_trade_route_between_centers", "p_town_1", "p_town_4"), #Sargoth - Suno
      (call_script, "script_set_trade_route_between_centers", "p_town_1", "p_town_12"), #Sargoth - Wercheg
      (call_script, "script_set_trade_route_between_centers", "p_town_1", "p_town_11"), #Sargoth - Curaw
      (call_script, "script_set_trade_route_between_centers", "p_town_1", "p_town_8"), #Sargoth - Reyvadin
      (call_script, "script_set_trade_route_between_centers", "p_town_1", "p_town_13"), #Sargoth - Rivacheg
      (call_script, "script_set_trade_route_between_centers", "p_town_1", "p_town_7"), #Sargoth - Uxkhal
      (call_script, "script_set_trade_route_between_centers", "p_town_1", "p_town_9"), #Sargoth - Khudan
      (call_script, "script_set_trade_route_between_centers", "p_town_1", "p_town_6"), #Sargoth - Praven
      (call_script, "script_set_trade_route_between_centers", "p_town_1", "p_town_15"), #Sargoth - Yalen      
      (call_script, "script_set_trade_route_between_centers", "p_town_1", "p_town_16"), #Sargoth - Dhirim
	 
	  #TIHR- 8 Routes
      (call_script, "script_set_trade_route_between_centers", "p_town_2", "p_town_4"), #Tihr- Suno
      (call_script, "script_set_trade_route_between_centers", "p_town_2", "p_town_6"), #Tihr - Praven
      (call_script, "script_set_trade_route_between_centers", "p_town_2", "p_town_7"), #Tihr - Uxkhal
      (call_script, "script_set_trade_route_between_centers", "p_town_2", "p_town_15"), #Tihr - Yalen
      (call_script, "script_set_trade_route_between_centers", "p_town_2", "p_town_12"), #Tihr - Wercheg
      (call_script, "script_set_trade_route_between_centers", "p_town_2", "p_town_8"), #Tihr - Reyvadin
      (call_script, "script_set_trade_route_between_centers", "p_town_2", "p_town_11"), #Tihr - Curaw      
      (call_script, "script_set_trade_route_between_centers", "p_town_2", "p_town_16"), #Thir - Dhirim

	  #VELUCA - 8 Routes
      (call_script, "script_set_trade_route_between_centers", "p_town_3", "p_town_7"), #Veluca- Uxkhal
      (call_script, "script_set_trade_route_between_centers", "p_town_3", "p_town_5"), #Veluca - Jelkala
      (call_script, "script_set_trade_route_between_centers", "p_town_3", "p_town_15"), #Veluca - Yalen
      (call_script, "script_set_trade_route_between_centers", "p_town_3", "p_town_16"), #Veluca - Dhirim
      (call_script, "script_set_trade_route_between_centers", "p_town_3", "p_town_14"), #Veluca - Halmar
      (call_script, "script_set_trade_route_between_centers", "p_town_3", "p_town_4"), #Veluca - Suno
      (call_script, "script_set_trade_route_between_centers", "p_town_3", "p_town_19"), #Veluca - Shariz
      (call_script, "script_set_trade_route_between_centers", "p_town_3", "p_town_6"), #Veluca - Praven

	  #SUNO - 11 routes
	  #Sargoth, Tihr, Veluca
      (call_script, "script_set_trade_route_between_centers", "p_town_4", "p_town_12"), #Suno - Wercheg
      (call_script, "script_set_trade_route_between_centers", "p_town_4", "p_town_8"), #Suno - Reyvadin
      (call_script, "script_set_trade_route_between_centers", "p_town_4", "p_town_11"), #Suno - Curaw
      (call_script, "script_set_trade_route_between_centers", "p_town_4", "p_town_6"), #Suno - Praven
      (call_script, "script_set_trade_route_between_centers", "p_town_4", "p_town_7"), #Suno - Uxkhal
      (call_script, "script_set_trade_route_between_centers", "p_town_4", "p_town_16"), #Suno - Dhirim
      (call_script, "script_set_trade_route_between_centers", "p_town_4", "p_town_5"), #Suno - Jelkala
      (call_script, "script_set_trade_route_between_centers", "p_town_4", "p_town_15"), #Suno - Yalen

	  #JELKALA - 6 ROUTES
      #Veluca, Suno
      (call_script, "script_set_trade_route_between_centers", "p_town_5", "p_town_15"), #Jelkala - Yalen
      (call_script, "script_set_trade_route_between_centers", "p_town_5", "p_town_6"), #Jelkala - Praven
      (call_script, "script_set_trade_route_between_centers", "p_town_5", "p_town_7"), #Jelkala - Uxkhal
      (call_script, "script_set_trade_route_between_centers", "p_town_5", "p_town_19"), #Jelkala - Shariz
	  
	  #PRAVEN - 7 ROUTES
	  #Tihr, Veluca, Suno, Jelkala
      (call_script, "script_set_trade_route_between_centers", "p_town_6", "p_town_7"), #Praven - Uxkhal
      (call_script, "script_set_trade_route_between_centers", "p_town_6", "p_town_15"), #Praven - Yalen
      (call_script, "script_set_trade_route_between_centers", "p_town_6", "p_town_16"), #Praven - Dhirim

	  #UXKHAL - 9 Routes
	  #Sargoth, Tihr, Suno, Jelkala, Praven 
      (call_script, "script_set_trade_route_between_centers", "p_town_7", "p_town_15"), #Yalen
      (call_script, "script_set_trade_route_between_centers", "p_town_7", "p_town_16"), #Dhirim
      (call_script, "script_set_trade_route_between_centers", "p_town_7", "p_town_19"), #Shariz
      (call_script, "script_set_trade_route_between_centers", "p_town_7", "p_town_14"), #Halmar

	  #REYVADIN - 9 Routes
	  #Suno, Sargoth
      (call_script, "script_set_trade_route_between_centers", "p_town_8", "p_town_9"), #Khudan 
      (call_script, "script_set_trade_route_between_centers", "p_town_8", "p_town_11"), #Curaw
      (call_script, "script_set_trade_route_between_centers", "p_town_8", "p_town_12"), #Wercheg
      (call_script, "script_set_trade_route_between_centers", "p_town_8", "p_town_13"), #Rivacheg
      (call_script, "script_set_trade_route_between_centers", "p_town_8", "p_town_16"), #Dhirim
      (call_script, "script_set_trade_route_between_centers", "p_town_8", "p_town_18"), #Narra
      (call_script, "script_set_trade_route_between_centers", "p_town_8", "p_town_17"), #Ichamur

	  #KHUDAN - 9 Routes
	  #Sargoth, Reyvadin
      (call_script, "script_set_trade_route_between_centers", "p_town_9", "p_town_11"), #Curaw
      (call_script, "script_set_trade_route_between_centers", "p_town_9", "p_town_13"), #Rivacheg
      (call_script, "script_set_trade_route_between_centers", "p_town_9", "p_town_12"), #Wercheg
      (call_script, "script_set_trade_route_between_centers", "p_town_9", "p_town_17"), #Ichamur
      (call_script, "script_set_trade_route_between_centers", "p_town_9", "p_town_10"), #Tulga
      (call_script, "script_set_trade_route_between_centers", "p_town_9", "p_town_16"), #Dhirim
      (call_script, "script_set_trade_route_between_centers", "p_town_9", "p_town_18"), #Narra

	  #TULGA - 7 Routes
	  #Khudan
      (call_script, "script_set_trade_route_between_centers", "p_town_10", "p_town_17"), #Ichamur
      (call_script, "script_set_trade_route_between_centers", "p_town_10", "p_town_18"), #Narra
      (call_script, "script_set_trade_route_between_centers", "p_town_10", "p_town_22"), #Bariyye
      (call_script, "script_set_trade_route_between_centers", "p_town_10", "p_town_21"), #Ahmerrad
      (call_script, "script_set_trade_route_between_centers", "p_town_10", "p_town_14"), #Halmar
      (call_script, "script_set_trade_route_between_centers", "p_town_10", "p_town_20"), #Durquba

	  #CURAW - 9 Routes
	  #Khudan, Reyvadin, Sargoth, Suno
      (call_script, "script_set_trade_route_between_centers", "p_town_11", "p_town_12"), #Wercheg
      (call_script, "script_set_trade_route_between_centers", "p_town_11", "p_town_13"), #Rivacheg
      (call_script, "script_set_trade_route_between_centers", "p_town_11", "p_town_14"), #Halmar
      (call_script, "script_set_trade_route_between_centers", "p_town_11", "p_town_16"), #Dhirim
      (call_script, "script_set_trade_route_between_centers", "p_town_11", "p_town_17"), #Ichamur
      
	  #WERCHEG - 7 Routes
	  #Sargoth, Suno, Reyvadin, Khudan, Curaw, Tihr
      (call_script, "script_set_trade_route_between_centers", "p_town_12", "p_town_13"), #Rivacheg
	  
	  #RIVACHEG - 6 Routes
	  #Sargoth, Reyvadin, Khudan, Curaw, Wercheg
      (call_script, "script_set_trade_route_between_centers", "p_town_13", "p_town_17"), #Ichamur

	  #HALMAR- 11 Routes 
	  #Veluca, Uxkhal, Tulga, Curaw
      (call_script, "script_set_trade_route_between_centers", "p_town_14", "p_town_17"), #Ichamur
      (call_script, "script_set_trade_route_between_centers", "p_town_14", "p_town_18"), #Narra
      (call_script, "script_set_trade_route_between_centers", "p_town_14", "p_town_21"), #Ahmerrad
      (call_script, "script_set_trade_route_between_centers", "p_town_14", "p_town_22"), #Bariyye
      (call_script, "script_set_trade_route_between_centers", "p_town_14", "p_town_20"), #Durquba
      (call_script, "script_set_trade_route_between_centers", "p_town_14", "p_town_19"), #Shariz
      (call_script, "script_set_trade_route_between_centers", "p_town_14", "p_town_16"), #Dhirim

	  #YALEN - 7 Routes
	  #Sargoth, Tihr, Veluca, Suno, Jelkala, Praven, Uxkhal
	  
	  #DHIRIM - 13 Routes
	  #Sargoth, Thir, Veluca, Suno, Praven, Uxkhal, Reyvadin, Khudan, Curaw, Halmar
      (call_script, "script_set_trade_route_between_centers", "p_town_16", "p_town_18"), #Narra
      (call_script, "script_set_trade_route_between_centers", "p_town_16", "p_town_20"), #Durquba
      (call_script, "script_set_trade_route_between_centers", "p_town_16", "p_town_19"), #Shariz
	  
	  #ICHAMUR - 7 Routes
      #Reyvadin, Khudan, Tulga, Curaw, Rivacheg, Halmar
      (call_script, "script_set_trade_route_between_centers", "p_town_17", "p_town_18"), #Narra

	  #NARRA - 9 Routes
      #Reyvadin, Khudan, Tulga, Halmar, Dhirim, Ichamur
      (call_script, "script_set_trade_route_between_centers", "p_town_18", "p_town_20"), #Durquba
      (call_script, "script_set_trade_route_between_centers", "p_town_18", "p_town_21"), #Ahmerrad
      (call_script, "script_set_trade_route_between_centers", "p_town_18", "p_town_22"), #Bariyye
	  
	  #SHARIZ - 8 Routes
      #Veluca, Jelkala, Uxkhal, Halmar, Dhirim
      (call_script, "script_set_trade_route_between_centers", "p_town_19", "p_town_20"), #Durquba
      (call_script, "script_set_trade_route_between_centers", "p_town_19", "p_town_21"), #Ahmerrad
      (call_script, "script_set_trade_route_between_centers", "p_town_19", "p_town_22"), #Bariyye
	  
	  #DURQUBA - 7 Routes
      #Tulga, Halmar, Dhirim, Narra, Shariz
      (call_script, "script_set_trade_route_between_centers", "p_town_20", "p_town_21"), #Ahmerrad
      (call_script, "script_set_trade_route_between_centers", "p_town_20", "p_town_22"), #Bariyye

	  #AHMERRAD - 6 Routes
      #Tulga, Halmar, Narra, Shariz, Durquba
      (call_script, "script_set_trade_route_between_centers", "p_town_21", "p_town_22"), #Bariyye

	  #BARIYYE - 6 Routes
      #Tulga, Halmar, Narra, Shariz, Durquba, Ahmerrad
	]),
	
	
	 
    ("initialize_faction_troop_types",
    [

      (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_swadian_deserter"),
          (faction_set_slot, ":faction_no",  slot_faction_guard_troop, "trp_swadian_sergeant"),
          (faction_set_slot, ":faction_no",  slot_faction_messenger_troop, "trp_swadian_messenger"),
          (faction_set_slot, ":faction_no",  slot_faction_prison_guard_troop, "trp_swadian_prison_guard"),
          (faction_set_slot, ":faction_no",  slot_faction_castle_guard_troop, "trp_swadian_castle_guard"),
          (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_vaegir_deserter"),
          (faction_set_slot, ":faction_no", slot_faction_guard_troop, "trp_vaegir_varangian_guard"),
          (faction_set_slot, ":faction_no", slot_faction_messenger_troop, "trp_vaegir_messenger"),
          (faction_set_slot, ":faction_no", slot_faction_prison_guard_troop, "trp_vaegir_prison_guard"),
          (faction_set_slot, ":faction_no", slot_faction_castle_guard_troop, "trp_vaegir_castle_guard"),
          (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_khergit_deserter"),
          (faction_set_slot, ":faction_no", slot_faction_guard_troop, "trp_khergit_rider"),
          (faction_set_slot, ":faction_no", slot_faction_messenger_troop, "trp_khergit_messenger"),
          (faction_set_slot, ":faction_no", slot_faction_prison_guard_troop, "trp_khergit_prison_guard"),
          (faction_set_slot, ":faction_no", slot_faction_castle_guard_troop, "trp_khergit_castle_guard"),
          (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"),
        (else_try),
          (faction_slot_eq, ":faction_no", slot_faction_culture, "fac_culture_6"),
      
          (faction_set_slot, ":faction_no", slot_faction_deserter_troop, "trp_sarranid_deserter"),
          (faction_set_slot, ":faction_no", slot_faction_guard_troop, "trp_sarranid_castle_guard"),
          (faction_set_slot, ":faction_no", slot_faction_messenger_troop, "trp_sarranid_messenger"),
          (faction_set_slot, ":faction_no", slot_faction_prison_guard_troop, "trp_sarranid_prison_guard"),
          (faction_set_slot, ":faction_no", slot_faction_castle_guard_troop, "trp_sarranid_castle_guard"),
          (faction_set_slot, ":faction_no",  slot_faction_reinforcements_a, "pt_kingdom_6_reinforcements_a"),
          (faction_set_slot, ":faction_no",  slot_faction_reinforcements_b, "pt_kingdom_6_reinforcements_b"),
          (faction_set_slot, ":faction_no",  slot_faction_reinforcements_c, "pt_kingdom_6_reinforcements_c"),
		# NE dk
        (else_try),
          (faction_slot_eq, ":faction_no", slot_faction_culture, "fac_culture_dark_knights"),
      
          (faction_set_slot, ":faction_no", slot_faction_deserter_troop, "trp_dark_initiate"),
          (faction_set_slot, ":faction_no", slot_faction_guard_troop, "trp_dark_knight"),
          (faction_set_slot, ":faction_no", slot_faction_messenger_troop, "trp_dark_squire"),
          (faction_set_slot, ":faction_no", slot_faction_prison_guard_troop, "trp_dark_knight"),
          (faction_set_slot, ":faction_no", slot_faction_castle_guard_troop, "trp_dark_knight"),
          (faction_set_slot, ":faction_no",  slot_faction_reinforcements_a, "pt_dark_knights_reinforcements_a"),
          (faction_set_slot, ":faction_no",  slot_faction_reinforcements_b, "pt_dark_knights_reinforcements_b"),
          (faction_set_slot, ":faction_no",  slot_faction_reinforcements_c, "pt_dark_knights_reinforcements_c"),	
        # NE end dk		  
        (try_end),
      (try_end),
	]),
	 
    ("initialize_item_info",
    [	 
	  # Setting food bonuses - these have been changed to incentivize using historical rations. Bread is the most cost-efficient
	  #Staples
      (item_set_slot, "itm_bread", slot_item_food_bonus, 8), #brought up from 4
      (item_set_slot, "itm_grain", slot_item_food_bonus, 2), #new - can be boiled as porridge
	  
	  #Fat sources - preserved
      (item_set_slot, "itm_smoked_fish", slot_item_food_bonus, 4),
      (item_set_slot, "itm_dried_meat", slot_item_food_bonus, 5),
      (item_set_slot, "itm_cheese", slot_item_food_bonus, 5),
      (item_set_slot, "itm_sausages", slot_item_food_bonus, 5),
      (item_set_slot, "itm_butter", slot_item_food_bonus, 4), #brought down from 8

	  #Fat sources - perishable
      (item_set_slot, "itm_chicken", slot_item_food_bonus, 8), #brought up from 7
      (item_set_slot, "itm_cattle_meat", slot_item_food_bonus, 7), #brought down from 7
      (item_set_slot, "itm_pork", slot_item_food_bonus, 6), #brought down from 6
	  
	  #Produce
      (item_set_slot, "itm_raw_olives", slot_item_food_bonus, 1),
      (item_set_slot, "itm_cabbages", slot_item_food_bonus, 2),
      (item_set_slot, "itm_raw_grapes", slot_item_food_bonus, 3),
      (item_set_slot, "itm_apples", slot_item_food_bonus, 4), #brought down from 5

	  #Sweet items
      (item_set_slot, "itm_raw_date_fruit", slot_item_food_bonus, 4), #brought down from 8
      (item_set_slot, "itm_honey", slot_item_food_bonus, 6), #brought down from 12
      
      (item_set_slot, "itm_wine", slot_item_food_bonus, 5),
      (item_set_slot, "itm_ale", slot_item_food_bonus, 4),
	  # NE food
	  #v585 Josef whiskey
      (item_set_slot, "itm_whiskey", slot_item_food_bonus, 30),	  
	  (item_set_slot, "itm_hardtack", slot_item_food_bonus, 0), # Jinnai
	  (item_set_slot, "itm_hardtack", slot_item_base_price, 200),
	  # NE end food
	  
	  #Item economic settings	  
	  (item_set_slot, "itm_grain", slot_item_urban_demand, 20),
      (item_set_slot, "itm_grain", slot_item_rural_demand, 20),
      (item_set_slot, "itm_grain", slot_item_desert_demand, 20),
      (item_set_slot, "itm_grain", slot_item_production_slot, slot_center_acres_grain),
      (item_set_slot, "itm_grain", slot_item_production_string, "str_acres_grain"),
      (item_set_slot, "itm_grain", slot_item_base_price, 30),
	  
	  
      (item_set_slot, "itm_bread", slot_item_urban_demand, 30),
      (item_set_slot, "itm_bread", slot_item_rural_demand, 30),
      (item_set_slot, "itm_bread", slot_item_desert_demand, 30),
      (item_set_slot, "itm_bread", slot_item_production_slot, slot_center_mills),
      (item_set_slot, "itm_bread", slot_item_production_string, "str_mills"),
      (item_set_slot, "itm_bread", slot_item_primary_raw_material, "itm_grain"),
      (item_set_slot, "itm_bread", slot_item_input_number, 6),
      (item_set_slot, "itm_bread", slot_item_output_per_run, 6),
      (item_set_slot, "itm_bread", slot_item_overhead_per_run, 30),
      (item_set_slot, "itm_bread", slot_item_base_price, 50),
      (item_set_slot, "itm_bread", slot_item_enterprise_building_cost, 1500),

	  
	  (item_set_slot, "itm_ale", slot_item_urban_demand, 10),
	  (item_set_slot, "itm_ale", slot_item_rural_demand, 15),
      (item_set_slot, "itm_ale", slot_item_desert_demand, 0),
      (item_set_slot, "itm_ale", slot_item_production_slot, slot_center_breweries),
      (item_set_slot, "itm_ale", slot_item_production_string, "str_breweries"),
      (item_set_slot, "itm_ale", slot_item_base_price, 120),
      (item_set_slot, "itm_ale", slot_item_primary_raw_material, "itm_grain"),
	  (item_set_slot, "itm_ale", slot_item_input_number, 1),
      (item_set_slot, "itm_ale", slot_item_output_per_run, 2),
      (item_set_slot, "itm_ale", slot_item_overhead_per_run, 50),
      (item_set_slot, "itm_ale", slot_item_base_price, 120),
      (item_set_slot, "itm_ale", slot_item_enterprise_building_cost, 2500),
	  	  
	  (item_set_slot, "itm_wine", slot_item_urban_demand, 15),
	  (item_set_slot, "itm_wine", slot_item_rural_demand, 10),
      (item_set_slot, "itm_wine", slot_item_desert_demand, 25),
      (item_set_slot, "itm_wine", slot_item_production_slot, slot_center_wine_presses),
      (item_set_slot, "itm_wine", slot_item_production_string, "str_presses"),
      (item_set_slot, "itm_wine", slot_item_primary_raw_material, "itm_raw_grapes"),
      (item_set_slot, "itm_wine", slot_item_input_number, 4),
      (item_set_slot, "itm_wine", slot_item_output_per_run, 2),
	  (item_set_slot, "itm_wine", slot_item_overhead_per_run, 60),
      (item_set_slot, "itm_wine", slot_item_base_price, 220),
      (item_set_slot, "itm_wine", slot_item_enterprise_building_cost, 5000),

	  (item_set_slot, "itm_raw_grapes", slot_item_urban_demand, 0),
	  (item_set_slot, "itm_raw_grapes", slot_item_rural_demand, 0),
      (item_set_slot, "itm_raw_grapes", slot_item_desert_demand, 0),
      (item_set_slot, "itm_raw_grapes", slot_item_production_slot, slot_center_acres_vineyard),
      (item_set_slot, "itm_raw_grapes", slot_item_production_string, "str_acres_orchard"),
      (item_set_slot, "itm_raw_grapes", slot_item_is_raw_material_only_for, "itm_wine"),
      (item_set_slot, "itm_raw_grapes", slot_item_base_price, 75),
	
	  (item_set_slot, "itm_apples", slot_item_urban_demand, 4),
	  (item_set_slot, "itm_apples", slot_item_rural_demand, 4),
	  (item_set_slot, "itm_apples", slot_item_desert_demand, 0),
      (item_set_slot, "itm_apples", slot_item_production_slot, slot_center_acres_vineyard),
      (item_set_slot, "itm_apples", slot_item_production_string, "str_acres_orchard"),
      (item_set_slot, "itm_apples", slot_item_base_price, 44),
	  
      (item_set_slot, "itm_smoked_fish", slot_item_urban_demand, 16),
      (item_set_slot, "itm_smoked_fish", slot_item_rural_demand, 16),
      (item_set_slot, "itm_smoked_fish", slot_item_desert_demand, 16),
      (item_set_slot, "itm_smoked_fish", slot_item_production_slot, slot_center_fishing_fleet),
      (item_set_slot, "itm_smoked_fish", slot_item_production_string, "str_boats"),

      (item_set_slot, "itm_salt", slot_item_urban_demand, 5),
      (item_set_slot, "itm_salt", slot_item_rural_demand, 3),
      (item_set_slot, "itm_salt", slot_item_desert_demand, -1),
      (item_set_slot, "itm_salt", slot_item_production_slot, slot_center_salt_pans),
      (item_set_slot, "itm_salt", slot_item_production_string, "str_pans"),
	  
      (item_set_slot, "itm_dried_meat", slot_item_urban_demand, 15),
      (item_set_slot, "itm_dried_meat", slot_item_rural_demand, 15),
      (item_set_slot, "itm_dried_meat", slot_item_desert_demand, 15),
      (item_set_slot, "itm_dried_meat", slot_item_production_slot, slot_center_head_cattle),
      (item_set_slot, "itm_dried_meat", slot_item_production_string, "str_head_cattle"),

      (item_set_slot, "itm_cheese", slot_item_urban_demand, 10),
      (item_set_slot, "itm_cheese", slot_item_rural_demand, 10),
      (item_set_slot, "itm_cheese", slot_item_desert_demand, 10),
      (item_set_slot, "itm_cheese", slot_item_production_slot, slot_center_head_cattle),
      (item_set_slot, "itm_cheese", slot_item_production_string, "str_head_cattle"),

      (item_set_slot, "itm_butter", slot_item_urban_demand, 2),
      (item_set_slot, "itm_butter", slot_item_rural_demand, 2),
      (item_set_slot, "itm_butter", slot_item_desert_demand, 2),
      (item_set_slot, "itm_butter", slot_item_production_slot, slot_center_head_cattle),
      (item_set_slot, "itm_butter", slot_item_production_string, "str_head_cattle"),

      (item_set_slot, "itm_leatherwork", slot_item_urban_demand, 10),
      (item_set_slot, "itm_leatherwork", slot_item_rural_demand, 10),
      (item_set_slot, "itm_leatherwork", slot_item_desert_demand, 10),
      (item_set_slot, "itm_leatherwork", slot_item_production_slot, slot_center_tanneries),
      (item_set_slot, "itm_leatherwork", slot_item_production_string, "str_tanneries"),
      (item_set_slot, "itm_leatherwork", slot_item_primary_raw_material, "itm_raw_leather"),
      (item_set_slot, "itm_leatherwork", slot_item_input_number, 3),
      (item_set_slot, "itm_leatherwork", slot_item_output_per_run, 3),
      (item_set_slot, "itm_leatherwork", slot_item_overhead_per_run, 50),
	  (item_set_slot, "itm_leatherwork", slot_item_base_price, 220),
	  (item_set_slot, "itm_leatherwork", slot_item_enterprise_building_cost, 8000),

      (item_set_slot, "itm_raw_leather", slot_item_urban_demand, 0),
      (item_set_slot, "itm_raw_leather", slot_item_rural_demand, 0),
      (item_set_slot, "itm_raw_leather", slot_item_desert_demand, 0),
      (item_set_slot, "itm_raw_leather", slot_item_production_slot, slot_center_head_cattle),
      (item_set_slot, "itm_raw_leather", slot_item_production_string, "str_head_cattle"),
      (item_set_slot, "itm_raw_leather", slot_item_is_raw_material_only_for, "itm_leatherwork"),
	  (item_set_slot, "itm_raw_leather", slot_item_base_price, 120),
	  	  
  	  (item_set_slot, "itm_sausages", slot_item_urban_demand, 5),
	  (item_set_slot, "itm_sausages", slot_item_rural_demand, 5),
	  (item_set_slot, "itm_sausages", slot_item_desert_demand, 5),
      (item_set_slot, "itm_sausages", slot_item_production_slot, slot_center_head_sheep),
      (item_set_slot, "itm_sausages", slot_item_production_string, "str_head_sheep"),
	  
	  (item_set_slot, "itm_wool", slot_item_urban_demand, 0),
	  (item_set_slot, "itm_wool", slot_item_rural_demand, 0),
	  (item_set_slot, "itm_wool", slot_item_desert_demand, 0),
      (item_set_slot, "itm_wool", slot_item_production_slot, slot_center_head_sheep),
      (item_set_slot, "itm_wool", slot_item_production_string, "str_head_sheep"),
	  (item_set_slot, "itm_wool", slot_item_is_raw_material_only_for, "itm_wool_cloth"),
	  (item_set_slot, "itm_wool", slot_item_base_price,130),

	  (item_set_slot, "itm_wool_cloth", slot_item_urban_demand, 15),
	  (item_set_slot, "itm_wool_cloth", slot_item_rural_demand, 20),
	  (item_set_slot, "itm_wool_cloth", slot_item_desert_demand, 5),
      (item_set_slot, "itm_wool_cloth", slot_item_production_slot, slot_center_wool_looms),
      (item_set_slot, "itm_wool_cloth", slot_item_production_string, "str_looms"),
	  (item_set_slot, "itm_wool_cloth", slot_item_primary_raw_material, "itm_wool"),
      (item_set_slot, "itm_wool_cloth", slot_item_input_number, 2),
      (item_set_slot, "itm_wool_cloth", slot_item_output_per_run, 2),
      (item_set_slot, "itm_wool_cloth", slot_item_overhead_per_run, 120),
	  (item_set_slot, "itm_wool_cloth", slot_item_base_price, 250),
	  (item_set_slot, "itm_wool_cloth", slot_item_enterprise_building_cost, 6000),
	  
	  (item_set_slot, "itm_raw_flax", slot_item_urban_demand, 0),
	  (item_set_slot, "itm_raw_flax", slot_item_rural_demand, 0),
	  (item_set_slot, "itm_raw_flax", slot_item_desert_demand, 0),
      (item_set_slot, "itm_raw_flax", slot_item_production_slot, slot_center_acres_flax),
      (item_set_slot, "itm_raw_flax", slot_item_production_string, "str_acres_flax"),
      (item_set_slot, "itm_raw_flax", slot_item_is_raw_material_only_for, "itm_linen"),
	  (item_set_slot, "itm_raw_flax", slot_item_base_price, 150),

	  (item_set_slot, "itm_linen", slot_item_urban_demand, 7),
	  (item_set_slot, "itm_linen", slot_item_rural_demand, 3),
	  (item_set_slot, "itm_linen", slot_item_desert_demand, 15),
      (item_set_slot, "itm_linen", slot_item_production_slot, slot_center_linen_looms),
      (item_set_slot, "itm_linen", slot_item_production_string, "str_looms"),
      (item_set_slot, "itm_linen", slot_item_primary_raw_material, "itm_raw_flax"),
      (item_set_slot, "itm_linen", slot_item_input_number, 2),
      (item_set_slot, "itm_linen", slot_item_output_per_run, 2),
      (item_set_slot, "itm_linen", slot_item_overhead_per_run, 120),
	  (item_set_slot, "itm_linen", slot_item_base_price, 250),
	  (item_set_slot, "itm_linen", slot_item_enterprise_building_cost, 6000),
	  
	  (item_set_slot, "itm_iron", slot_item_urban_demand, 0),
	  (item_set_slot, "itm_iron", slot_item_rural_demand, 0),
	  (item_set_slot, "itm_iron", slot_item_desert_demand, 0),
      (item_set_slot, "itm_iron", slot_item_production_slot, slot_center_iron_deposits),
      (item_set_slot, "itm_iron", slot_item_production_string, "str_deposits"),
      (item_set_slot, "itm_iron", slot_item_is_raw_material_only_for, "itm_tools"),
	  (item_set_slot, "itm_iron", slot_item_base_price, 264),
	  
	  (item_set_slot, "itm_tools", slot_item_urban_demand, 7),
	  (item_set_slot, "itm_tools", slot_item_rural_demand, 7),
	  (item_set_slot, "itm_tools", slot_item_desert_demand, 7),
      (item_set_slot, "itm_tools", slot_item_production_slot, slot_center_smithies),
      (item_set_slot, "itm_tools", slot_item_production_string, "str_smithies"),
      (item_set_slot, "itm_tools", slot_item_primary_raw_material, "itm_iron"),
      (item_set_slot, "itm_tools", slot_item_input_number, 2),
      (item_set_slot, "itm_tools", slot_item_output_per_run, 2),
      (item_set_slot, "itm_tools", slot_item_overhead_per_run, 60),
	  (item_set_slot, "itm_tools", slot_item_base_price, 410),
	  (item_set_slot, "itm_tools", slot_item_enterprise_building_cost, 3500),
	  	  
	  (item_set_slot, "itm_pottery", slot_item_urban_demand, 5),
	  (item_set_slot, "itm_pottery", slot_item_rural_demand, 5),
	  (item_set_slot, "itm_pottery", slot_item_desert_demand, 5),
      (item_set_slot, "itm_pottery", slot_item_production_slot, slot_center_pottery_kilns),
      (item_set_slot, "itm_pottery", slot_item_production_string, "str_kilns"),
	  	  
	  (item_set_slot, "itm_oil", slot_item_urban_demand, 10),
	  (item_set_slot, "itm_oil", slot_item_rural_demand, 5),
	  (item_set_slot, "itm_oil", slot_item_desert_demand, -1),
      (item_set_slot, "itm_oil", slot_item_production_slot, slot_center_olive_presses),
      (item_set_slot, "itm_oil", slot_item_production_string, "str_presses"),
      (item_set_slot, "itm_oil", slot_item_primary_raw_material, "itm_raw_olives"),	
      (item_set_slot, "itm_oil", slot_item_input_number, 6),
      (item_set_slot, "itm_oil", slot_item_output_per_run, 2),
      (item_set_slot, "itm_oil", slot_item_overhead_per_run, 80),
	  (item_set_slot, "itm_oil", slot_item_base_price, 450),
	  (item_set_slot, "itm_oil", slot_item_enterprise_building_cost, 4500),
	
	  (item_set_slot, "itm_raw_olives", slot_item_urban_demand, 0),
	  (item_set_slot, "itm_raw_olives", slot_item_rural_demand, 0),
	  (item_set_slot, "itm_raw_olives", slot_item_desert_demand, 0),
      (item_set_slot, "itm_raw_olives", slot_item_production_slot, slot_center_acres_olives),
      (item_set_slot, "itm_raw_olives", slot_item_production_string, "str_olive_groves"),
      (item_set_slot, "itm_raw_olives", slot_item_is_raw_material_only_for, "itm_oil"),
	  (item_set_slot, "itm_raw_olives", slot_item_base_price, 100),
	 
	  (item_set_slot, "itm_velvet", slot_item_urban_demand, 5),
	  (item_set_slot, "itm_velvet", slot_item_rural_demand, 0),
	  (item_set_slot, "itm_velvet", slot_item_desert_demand, -1),
      (item_set_slot, "itm_velvet", slot_item_production_slot, slot_center_silk_looms),
      (item_set_slot, "itm_velvet", slot_item_production_string, "str_looms"),
	  (item_set_slot, "itm_velvet", slot_item_primary_raw_material, "itm_raw_silk"),
      (item_set_slot, "itm_velvet", slot_item_input_number, 2),
      (item_set_slot, "itm_velvet", slot_item_output_per_run, 2),
      (item_set_slot, "itm_velvet", slot_item_overhead_per_run, 160),
	  (item_set_slot, "itm_velvet", slot_item_base_price, 1025),
	  (item_set_slot, "itm_velvet", slot_item_secondary_raw_material, "itm_raw_dyes"),
	  (item_set_slot, "itm_velvet", slot_item_enterprise_building_cost, 10000),
	
	  (item_set_slot, "itm_raw_silk", slot_item_urban_demand, 0),
	  (item_set_slot, "itm_raw_silk", slot_item_rural_demand, 0),
      (item_set_slot, "itm_raw_silk", slot_item_production_slot, slot_center_silk_farms),
      (item_set_slot, "itm_raw_silk", slot_item_production_string, "str_mulberry_groves"),
      (item_set_slot, "itm_raw_silk", slot_item_is_raw_material_only_for, "itm_velvet"),
      (item_set_slot, "itm_raw_silk", slot_item_base_price, 600),

	  (item_set_slot, "itm_raw_dyes", slot_item_urban_demand, 3),
	  (item_set_slot, "itm_raw_dyes", slot_item_rural_demand, 0),
	  (item_set_slot, "itm_raw_dyes", slot_item_desert_demand, -1),
	  (item_set_slot, "itm_raw_dyes", slot_item_production_string, "str_caravans"),
	  (item_set_slot, "itm_raw_dyes", slot_item_base_price, 200),
	  
	  (item_set_slot, "itm_spice", slot_item_urban_demand, 5),
	  (item_set_slot, "itm_spice", slot_item_rural_demand, 0),
	  (item_set_slot, "itm_spice", slot_item_desert_demand, 5),
	  (item_set_slot, "itm_spice", slot_item_production_string, "str_caravans"),
	  
	  (item_set_slot, "itm_furs", slot_item_urban_demand, 5),
	  (item_set_slot, "itm_furs", slot_item_rural_demand, 0),
	  (item_set_slot, "itm_furs", slot_item_desert_demand, -1),
	  (item_set_slot, "itm_furs", slot_item_production_slot, slot_center_fur_traps),
	  (item_set_slot, "itm_furs", slot_item_production_string, "str_traps"),

      (item_set_slot, "itm_honey", slot_item_urban_demand, 5),
      (item_set_slot, "itm_honey", slot_item_rural_demand, 5),
      (item_set_slot, "itm_honey", slot_item_desert_demand, 5),
      (item_set_slot, "itm_honey", slot_item_production_slot, slot_center_apiaries),
      (item_set_slot, "itm_honey", slot_item_production_string, "str_hives"),
	  
      (item_set_slot, "itm_cabbages", slot_item_urban_demand, 7),
      (item_set_slot, "itm_cabbages", slot_item_rural_demand, 7),
      (item_set_slot, "itm_cabbages", slot_item_desert_demand, 7),
      (item_set_slot, "itm_cabbages", slot_item_production_slot, slot_center_household_gardens),
      (item_set_slot, "itm_cabbages", slot_item_production_string, "str_gardens"),

      (item_set_slot, "itm_raw_date_fruit", slot_item_urban_demand, 7),
      (item_set_slot, "itm_raw_date_fruit", slot_item_rural_demand, 7),
      (item_set_slot, "itm_raw_date_fruit", slot_item_desert_demand, 7),
      (item_set_slot, "itm_raw_date_fruit", slot_item_production_slot, slot_center_household_gardens),
      (item_set_slot, "itm_raw_date_fruit", slot_item_production_string, "str_acres_oasis"),
	  	  
      # Setting book intelligence requirements
      (item_set_slot, "itm_book_tactics", slot_item_intelligence_requirement, 9),
      (item_set_slot, "itm_book_persuasion", slot_item_intelligence_requirement, 8),
      (item_set_slot, "itm_book_leadership", slot_item_intelligence_requirement, 7),
      (item_set_slot, "itm_book_intelligence", slot_item_intelligence_requirement, 10),
      (item_set_slot, "itm_book_trade", slot_item_intelligence_requirement, 11),
      (item_set_slot, "itm_book_weapon_mastery", slot_item_intelligence_requirement, 9),
      (item_set_slot, "itm_book_engineering", slot_item_intelligence_requirement, 12),

      (item_set_slot, "itm_book_wound_treatment_reference", slot_item_intelligence_requirement, 10),
      (item_set_slot, "itm_book_training_reference", slot_item_intelligence_requirement, 10),
      (item_set_slot, "itm_book_surgery_reference", slot_item_intelligence_requirement, 10),	 
	 ]),
	 
	 
    ("initialize_town_arena_info",
    [
      (try_for_range, ":town_no", towns_begin, towns_end),
        (party_set_slot, ":town_no", slot_town_tournament_max_teams, 4),
        (party_set_slot, ":town_no", slot_town_tournament_max_team_size, 8),
      (try_end),
      (party_set_slot, "p_town_6", slot_town_tournament_max_team_size, 2),

      (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),
	  
      (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),

      (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),

      (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),
      
      (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),

      (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),

      (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),

      (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),

      (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),

      (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),

      (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),

      (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),

      (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),

      (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),

      (party_set_slot,"p_town_15", slot_town_arena_melee_1_num_teams,   2),
      (party_set_slot,"p_town_15", slot_town_arena_melee_1_team_size,   8),
      (party_set_slot,"p_town_15", slot_town_arena_melee_2_num_teams,   3),
      (party_set_slot,"p_town_15", slot_town_arena_melee_2_team_size,   4),
      (party_set_slot,"p_town_15", slot_town_arena_melee_3_num_teams,   3),
      (party_set_slot,"p_town_15", slot_town_arena_melee_3_team_size,   6),

      (party_set_slot,"p_town_16", slot_town_arena_melee_1_num_teams,   3),
      (party_set_slot,"p_town_16", slot_town_arena_melee_1_team_size,   8),
      (party_set_slot,"p_town_16", slot_town_arena_melee_2_num_teams,   4),
      (party_set_slot,"p_town_16", slot_town_arena_melee_2_team_size,   6),
      (party_set_slot,"p_town_16", slot_town_arena_melee_3_num_teams,   4),
      (party_set_slot,"p_town_16", slot_town_arena_melee_3_team_size,   5),

      (party_set_slot,"p_town_17", slot_town_arena_melee_1_num_teams,   2),
      (party_set_slot,"p_town_17", slot_town_arena_melee_1_team_size,   8),
      (party_set_slot,"p_town_17", slot_town_arena_melee_2_num_teams,   4),
      (party_set_slot,"p_town_17", slot_town_arena_melee_2_team_size,   5),
      (party_set_slot,"p_town_17", slot_town_arena_melee_3_num_teams,   4),
      (party_set_slot,"p_town_17", slot_town_arena_melee_3_team_size,   7),

      (party_set_slot,"p_town_18", slot_town_arena_melee_1_num_teams,   2),
      (party_set_slot,"p_town_18", slot_town_arena_melee_1_team_size,   4),
      (party_set_slot,"p_town_18", slot_town_arena_melee_2_num_teams,   2),
      (party_set_slot,"p_town_18", slot_town_arena_melee_2_team_size,   5),
      (party_set_slot,"p_town_18", slot_town_arena_melee_3_num_teams,   2),
      (party_set_slot,"p_town_18", slot_town_arena_melee_3_team_size,   6),

      (party_set_slot,"p_town_19", slot_town_arena_melee_1_num_teams,   2),
      (party_set_slot,"p_town_19", slot_town_arena_melee_1_team_size,   8),
      (party_set_slot,"p_town_19", slot_town_arena_melee_2_num_teams,   4),
      (party_set_slot,"p_town_19", slot_town_arena_melee_2_team_size,   4),
      (party_set_slot,"p_town_19", slot_town_arena_melee_3_num_teams,   4),
      (party_set_slot,"p_town_19", slot_town_arena_melee_3_team_size,   6),

      (party_set_slot,"p_town_20", slot_town_arena_melee_1_num_teams,   4),
      (party_set_slot,"p_town_20", slot_town_arena_melee_1_team_size,   2),
      (party_set_slot,"p_town_20", slot_town_arena_melee_2_num_teams,   4),
      (party_set_slot,"p_town_20", slot_town_arena_melee_2_team_size,   4),
      (party_set_slot,"p_town_20", slot_town_arena_melee_3_num_teams,   4),
      (party_set_slot,"p_town_20", slot_town_arena_melee_3_team_size,   6),

      (party_set_slot,"p_town_21", slot_town_arena_melee_1_num_teams,   3),
      (party_set_slot,"p_town_21", slot_town_arena_melee_1_team_size,   3),
      (party_set_slot,"p_town_21", slot_town_arena_melee_2_num_teams,   2),
      (party_set_slot,"p_town_21", slot_town_arena_melee_2_team_size,   6),
      (party_set_slot,"p_town_21", slot_town_arena_melee_3_num_teams,   2),
      (party_set_slot,"p_town_21", slot_town_arena_melee_3_team_size,   8),

      (party_set_slot,"p_town_22", slot_town_arena_melee_1_num_teams,   4),
      (party_set_slot,"p_town_22", slot_town_arena_melee_1_team_size,   3),
      (party_set_slot,"p_town_22", slot_town_arena_melee_2_num_teams,   3),
      (party_set_slot,"p_town_22", slot_town_arena_melee_2_team_size,   4),
      (party_set_slot,"p_town_22", slot_town_arena_melee_3_num_teams,   2),
      (party_set_slot,"p_town_22", slot_town_arena_melee_3_team_size,   6),
	]),	

	("initialize_banner_info",	
	[	
	  #Banners
      (try_for_range, ":cur_troop", active_npcs_begin, kingdom_ladies_end),
        (troop_set_slot, ":cur_troop", slot_troop_custom_banner_flag_type, -1),
        (troop_set_slot, ":cur_troop", slot_troop_custom_banner_map_flag_type, -1),
      (try_end),
      (troop_set_slot, "trp_player", slot_troop_custom_banner_flag_type, -1),
      (troop_set_slot, "trp_player", slot_troop_custom_banner_map_flag_type, -1),
      (store_random_in_range, "$g_election_date", 0, 45), #setting a random election date
      #Assigning global constant
      #(call_script, "script_store_average_center_value_per_faction"),

	  # NE kt0
	  #kt0 Autoresolve v586
	  (call_script, "script_kt_init_troop_slots"),
	  
	  # ne settings
	  ## Assign initial values to customization options - Jinnai
      (assign,"$setting_troops_flee",1),
      (assign,"$setting_use_new_loot_system",1),
      (assign,"$setting_towns_rebel",1),
      (assign,"$setting_lords_rebel",1),
      (assign,"$setting_use_spearwall",1),
      (assign,"$setting_use_shieldbash",1),
      (assign,"$setting_use_new_noble_recruit_system",1),
      (assign,"$setting_require_faction_noble_recruit",1),
      (assign,"$setting_prisoner_penalties",1),
	  # v585 Josef formations
	  (assign,"$setting_troops_form",0),  # Formations OFF at start
	  
	  # (assign,"$setting_sort_inventory",0),  
	  # end v585 Josef
	  # v586 initialise merc targeting
	  (assign, "$ass_target_lord", "p_main_party"),
	  (assign, "$songlist", 0),
	  (assign, "$songlist1", 0),
	  (assign, "$songlist2", 0),
	  (assign, "$songlist3", 0),
	  (assign, "$mercenary", 0),
	  (assign, "$vassal_of", 0), 
	  (assign, "$played_songs", 0),
	  # set flag for player formations (to be switched during certain elite quests)
	  (assign, "$switch_formations", 0), 
	  # end
      (assign,"$setting_lords_ask",1),
      (assign,"$setting_use_wounding",1),
      #(assign,"$setting_use_roads",0),
      (assign,"$setting_invasion_time",3600),
      #(assign, "$setting_overseer_looting", 0),
 #     (assign,"$save_game_version",expansion_version),
      (assign,"$invaded",0),
      (assign,"$has_crown",0),
      (assign,"$vassal_gift",0),
	  
	  # NE end settings

	  
      (troop_set_slot, "trp_player", slot_troop_custom_banner_bg_color_1, 0xFFFFFFFF),
      (troop_set_slot, "trp_player", slot_troop_custom_banner_bg_color_2, 0xFFFFFFFF),
      (troop_set_slot, "trp_player", slot_troop_custom_banner_charge_color_1, 0xFFFFFFFF),
      (troop_set_slot, "trp_player", slot_troop_custom_banner_charge_color_2, 0xFFFFFFFF),
      (troop_set_slot, "trp_player", slot_troop_custom_banner_charge_color_3, 0xFFFFFFFF),
      (troop_set_slot, "trp_player", slot_troop_custom_banner_charge_color_4, 0xFFFFFFFF),

      #Setting background colors for banners
      (troop_set_slot, "trp_banner_background_color_array", 0, 0xFF8f4531),
      (troop_set_slot, "trp_banner_background_color_array", 1, 0xFFd9d7d1),
      (troop_set_slot, "trp_banner_background_color_array", 2, 0xFF373736),
      (troop_set_slot, "trp_banner_background_color_array", 3, 0xFFa48b28),
      (troop_set_slot, "trp_banner_background_color_array", 4, 0xFF497735),
      (troop_set_slot, "trp_banner_background_color_array", 5, 0xFF82362d),
      (troop_set_slot, "trp_banner_background_color_array", 6, 0xFF793329),
      (troop_set_slot, "trp_banner_background_color_array", 7, 0xFF262521),
      (troop_set_slot, "trp_banner_background_color_array", 8, 0xFFd9dad1),
      (troop_set_slot, "trp_banner_background_color_array", 9, 0xFF524563),
      (troop_set_slot, "trp_banner_background_color_array", 10, 0xFF91312c),
      (troop_set_slot, "trp_banner_background_color_array", 11, 0xFFafa231),
      (troop_set_slot, "trp_banner_background_color_array", 12, 0xFF706d3c),
      (troop_set_slot, "trp_banner_background_color_array", 13, 0xFFd6d3ce),
      (troop_set_slot, "trp_banner_background_color_array", 14, 0xFF521c08),
      (troop_set_slot, "trp_banner_background_color_array", 15, 0xFF394584),
      (troop_set_slot, "trp_banner_background_color_array", 16, 0xFF42662e),
      (troop_set_slot, "trp_banner_background_color_array", 17, 0xFFdfded6),
      (troop_set_slot, "trp_banner_background_color_array", 18, 0xFF292724),
      (troop_set_slot, "trp_banner_background_color_array", 19, 0xFF58611b),
      (troop_set_slot, "trp_banner_background_color_array", 20, 0xFF313a67),
      (troop_set_slot, "trp_banner_background_color_array", 21, 0xFF9c924a),
	  (troop_set_slot, "trp_banner_background_color_array", 22, 0xFF998b39),
	  (troop_set_slot, "trp_banner_background_color_array", 23, 0xFF365168),
      (troop_set_slot, "trp_banner_background_color_array", 24, 0xFFd6d3ce),
      (troop_set_slot, "trp_banner_background_color_array", 25, 0xFF94a642),
      (troop_set_slot, "trp_banner_background_color_array", 26, 0xFF944131),
      (troop_set_slot, "trp_banner_background_color_array", 27, 0xFF893b34),
      (troop_set_slot, "trp_banner_background_color_array", 28, 0xFF425510),
      (troop_set_slot, "trp_banner_background_color_array", 29, 0xFF94452e),
      (troop_set_slot, "trp_banner_background_color_array", 30, 0xFF475a94),
      (troop_set_slot, "trp_banner_background_color_array", 31, 0xFFd1b231),
      (troop_set_slot, "trp_banner_background_color_array", 32, 0xFFe1e2df),
	  (troop_set_slot, "trp_banner_background_color_array", 33, 0xFF997c1e),
      (troop_set_slot, "trp_banner_background_color_array", 34, 0xFFc6b74d),
	  (troop_set_slot, "trp_banner_background_color_array", 35, 0xFFad9a18),
      (troop_set_slot, "trp_banner_background_color_array", 36, 0xFF212421),
	  (troop_set_slot, "trp_banner_background_color_array", 37, 0xFF8c2021),
      (troop_set_slot, "trp_banner_background_color_array", 38, 0xFF4d7136),
	  (troop_set_slot, "trp_banner_background_color_array", 39, 0xFF395d84),
      (troop_set_slot, "trp_banner_background_color_array", 40, 0xFF527539),
      (troop_set_slot, "trp_banner_background_color_array", 41, 0xFF9c3c39),
      (troop_set_slot, "trp_banner_background_color_array", 42, 0xFF42518c),
      (troop_set_slot, "trp_banner_background_color_array", 43, 0xFFa46a2c),
	  (troop_set_slot, "trp_banner_background_color_array", 44, 0xFF9f5141),
      (troop_set_slot, "trp_banner_background_color_array", 45, 0xFF2c6189),
      (troop_set_slot, "trp_banner_background_color_array", 46, 0xFF556421),
      (troop_set_slot, "trp_banner_background_color_array", 47, 0xFF9d621e),
      (troop_set_slot, "trp_banner_background_color_array", 48, 0xFFdeded6),
      (troop_set_slot, "trp_banner_background_color_array", 49, 0xFF6e4891),
      (troop_set_slot, "trp_banner_background_color_array", 50, 0xFF865a29),
      (troop_set_slot, "trp_banner_background_color_array", 51, 0xFFdedfd9),
      (troop_set_slot, "trp_banner_background_color_array", 52, 0xFF524273),
      (troop_set_slot, "trp_banner_background_color_array", 53, 0xFF8c3821),
	  (troop_set_slot, "trp_banner_background_color_array", 54, 0xFFd1cec6),
      (troop_set_slot, "trp_banner_background_color_array", 55, 0xFF313031),
      (troop_set_slot, "trp_banner_background_color_array", 56, 0xFF47620d),
	  (troop_set_slot, "trp_banner_background_color_array", 57, 0xFF6b4139),
      (troop_set_slot, "trp_banner_background_color_array", 58, 0xFFd6d7d6),
      (troop_set_slot, "trp_banner_background_color_array", 59, 0xFF2e2f2c),
      (troop_set_slot, "trp_banner_background_color_array", 60, 0xFF604283),
      (troop_set_slot, "trp_banner_background_color_array", 61, 0xFF395584),
      (troop_set_slot, "trp_banner_background_color_array", 62, 0xFF313031),
      (troop_set_slot, "trp_banner_background_color_array", 63, 0xFF7e3f2e),
      (troop_set_slot, "trp_banner_background_color_array", 64, 0xFF343434),
      (troop_set_slot, "trp_banner_background_color_array", 65, 0xFF3c496b),
      (troop_set_slot, "trp_banner_background_color_array", 66, 0xFFd9d8d1),
      (troop_set_slot, "trp_banner_background_color_array", 67, 0xFF99823c),
      (troop_set_slot, "trp_banner_background_color_array", 68, 0xFF9f822e),
      (troop_set_slot, "trp_banner_background_color_array", 69, 0xFF393839),
      (troop_set_slot, "trp_banner_background_color_array", 70, 0xFFa54931),
      (troop_set_slot, "trp_banner_background_color_array", 71, 0xFFdfdcd6),
      (troop_set_slot, "trp_banner_background_color_array", 72, 0xFF9f4a36),
      (troop_set_slot, "trp_banner_background_color_array", 73, 0xFF8c7521),
      (troop_set_slot, "trp_banner_background_color_array", 74, 0xFF9f4631),
      (troop_set_slot, "trp_banner_background_color_array", 75, 0xFF793324),
      (troop_set_slot, "trp_banner_background_color_array", 76, 0xFF395076),
      (troop_set_slot, "trp_banner_background_color_array", 77, 0xFF2c2b2c),
      (troop_set_slot, "trp_banner_background_color_array", 78, 0xFF657121),
      (troop_set_slot, "trp_banner_background_color_array", 79, 0xFF7e3121),
      (troop_set_slot, "trp_banner_background_color_array", 80, 0xFF76512e),
      (troop_set_slot, "trp_banner_background_color_array", 81, 0xFFe7e3de),
      (troop_set_slot, "trp_banner_background_color_array", 82, 0xFF947921),
      (troop_set_slot, "trp_banner_background_color_array", 83, 0xFF4d7b7c),
      (troop_set_slot, "trp_banner_background_color_array", 84, 0xFF343331),
      (troop_set_slot, "trp_banner_background_color_array", 85, 0xFFa74d36),
      (troop_set_slot, "trp_banner_background_color_array", 86, 0xFFe7e3de),
      (troop_set_slot, "trp_banner_background_color_array", 87, 0xFFd6d8ce),
      (troop_set_slot, "trp_banner_background_color_array", 88, 0xFF3e4d67),
      (troop_set_slot, "trp_banner_background_color_array", 89, 0xFF9f842e),
      (troop_set_slot, "trp_banner_background_color_array", 90, 0xFF4d6994),
      (troop_set_slot, "trp_banner_background_color_array", 91, 0xFF4a6118),
      (troop_set_slot, "trp_banner_background_color_array", 92, 0xFF943c29),
      (troop_set_slot, "trp_banner_background_color_array", 93, 0xFF394479),
      (troop_set_slot, "trp_banner_background_color_array", 94, 0xFF343331),
      (troop_set_slot, "trp_banner_background_color_array", 95, 0xFF3f4d5d),
      (troop_set_slot, "trp_banner_background_color_array", 96, 0xFF4a6489),
      (troop_set_slot, "trp_banner_background_color_array", 97, 0xFF313031),
      (troop_set_slot, "trp_banner_background_color_array", 98, 0xFFd6d7ce),
      (troop_set_slot, "trp_banner_background_color_array", 99, 0xFFc69e00),
      (troop_set_slot, "trp_banner_background_color_array", 100, 0xFF638e52),
      (troop_set_slot, "trp_banner_background_color_array", 101, 0xFFdcdbd3),
      (troop_set_slot, "trp_banner_background_color_array", 102, 0xFFdbdcd3),
      (troop_set_slot, "trp_banner_background_color_array", 103, 0xFF843831),
      (troop_set_slot, "trp_banner_background_color_array", 104, 0xFFcecfc6),
	  (troop_set_slot, "trp_banner_background_color_array", 105, 0xFFc39d31),
	  (troop_set_slot, "trp_banner_background_color_array", 106, 0xFFcbb670),
	  (troop_set_slot, "trp_banner_background_color_array", 107, 0xFF394a18),
	  (troop_set_slot, "trp_banner_background_color_array", 108, 0xFF372708),
	  (troop_set_slot, "trp_banner_background_color_array", 109, 0xFF9a6810),
	  (troop_set_slot, "trp_banner_background_color_array", 110, 0xFFb27910),
	  (troop_set_slot, "trp_banner_background_color_array", 111, 0xFF8c8621),
	  (troop_set_slot, "trp_banner_background_color_array", 112, 0xFF975a03),
	  (troop_set_slot, "trp_banner_background_color_array", 113, 0xFF2c2924),
	  (troop_set_slot, "trp_banner_background_color_array", 114, 0xFFaa962c),
	  (troop_set_slot, "trp_banner_background_color_array", 115, 0xFFa2822e),
	  (troop_set_slot, "trp_banner_background_color_array", 116, 0xFF7b8a8c),
	  (troop_set_slot, "trp_banner_background_color_array", 117, 0xFF3c0908),
      (troop_set_slot, "trp_banner_background_color_array", 118, 0xFFFF00FF),
      (troop_set_slot, "trp_banner_background_color_array", 119, 0xFF671e14),
      (troop_set_slot, "trp_banner_background_color_array", 120, 0xFF103042),
      (troop_set_slot, "trp_banner_background_color_array", 121, 0xFF4a4500),
      (troop_set_slot, "trp_banner_background_color_array", 122, 0xFF703324),
	  (troop_set_slot, "trp_banner_background_color_array", 123, 0xFF24293c),
	  (troop_set_slot, "trp_banner_background_color_array", 124, 0xFF5d6966),
	  (troop_set_slot, "trp_banner_background_color_array", 125, 0xFFbd9631),
	  (troop_set_slot, "trp_banner_background_color_array", 126, 0xFFc6b26b),
	  (troop_set_slot, "trp_banner_background_color_array", 127, 0xFF394918),

      #Default banners
      (troop_set_slot, "trp_banner_background_color_array", 128, 0xFF212221),
      (troop_set_slot, "trp_banner_background_color_array", 129, 0xFF212221),
      (troop_set_slot, "trp_banner_background_color_array", 130, 0xFF2E3B10),
      (troop_set_slot, "trp_banner_background_color_array", 131, 0xFF425D7B),
      (troop_set_slot, "trp_banner_background_color_array", 132, 0xFF394608),
	  ]),
		
		
    ("initialize_economic_information",
    [   	     
	    #All towns produce tools, pottery, and wool cloth for sale in countryside
	(try_for_range, ":town_no", towns_begin, towns_end),	
		(party_set_slot, ":town_no", slot_center_wool_looms, 20),
		(party_set_slot, ":town_no", slot_center_breweries, 2),
		(party_set_slot, ":town_no", slot_center_pottery_kilns, 10),
		(party_set_slot, ":town_no", slot_center_smithies, 15),
		(party_set_slot, ":town_no", slot_center_mills, 5),
		(party_set_slot, ":town_no", slot_center_tanneries, 2),
		(party_set_slot, ":town_no", slot_center_wine_presses, 1),
		(party_set_slot, ":town_no", slot_center_olive_presses, 2),
		
		(party_set_slot, ":town_no", slot_center_acres_grain, 1000), #Surrounding fields
		(party_set_slot, ":town_no", slot_center_acres_vineyard, 1000), #Surrounding fields
		
    (try_end),
	  
	(party_set_slot, "p_town_1", slot_center_linen_looms, 15), 		#Sargoth
	
	(party_set_slot, "p_town_2", slot_center_salt_pans, 5), 		#Tihr
	(party_set_slot, "p_town_2", slot_center_fishing_fleet, 25), 	#Tihr
	
	(party_set_slot, "p_town_3", slot_center_wine_presses, 10), 	#Veluca
	
	(party_set_slot, "p_town_4", slot_center_olive_presses, 15), 	#Suno
	
	(party_set_slot, "p_town_5", slot_center_silk_looms, 20), 		#Jelkaka
	(party_set_slot, "p_town_5", slot_center_fishing_fleet, 30), 	#Jelkala

	(party_set_slot, "p_town_6", slot_center_breweries, 10), 		#Praven
	(party_set_slot, "p_town_6", slot_center_tanneries, 4), 	    #Praven
	(party_set_slot, "p_town_6", slot_center_fishing_fleet, 10), 	#Praven
	
	(party_set_slot, "p_town_7", slot_center_mills, 15), 			#Uxkhal
	(party_set_slot, "p_town_7", slot_center_tanneries, 4), 	    #Uxkhal

	(party_set_slot, "p_town_8", slot_center_smithies, 25), 	    #Reyvadin
	(party_set_slot, "p_town_8", slot_center_wool_looms, 35), 	    #Reyvadin
	(party_set_slot, "p_town_8", slot_center_tanneries, 4), 	    #Reyvadin

	(party_set_slot, "p_town_9", slot_center_smithies, 18), 	    #Khudan
	(party_set_slot, "p_town_9", slot_center_tanneries, 3), 	    #Khudan
	(party_set_slot, "p_town_9", slot_center_fishing_fleet, 5), 	#Khudan
	
	(party_set_slot, "p_town_10", slot_center_salt_pans, 2), 	    #Tulga
	
	(party_set_slot, "p_town_11", slot_center_smithies, 19),		#Curaw
	(party_set_slot, "p_town_11", slot_center_fishing_fleet, 10), 	#Khudan
	
    (party_set_slot, "p_town_12", slot_center_salt_pans, 5), 		#Wercheg
	(party_set_slot, "p_town_12", slot_center_fishing_fleet, 25), 	#Wercheg

	(party_set_slot, "p_town_13", slot_center_wool_looms, 30), 	    #Rivacheg
	(party_set_slot, "p_town_13", slot_center_tanneries, 5), 	    #Rivacheg
	(party_set_slot, "p_town_13", slot_center_fishing_fleet, 20), 	#Rivacheg

    (party_set_slot, "p_town_14", slot_center_salt_pans, 2), 		#Halmar
	(party_set_slot, "p_town_14", slot_center_tanneries, 3), 	    #Halmar
	
	(party_set_slot, "p_town_15", slot_center_smithies, 20), 		#Yalen
	(party_set_slot, "p_town_15", slot_center_wine_presses, 5), 	#Yalen
	(party_set_slot, "p_town_15", slot_center_olive_presses, 5), 	#Yalen
	(party_set_slot, "p_town_15", slot_center_fishing_fleet, 25), 	#Yalen
	
	(party_set_slot, "p_town_16", slot_center_smithies, 30), 		#Dhirim
	(party_set_slot, "p_town_16", slot_center_tanneries, 4), 	    #Dhirim

	(party_set_slot, "p_town_17", slot_center_wool_looms, 40), 	    #Ichamur

	(party_set_slot, "p_town_18", slot_center_wool_looms, 35), 	    #narra
	(party_set_slot, "p_town_18", slot_center_wine_presses, 4), 	#narra
	  
	(party_set_slot, "p_town_19", slot_center_tanneries, 5), 	    #Shariz
	(party_set_slot, "p_town_19", slot_center_breweries, 0), 	    #Shariz
	(party_set_slot, "p_town_19", slot_center_wine_presses, 3), 	#Shariz
	(party_set_slot, "p_town_19", slot_center_fishing_fleet, 5), 	#Shariz

	(party_set_slot, "p_town_20", slot_center_tanneries, 5), 	    #Darquba
	(party_set_slot, "p_town_20", slot_center_breweries, 0), 	    #Darquba
	(party_set_slot, "p_town_20", slot_center_wine_presses, 2), 	#Darquba

	(party_set_slot, "p_town_21", slot_center_tanneries, 5), 	    #Ahmerrad
	(party_set_slot, "p_town_21", slot_center_breweries, 0), 	    #Ahmerrad
	(party_set_slot, "p_town_21", slot_center_wine_presses, 2), 	#Ahmerrad
	  
	(party_set_slot, "p_town_22", slot_center_tanneries, 5), 	    #Bariyye
	(party_set_slot, "p_town_22", slot_center_breweries, 0), 	    #Bariyye


	
    (try_for_range, ":village_no", villages_begin, villages_end),
        (store_random_in_range, ":random_cattle", 35, 65),
        (party_set_slot, ":village_no", slot_center_head_cattle, ":random_cattle"),

        (store_random_in_range, ":random_sheep", 90, 120),
        (party_set_slot, ":village_no", slot_center_head_sheep, ":random_sheep"),

		(party_set_slot, ":village_no", slot_center_acres_grain, 10000), #10 acres for each of 1000 households
		(party_set_slot, ":village_no", slot_center_acres_vineyard, 500), #10 acres for each of 1000 households
		(party_set_slot, ":village_no", slot_center_acres_olives, 200), #10 acres for each of 1000 households

		(party_set_slot, ":village_no", slot_center_apiaries, 1), 
		(party_set_slot, ":village_no", slot_center_mills, 1),
		(party_set_slot, ":village_no", slot_center_pottery_kilns, 1),
		
		
		(try_begin),
			(party_slot_eq, ":village_no", slot_village_market_town, "p_town_1"), #Sargoth, flax
			(party_set_slot, ":village_no", slot_center_acres_flax, 8000),
		
		(else_try),
			(party_slot_eq, ":village_no", slot_village_market_town, "p_town_2"), #Wercheg
                        (party_set_slot, ":village_no", slot_center_acres_vineyard, 8000),
                        (party_set_slot, ":village_no", slot_center_household_gardens, 10),
			
		(else_try),	
			(party_slot_eq, ":village_no", slot_village_market_town, "p_town_3"), #veluca
			(party_set_slot, ":village_no", slot_center_acres_vineyard, 2000),
			(party_set_slot, ":village_no", slot_center_acres_olives, 4000),
			
		(else_try),
			(party_slot_eq, ":village_no", slot_village_market_town, "p_town_4"), #suno 
			(party_set_slot, ":village_no", slot_center_acres_grain, 12000),
			(party_set_slot, ":village_no", slot_center_acres_olives, 5000),
			
		(else_try),
			(party_slot_eq, ":village_no", slot_village_market_town, "p_town_5"), #jelkala
			(party_set_slot, ":village_no", slot_center_silk_farms, 500),
			
		(else_try),
			(party_slot_eq, ":village_no", slot_village_market_town, "p_town_6"), #praven 
			(party_set_slot, ":village_no", slot_center_acres_grain, 15000),
		
		(else_try),
			(party_slot_eq, ":village_no", slot_village_market_town, "p_town_7"), #uxkhal 
			(party_set_slot, ":village_no", slot_center_acres_grain, 15000),

		(else_try),
			(party_slot_eq, ":village_no", slot_village_market_town, "p_town_8"), #reyvadin 
			(party_set_slot, ":village_no", slot_center_head_cattle, 100),
			(party_set_slot, ":village_no", slot_center_acres_grain, 12000),
			
		(else_try),
			(party_slot_eq, ":village_no", slot_village_market_town, "p_town_9"), #khudan 
			(party_set_slot, ":village_no", slot_center_fur_traps, 4),
			(party_set_slot, ":village_no", slot_center_acres_vineyard, 0),
			(party_set_slot, ":village_no", slot_center_acres_olives, 0),
		
		(else_try),
			(party_slot_eq, ":village_no", slot_village_market_town, "p_town_10"), #tulga 
			(party_set_slot, ":village_no", slot_center_head_sheep, 150),
			(party_set_slot, ":village_no", slot_center_acres_grain, 8000),
			(party_set_slot, ":village_no", slot_center_salt_pans, 1),
			(party_set_slot, ":village_no", slot_center_fur_traps, 1),
			
		(else_try),
			(party_slot_eq, ":village_no", slot_village_market_town, "p_town_11"), #curaw
			(party_set_slot, ":village_no", slot_center_iron_deposits, 10),
			(party_set_slot, ":village_no", slot_center_fur_traps, 3),
			(party_set_slot, ":village_no", slot_center_acres_vineyard, 0),
			(party_set_slot, ":village_no", slot_center_acres_olives, 0),

		(else_try),
			(party_slot_eq, ":village_no", slot_village_market_town, "p_town_12"), #rivacheg
			(party_set_slot, ":village_no", slot_center_head_cattle, 75),
			(party_set_slot, ":village_no", slot_center_acres_grain, 12000),
			
		(else_try),
			(party_slot_eq, ":village_no", slot_village_market_town, "p_town_13"), #Wercheg
		
		#14Halmar has a salt pan nearby
		(else_try),
			(party_slot_eq, ":village_no", slot_village_market_town, "p_town_14"), #Halmar
			(party_set_slot, ":village_no", slot_center_salt_pans, 1),
		
		(else_try),
			(party_slot_eq, ":village_no", slot_village_market_town, "p_town_15"), #yalen
			(party_set_slot, ":village_no", slot_center_acres_vineyard, 2000),
			
		(else_try),
			(party_slot_eq, ":village_no", slot_village_market_town, "p_town_16"), #dhirim
			(party_set_slot, ":village_no", slot_center_iron_deposits, 7),

		#17 Ichamur
		(else_try),
			(party_slot_eq, ":village_no", slot_village_market_town, "p_town_17"), #ichamur
			(party_set_slot, ":village_no", slot_center_acres_grain, 12000),
			(party_set_slot, ":village_no", slot_center_fur_traps, 1),

		#18 Narra
		(else_try),
			(party_slot_eq, ":village_no", slot_village_market_town, "p_town_18"), #narra
			(party_set_slot, ":village_no", slot_center_iron_deposits, 2),
			
		(else_try),
			(party_slot_eq, ":village_no", slot_village_market_town, "p_town_19"), #
			(party_set_slot, ":village_no", slot_center_acres_grain, 7000),
			(party_set_slot, ":village_no", slot_center_acres_vineyard, 2000),
			(party_set_slot, ":village_no", slot_center_acres_flax, 2000),
			(party_set_slot, ":village_no", slot_center_acres_olives, 3000),
			(party_set_slot, ":village_no", slot_center_acres_dates, 8000),
			(party_set_slot, ":village_no", slot_center_salt_pans, 1),
			(party_set_slot, ":village_no", slot_center_head_sheep, 150),
			(party_set_slot, ":village_no", slot_center_head_cattle, 30),

		(else_try),
			(party_slot_eq, ":village_no", slot_village_market_town, "p_town_20"), #
			(party_set_slot, ":village_no", slot_center_acres_grain, 7000),
			(party_set_slot, ":village_no", slot_center_acres_vineyard, 2000),
			(party_set_slot, ":village_no", slot_center_acres_olives, 3000),
			(party_set_slot, ":village_no", slot_center_acres_dates, 8000),
			(party_set_slot, ":village_no", slot_center_salt_pans, 1),
			(party_set_slot, ":village_no", slot_center_head_sheep, 150),
			(party_set_slot, ":village_no", slot_center_head_cattle, 30),
			(party_set_slot, ":village_no", slot_center_linen_looms, 30),
			
		(else_try),
			(party_slot_eq, ":village_no", slot_village_market_town, "p_town_21"), #Ahmerrad -- hillside
			(party_set_slot, ":village_no", slot_center_acres_grain, 9000),
			(party_set_slot, ":village_no", slot_center_acres_vineyard, 2000),
			(party_set_slot, ":village_no", slot_center_acres_olives, 4000),
			(party_set_slot, ":village_no", slot_center_acres_dates, 2000),
			(party_set_slot, ":village_no", slot_center_iron_deposits, 8),
			(party_set_slot, ":village_no", slot_center_head_sheep, 150),
			(party_set_slot, ":village_no", slot_center_head_cattle, 30),

		(else_try),
			(party_slot_eq, ":village_no", slot_village_market_town, "p_town_22"), #Bariyye -- deep desert
			(party_set_slot, ":village_no", slot_center_acres_grain, 5000),
			(party_set_slot, ":village_no", slot_center_acres_vineyard, 2000),
			(party_set_slot, ":village_no", slot_center_acres_flax, 2000),
			(party_set_slot, ":village_no", slot_center_acres_olives, 3000),
			(party_set_slot, ":village_no", slot_center_acres_dates, 8000),
			(party_set_slot, ":village_no", slot_center_salt_pans, 3),
			(party_set_slot, ":village_no", slot_center_iron_deposits, 5),
			(party_set_slot, ":village_no", slot_center_head_sheep, 150),
			(party_set_slot, ":village_no", slot_center_head_cattle, 30),
			
		(try_end),
    (try_end),
	
       #determining village productions which are bounded by castle by nearby village productions which are bounded by a town.
       (try_for_range, ":village_no", villages_begin, villages_end),
         (party_get_slot, ":bound_center", ":village_no", slot_village_bound_center),
         (is_between, ":bound_center", castles_begin, castles_end),

         (try_for_range, ":cur_production_source", slot_production_sources_begin, slot_production_sources_end),

               (assign, ":total_averaged_production", 0),
               (try_for_range, ":effected_village_no", villages_begin, villages_end),
                 (party_get_slot, ":bound_center", ":effected_village_no", slot_village_bound_center),
             (is_between, ":bound_center", towns_begin, towns_end),

                 (store_distance_to_party_from_party, ":dist", ":village_no", ":effected_village_no"),
                 (le, ":dist", 72),
                 
                 (party_get_slot, ":production", ":village_no", ":cur_production_source"),
                 
                 (store_add, ":dist_plus_24", ":dist", 24),
                 (store_mul, ":production_mul_12", ":production", 12),
                 (store_div, ":averaged_production", ":production_mul_12", ":dist_plus_24"), #if close (12/24=1/2) else (12/96=1/8)              
                 (val_div, ":averaged_production", 2), #if close (1/4) else (1/16)
                 (val_add, ":total_averaged_production", ":averaged_production"),
               (try_end),

               (party_set_slot, ":village_no", ":cur_production_source", ":total_averaged_production"),
         (try_end),
       (try_end),

  
	#Ocean and river villages, new map  
	  
#, , , , , , Vajayeg, ,  Tismir, , Shapeshte, , Kulum, Aldalen, Gisim, , Balanli, Elberl,Nemeija, , Iyindah, Veidar. , , ,., , , 

    (party_set_slot, "p_village_1", slot_center_fishing_fleet, 15), #Yaragar
    (party_set_slot, "p_village_3", slot_center_fishing_fleet, 15), #Azgad
    (party_set_slot, "p_village_5", slot_center_fishing_fleet, 15), #Kulum
	
    (party_set_slot, "p_village_8", slot_center_fishing_fleet, 15), #Haen
    (party_set_slot, "p_village_9", slot_center_fishing_fleet, 15), #Buvran

    (party_set_slot, "p_village_20", slot_center_fishing_fleet, 15), #Uslum
    (party_set_slot, "p_village_21", slot_center_fishing_fleet, 15), #Bazeck
    (party_set_slot, "p_village_23", slot_center_fishing_fleet, 15), #Ilvia
    (party_set_slot, "p_village_27", slot_center_fishing_fleet, 15), #Glunmar

    (party_set_slot, "p_village_30", slot_center_fishing_fleet, 20), #Ruvar
    (party_set_slot, "p_village_31", slot_center_fishing_fleet, 15), #Ambean
    (party_set_slot, "p_village_35", slot_center_fishing_fleet, 15), #Feacharin
	
    (party_set_slot, "p_village_47", slot_center_fishing_fleet, 15), #Epeshe
    (party_set_slot, "p_village_49", slot_center_fishing_fleet, 15), #Tismirr

    (party_set_slot, "p_village_51", slot_center_fishing_fleet, 15), #Jelbegi
    (party_set_slot, "p_village_56", slot_center_fishing_fleet, 15), #Fenada

    (party_set_slot, "p_village_66", slot_center_fishing_fleet, 15), #Fisdnar
#    (party_set_slot, "p_village_67", slot_center_fishing_fleet, 15), #Tebandra
    (party_set_slot, "p_village_68", slot_center_fishing_fleet, 15), #Ibdeles
    (party_set_slot, "p_village_69", slot_center_fishing_fleet, 15), #Kwynn

    (party_set_slot, "p_village_77", slot_center_fishing_fleet, 25), #Rizi - Estuary
    (party_set_slot, "p_village_79", slot_center_fishing_fleet, 15), #Istiniar

	(party_set_slot, "p_village_81", slot_center_fishing_fleet, 15), #Odasan
    (party_set_slot, "p_village_85", slot_center_fishing_fleet, 15), #Ismirala
    (party_set_slot, "p_village_87", slot_center_fishing_fleet, 15), #Udiniad
	
    (party_set_slot, "p_village_90", slot_center_fishing_fleet, 15), #Jamiche
	
#   (party_set_slot, "p_village_18", slot_center_fishing_fleet, 20), #Ulburban
#    (party_set_slot, "p_village_26", slot_center_fishing_fleet, 20), #Pagundur
#    (party_set_slot, "p_village_36", slot_center_fishing_fleet, 25), #Jayek

	#Initialize pastureland
	(try_for_range, ":center", centers_begin, centers_end),
		(party_get_slot, ":head_cattle", ":center", slot_center_head_cattle),
		(party_get_slot, ":head_sheep", ":center", slot_center_head_sheep),
		(store_mul, ":num_acres", ":head_cattle", 4),
		(val_add, ":num_acres", ":head_sheep"), 
		(val_add, ":num_acres", ":head_sheep"), 
		(val_mul, ":num_acres", 6),
		(val_div, ":num_acres", 5),
		(party_set_slot, ":center", slot_center_acres_pasture, ":num_acres"),
		
	(try_end),
	  
	#Initialize prices based on production, etc
    (try_for_range, ":unused", 0, 15), #15 cycles = 45 days. For a village with -20 production, this should lead to approximate +1000, modified
        (call_script, "script_update_trade_good_prices"), #changes prices based on production
        (call_script, "script_update_trade_good_prices"), 
        (call_script, "script_update_trade_good_prices"), 
		
		(call_script, "script_average_trade_good_prices"), #Conduct virtual trade  twice    
		(call_script, "script_average_trade_good_prices"), 
		
    (try_end),
	  
	#Initialize prosperity based on final prices
    (try_for_range, ":center_no", centers_begin, centers_end),
      (neg|is_between, ":center_no", castles_begin, castles_end),
      (store_random_in_range, ":random_prosperity_adder", -10, 10),
      (call_script, "script_get_center_ideal_prosperity", ":center_no"),
      (assign, ":prosperity", reg0),
      (val_add, ":prosperity", ":random_prosperity_adder"),
      (val_clamp, ":prosperity", 0, 100),
      (party_set_slot, ":center_no", slot_town_prosperity, ":prosperity"),                
	(try_end),
	
	(call_script, "script_calculate_castle_prosperities_by_using_its_villages"),
    ]),
	 
  #script_initialize_all_scene_prop_slots
  # INPUT: arg1 = scene_prop_no
  # OUTPUT: none
  ("initialize_all_scene_prop_slots",
   [
     (call_script, "script_initialize_scene_prop_slots", "spr_siege_ladder_move_6m"),
     (call_script, "script_initialize_scene_prop_slots", "spr_siege_ladder_move_8m"),
     (call_script, "script_initialize_scene_prop_slots", "spr_siege_ladder_move_10m"),
     (call_script, "script_initialize_scene_prop_slots", "spr_siege_ladder_move_12m"),
     (call_script, "script_initialize_scene_prop_slots", "spr_siege_ladder_move_14m"),
     (call_script, "script_initialize_scene_prop_slots", "spr_castle_e_sally_door_a"),
     (call_script, "script_initialize_scene_prop_slots", "spr_castle_f_sally_door_a"),
     (call_script, "script_initialize_scene_prop_slots", "spr_earth_sally_gate_left"),
     (call_script, "script_initialize_scene_prop_slots", "spr_earth_sally_gate_right"),
     (call_script, "script_initialize_scene_prop_slots", "spr_viking_keep_destroy_sally_door_left"),
     (call_script, "script_initialize_scene_prop_slots", "spr_viking_keep_destroy_sally_door_right"),
     (call_script, "script_initialize_scene_prop_slots", "spr_castle_f_door_a"),
     (call_script, "script_initialize_scene_prop_slots", "spr_belfry_a"),
     (call_script, "script_initialize_scene_prop_slots", "spr_belfry_b"),
     (call_script, "script_initialize_scene_prop_slots", "spr_winch_b"),
    ]),

  #script_initialize_scene_prop_slots
  # INPUT: arg1 = scene_prop_no
  # OUTPUT: none
  ("initialize_scene_prop_slots",
   [
     (store_script_param, ":scene_prop_no", 1),

     (scene_prop_get_num_instances, ":num_instances_of_scene_prop", ":scene_prop_no"),     
     (try_for_range, ":cur_instance", 0, ":num_instances_of_scene_prop"),
       (scene_prop_get_instance, ":cur_instance_id", ":scene_prop_no", ":cur_instance"),
       (try_for_range, ":cur_slot", 0, scene_prop_slots_end),
         (scene_prop_set_slot, ":cur_instance_id", ":cur_slot", 0),
       (try_end),
     (try_end),
     ]),
  
  #script_use_item
  # INPUT: arg1 = agent_id, arg2 = instance_id
  # OUTPUT: none
  ("use_item",
   [
     (store_script_param, ":instance_id", 1),
     (store_script_param, ":user_id", 2),

     (try_begin),
       (game_in_multiplayer_mode),
       (prop_instance_get_scene_prop_kind, ":scene_prop_id", ":instance_id"),
       (eq, ":scene_prop_id", "spr_winch_b"),
                      
       (multiplayer_get_my_player, ":my_player_no"),

       (this_or_next|gt, ":my_player_no", 0),
       (neg|multiplayer_is_dedicated_server),

       (ge, ":my_player_no", 0),
       (player_get_agent_id, ":my_agent_id", ":my_player_no"),
       (ge, ":my_agent_id", 0),
       (agent_is_active, ":my_agent_id"),
       (agent_get_team, ":my_team_no", ":my_agent_id"),
       (eq, ":my_team_no", 0),
                             
       (scene_prop_get_slot, ":opened_or_closed", ":instance_id", scene_prop_open_or_close_slot),
       (ge, ":user_id", 0),
       (agent_is_active, ":user_id"),
       (agent_get_player_id, ":user_player", ":user_id"),
       (str_store_player_username, s7, ":user_player"),
            
       (try_begin),
         (eq, ":opened_or_closed", 0),
         (display_message, "@{s7} opened the gate"),
       (else_try),  
         (display_message, "@{s7} closed the gate"),
       (try_end),
     (try_end),  

     (prop_instance_get_scene_prop_kind, ":scene_prop_id", ":instance_id"),
     
     (try_begin),
       (this_or_next|eq, ":scene_prop_id", "spr_winch_b"),
       (eq, ":scene_prop_id", "spr_winch"),
       (assign, ":effected_object", "spr_portcullis"),
     (else_try),
       (this_or_next|eq, ":scene_prop_id", "spr_door_destructible"),
       (this_or_next|eq, ":scene_prop_id", "spr_castle_f_door_b"),
       (this_or_next|eq, ":scene_prop_id", "spr_castle_e_sally_door_a"),
       (this_or_next|eq, ":scene_prop_id", "spr_castle_f_sally_door_a"),
       (this_or_next|eq, ":scene_prop_id", "spr_earth_sally_gate_left"),
       (this_or_next|eq, ":scene_prop_id", "spr_earth_sally_gate_right"),
       (this_or_next|eq, ":scene_prop_id", "spr_viking_keep_destroy_sally_door_left"),
       (this_or_next|eq, ":scene_prop_id", "spr_viking_keep_destroy_sally_door_right"),
       (this_or_next|eq, ":scene_prop_id", "spr_castle_f_door_a"),
       (this_or_next|eq, ":scene_prop_id", "spr_siege_ladder_move_6m"),
       (this_or_next|eq, ":scene_prop_id", "spr_siege_ladder_move_8m"),
       (this_or_next|eq, ":scene_prop_id", "spr_siege_ladder_move_10m"),
       (this_or_next|eq, ":scene_prop_id", "spr_siege_ladder_move_12m"),
       (eq, ":scene_prop_id", "spr_siege_ladder_move_14m"),
       (assign, ":effected_object", ":scene_prop_id"),
     (try_end),

     (assign, ":smallest_dist", -1),
     (prop_instance_get_position, pos0, ":instance_id"),
     (scene_prop_get_num_instances, ":num_instances_of_effected_object", ":effected_object"),     
     (try_for_range, ":cur_instance", 0, ":num_instances_of_effected_object"),
       (scene_prop_get_instance, ":cur_instance_id", ":effected_object", ":cur_instance"),
       (prop_instance_get_position, pos1, ":cur_instance_id"),
       (get_sq_distance_between_positions, ":dist", pos0, pos1),
       (this_or_next|eq, ":smallest_dist", -1),
       (lt, ":dist", ":smallest_dist"),
       (assign, ":smallest_dist", ":dist"),
       (assign, ":effected_object_instance_id", ":cur_instance_id"),
     (try_end),

     (try_begin),
       (ge, ":instance_id", 0),
       (ge, ":smallest_dist", 0),

       (try_begin),     
         (eq, ":effected_object", "spr_portcullis"),
         (scene_prop_get_slot, ":opened_or_closed", ":instance_id", scene_prop_open_or_close_slot),

         (try_begin),
           (eq, ":opened_or_closed", 0), #open gate
     
           (scene_prop_enable_after_time, ":instance_id", 400), #4 seconds
           (try_begin),
             (this_or_next|multiplayer_is_server),
             (neg|game_in_multiplayer_mode),
             (prop_instance_get_position, pos0, ":effected_object_instance_id"),
             (position_move_z, pos0, 375),
             (prop_instance_animate_to_position, ":effected_object_instance_id", pos0, 400),
           (try_end),
           (scene_prop_set_slot, ":instance_id", scene_prop_open_or_close_slot, 1),

           (try_begin),
             (eq, ":scene_prop_id", "spr_winch_b"),
             (this_or_next|multiplayer_is_server),
             (neg|game_in_multiplayer_mode),
             (prop_instance_get_position, pos1, ":instance_id"),
             (prop_instance_rotate_to_position, ":instance_id", pos1, 400, 72000),
           (try_end),
         (else_try), #close gate     
           (scene_prop_enable_after_time, ":instance_id", 400), #4 seconds
           (try_begin),
             (this_or_next|multiplayer_is_server),
             (neg|game_in_multiplayer_mode),
             (prop_instance_get_position, pos0, ":effected_object_instance_id"),
             (position_move_z, pos0, -375),
             (prop_instance_animate_to_position, ":effected_object_instance_id", pos0, 400),
           (try_end),
           (scene_prop_set_slot, ":instance_id", scene_prop_open_or_close_slot, 0),

           (try_begin),
             (eq, ":scene_prop_id", "spr_winch_b"),
             (this_or_next|multiplayer_is_server),
             (neg|game_in_multiplayer_mode),
             (prop_instance_get_position, pos1, ":instance_id"),
             (prop_instance_rotate_to_position, ":instance_id", pos1, 400, -72000),
           (try_end),
         (try_end),
       (else_try),
         (this_or_next|eq, ":effected_object", "spr_siege_ladder_move_6m"),
         (this_or_next|eq, ":effected_object", "spr_siege_ladder_move_8m"),
         (this_or_next|eq, ":effected_object", "spr_siege_ladder_move_10m"),
         (this_or_next|eq, ":effected_object", "spr_siege_ladder_move_12m"),
         (eq, ":effected_object", "spr_siege_ladder_move_14m"),

         (try_begin),
           (eq, ":effected_object", "spr_siege_ladder_move_6m"),
           (assign, ":animation_time_drop", 120),
           (assign, ":animation_time_elevate", 240),
         (else_try),
           (eq, ":effected_object", "spr_siege_ladder_move_8m"),
           (assign, ":animation_time_drop", 140),
           (assign, ":animation_time_elevate", 280),
         (else_try),
           (eq, ":effected_object", "spr_siege_ladder_move_10m"),
           (assign, ":animation_time_drop", 160),
           (assign, ":animation_time_elevate", 320),
         (else_try),
           (eq, ":effected_object", "spr_siege_ladder_move_12m"),
           (assign, ":animation_time_drop", 190),
           (assign, ":animation_time_elevate", 360),
         (else_try),
           (eq, ":effected_object", "spr_siege_ladder_move_14m"),
           (assign, ":animation_time_drop", 230),
           (assign, ":animation_time_elevate", 400),
         (try_end),
     
         (scene_prop_get_slot, ":opened_or_closed", ":instance_id", scene_prop_open_or_close_slot),

         (try_begin),
           (scene_prop_enable_after_time, ":effected_object_instance_id", ":animation_time_elevate"), #3 seconds in average
           (eq, ":opened_or_closed", 0), #ladder at ground           
           (prop_instance_get_starting_position, pos0, ":effected_object_instance_id"),
           (prop_instance_enable_physics, ":effected_object_instance_id", 0),
           (prop_instance_animate_to_position, ":effected_object_instance_id", pos0, 300),
           (scene_prop_set_slot, ":effected_object_instance_id", scene_prop_open_or_close_slot, 1), 
         (else_try), #ladder at wall
           (scene_prop_enable_after_time, ":effected_object_instance_id", ":animation_time_drop"), #1.5 seconds in average
           (prop_instance_get_position, pos0, ":instance_id"),

           (assign, ":smallest_dist", -1),
           (try_for_range, ":entry_point_no", multi_entry_points_for_usable_items_start, multi_entry_points_for_usable_items_end),
             (entry_point_get_position, pos1, ":entry_point_no"),
             (get_sq_distance_between_positions, ":dist", pos0, pos1),
             (this_or_next|eq, ":smallest_dist", -1),
             (lt, ":dist", ":smallest_dist"),
             (assign, ":smallest_dist", ":dist"),
             (assign, ":nearest_entry_point", ":entry_point_no"),
           (try_end),

           (try_begin),
             (ge, ":smallest_dist", 0),
             (lt, ":smallest_dist", 22500), #max 15m distance
             (entry_point_get_position, pos1, ":nearest_entry_point"),
             (position_rotate_x, pos1, -90),
             (scene_prop_set_slot, ":effected_object_instance_id", scene_prop_smoke_effect_done, 0),
             (prop_instance_enable_physics, ":effected_object_instance_id", 0),
             (prop_instance_animate_to_position, ":effected_object_instance_id", pos1, 130),
           (try_end),

           (scene_prop_set_slot, ":effected_object_instance_id", scene_prop_open_or_close_slot, 0),
         (try_end),
       (else_try),
         (this_or_next|eq, ":effected_object", "spr_door_destructible"),
         (this_or_next|eq, ":effected_object", "spr_castle_f_door_b"),
         (this_or_next|eq, ":scene_prop_id", "spr_castle_e_sally_door_a"),     
         (this_or_next|eq, ":scene_prop_id", "spr_castle_f_sally_door_a"),     
         (this_or_next|eq, ":scene_prop_id", "spr_earth_sally_gate_left"),     
         (this_or_next|eq, ":scene_prop_id", "spr_earth_sally_gate_right"),     
         (this_or_next|eq, ":scene_prop_id", "spr_viking_keep_destroy_sally_door_left"),     
         (this_or_next|eq, ":scene_prop_id", "spr_viking_keep_destroy_sally_door_right"),     
         (eq, ":scene_prop_id", "spr_castle_f_door_a"),
     
         (assign, ":effected_object_instance_id", ":instance_id"),
         (scene_prop_get_slot, ":opened_or_closed", ":effected_object_instance_id", scene_prop_open_or_close_slot),

         (try_begin),
           (eq, ":opened_or_closed", 0),

           (prop_instance_get_starting_position, pos0, ":effected_object_instance_id"),

           (scene_prop_enable_after_time, ":effected_object_instance_id", 100),

           (try_begin),
             (neg|eq, ":scene_prop_id", "spr_viking_keep_destroy_sally_door_left"),
             (neg|eq, ":scene_prop_id", "spr_earth_sally_gate_left"),
             
             (position_rotate_z, pos0, -85),
           (else_try),  
             (position_rotate_z, pos0, 85),
           (try_end),
           
           (prop_instance_animate_to_position, ":effected_object_instance_id", pos0, 100),
          
           (scene_prop_set_slot, ":effected_object_instance_id", scene_prop_open_or_close_slot, 1),
         (else_try),          
           (prop_instance_get_starting_position, pos0, ":effected_object_instance_id"),

           (scene_prop_enable_after_time, ":effected_object_instance_id", 100),

           (prop_instance_animate_to_position, ":effected_object_instance_id", pos0, 100),

           (scene_prop_set_slot, ":effected_object_instance_id", scene_prop_open_or_close_slot, 0),
         (try_end),
       (try_end),
     (try_end),
     ]),

  #script_determine_team_flags
  # INPUT: none
  # OUTPUT: none
  ("determine_team_flags",
   [
     (store_script_param, ":team_no", 1),          

     (try_begin),       
       (eq, "$g_multiplayer_game_type", multiplayer_game_type_capture_the_flag),
       
       (try_begin),
         (eq, ":team_no", 0),
     
         (team_get_faction, ":team_faction_no", 0),
         (try_begin),
           (eq, ":team_faction_no", "fac_kingdom_1"),   
           (assign, "$team_1_flag_scene_prop", "spr_ctf_flag_kingdom_1"),
         (else_try),
           (eq, ":team_faction_no", "fac_kingdom_2"),
           (assign, "$team_1_flag_scene_prop", "spr_ctf_flag_kingdom_2"),
         (else_try),
           (eq, ":team_faction_no", "fac_kingdom_3"), 
           (assign, "$team_1_flag_scene_prop", "spr_ctf_flag_kingdom_3"),
         (else_try),
           (eq, ":team_faction_no", "fac_kingdom_4"),
           (assign, "$team_1_flag_scene_prop", "spr_ctf_flag_kingdom_4"),
         (else_try),
           (eq, ":team_faction_no", "fac_kingdom_5"),
           (assign, "$team_1_flag_scene_prop", "spr_ctf_flag_kingdom_5"),
         (else_try),
           (eq, ":team_faction_no", "fac_kingdom_6"),
           (assign, "$team_1_flag_scene_prop", "spr_ctf_flag_kingdom_6"),
         (try_end),
       (else_try),
         (team_get_faction, ":team_faction_no", 1),
         (try_begin),    
           (eq, ":team_faction_no", "fac_kingdom_1"),   
           (assign, "$team_2_flag_scene_prop", "spr_ctf_flag_kingdom_1"),
         (else_try),
           (eq, ":team_faction_no", "fac_kingdom_2"),
           (assign, "$team_2_flag_scene_prop", "spr_ctf_flag_kingdom_2"),
         (else_try),
           (eq, ":team_faction_no", "fac_kingdom_3"),
           (assign, "$team_2_flag_scene_prop", "spr_ctf_flag_kingdom_3"),
         (else_try),
           (eq, ":team_faction_no", "fac_kingdom_4"),
           (assign, "$team_2_flag_scene_prop", "spr_ctf_flag_kingdom_4"),
         (else_try),
           (eq, ":team_faction_no", "fac_kingdom_5"),
           (assign, "$team_2_flag_scene_prop", "spr_ctf_flag_kingdom_5"),
         (else_try),
           (eq, ":team_faction_no", "fac_kingdom_6"),
           (assign, "$team_2_flag_scene_prop", "spr_ctf_flag_kingdom_6"),
         (try_end),  
       
         (try_begin),       
           (eq, "$team_1_flag_scene_prop", "$team_2_flag_scene_prop"),
           (assign, "$team_2_flag_scene_prop", "spr_ctf_flag_kingdom_7"),
         (try_end),
       (try_end),
     (else_try),  
       (try_begin),
         (eq, ":team_no", 0),
     
         (team_get_faction, ":team_faction_no", 0),
         (try_begin),
           (eq, ":team_faction_no", "fac_kingdom_1"),   
           (assign, "$team_1_flag_scene_prop", "spr_headquarters_flag_swadian"),
         (else_try),
           (eq, ":team_faction_no", "fac_kingdom_2"),
           (assign, "$team_1_flag_scene_prop", "spr_headquarters_flag_vaegir"),
         (else_try),
           (eq, ":team_faction_no", "fac_kingdom_3"), 
           (assign, "$team_1_flag_scene_prop", "spr_headquarters_flag_khergit"),
         (else_try),
           (eq, ":team_faction_no", "fac_kingdom_4"),
           (assign, "$team_1_flag_scene_prop", "spr_headquarters_flag_nord"),
         (else_try),
           (eq, ":team_faction_no", "fac_kingdom_5"),
           (assign, "$team_1_flag_scene_prop", "spr_headquarters_flag_rhodok"),
         (else_try),
           (eq, ":team_faction_no", "fac_kingdom_6"),
           (assign, "$team_1_flag_scene_prop", "spr_headquarters_flag_sarranid"),
         (try_end),
       (else_try),
         (team_get_faction, ":team_faction_no", 1),
         (try_begin),    
           (eq, ":team_faction_no", "fac_kingdom_1"),   
           (assign, "$team_2_flag_scene_prop", "spr_headquarters_flag_swadian"),
         (else_try),
           (eq, ":team_faction_no", "fac_kingdom_2"),
           (assign, "$team_2_flag_scene_prop", "spr_headquarters_flag_vaegir"),
         (else_try),
           (eq, ":team_faction_no", "fac_kingdom_3"),
           (assign, "$team_2_flag_scene_prop", "spr_headquarters_flag_khergit"),
         (else_try),
           (eq, ":team_faction_no", "fac_kingdom_4"),
           (assign, "$team_2_flag_scene_prop", "spr_headquarters_flag_nord"),
         (else_try),
           (eq, ":team_faction_no", "fac_kingdom_5"),
           (assign, "$team_2_flag_scene_prop", "spr_headquarters_flag_rhodok"),
         (else_try),
           (eq, ":team_faction_no", "fac_kingdom_6"),
           (assign, "$team_2_flag_scene_prop", "spr_headquarters_flag_sarranid"),
         (try_end),  
       
         (try_begin),       
           (eq, "$team_1_flag_scene_prop", "$team_2_flag_scene_prop"),
           (assign, "$team_2_flag_scene_prop", "spr_headquarters_flag_rebel"),
         (try_end),
       (try_end),
     (try_end),
   ]),
   

  #script_calculate_flag_move_time
  # INPUT: arg1 = number_of_total_agents_around_flag, arg2 = dist_between_flag_and_its_pole
  # OUTPUT: reg0 = flag move time
  ("calculate_flag_move_time",
   [
     (store_script_param, ":number_of_total_agents_around_flag", 1),
     (store_script_param, ":dist_between_flag_and_its_target", 2),

     (try_begin), #(if no one is around flag it again moves to its current owner situation but 5 times slower than normal)
       (eq, ":number_of_total_agents_around_flag", 0),
       (store_mul, reg0, ":dist_between_flag_and_its_target", 2500),#5.00 * 1.00 * (500 stable) = 2000 
     (else_try),
       (eq, ":number_of_total_agents_around_flag", 1),
       (store_mul, reg0, ":dist_between_flag_and_its_target", 500), #1.00 * (500 stable) = 500
     (else_try),
       (eq, ":number_of_total_agents_around_flag", 2),
       (store_mul, reg0, ":dist_between_flag_and_its_target", 300), #0.60(0.60) * (500 stable) = 300
     (else_try),
       (eq, ":number_of_total_agents_around_flag", 3),
       (store_mul, reg0, ":dist_between_flag_and_its_target", 195), #0.39(0.60 * 0.65) * (500 stable) = 195
     (else_try),
       (eq, ":number_of_total_agents_around_flag", 4),
       (store_mul, reg0, ":dist_between_flag_and_its_target", 137), #0.273(0.60 * 0.65 * 0.70) * (500 stable) = 136.5 >rounding> 137
     (else_try),
       (eq, ":number_of_total_agents_around_flag", 5),
       (store_mul, reg0, ":dist_between_flag_and_its_target", 102), #0.20475(0.60 * 0.65 * 0.70 * 0.75) * (500 stable) = 102.375 >rounding> 102
     (else_try),
       (eq, ":number_of_total_agents_around_flag", 6),
       (store_mul, reg0, ":dist_between_flag_and_its_target", 82),  #0.1638(0.60 * 0.65 * 0.70 * 0.75 * 0.80) * (500 stable) = 81.9 >rounding> 82
     (else_try),
       (eq, ":number_of_total_agents_around_flag", 7),
       (store_mul, reg0, ":dist_between_flag_and_its_target", 66),  #0.13104(0.60 * 0.65 * 0.70 * 0.75 * 0.80 * 0.85) * (500 stable) = 65.52 >rounding> 66
     (else_try),
       (eq, ":number_of_total_agents_around_flag", 8),
       (store_mul, reg0, ":dist_between_flag_and_its_target", 59),  #0.117936(0.60 * 0.65 * 0.70 * 0.75 * 0.80 * 0.85 * 0.90) * (500 stable) = 58.968 >rounding> 59
     (else_try),
       (store_mul, reg0, ":dist_between_flag_and_its_target", 56),  #0.1120392(0.60 * 0.65 * 0.70 * 0.75 * 0.80 * 0.85 * 0.90 * 0.95) * (500 stable) = 56.0196 >rounding> 56
     (try_end), 

     (assign, ":number_of_players", 0),
     (get_max_players, ":num_players"),                               
     (try_for_range, ":cur_player", 0, ":num_players"),
       (player_is_active, ":cur_player"),
       (val_add, ":number_of_players", 1),
     (try_end),

     (try_begin),
       (lt, ":number_of_players", 10),
       (val_mul, reg0, 50),
     (else_try),
       (lt, ":number_of_players", 35),
       (store_sub, ":number_of_players_multipication", 35, ":number_of_players"),
       (val_mul, ":number_of_players_multipication", 2),
       (store_sub, ":number_of_players_multipication", 100, ":number_of_players_multipication"),
       (val_mul, reg0, ":number_of_players_multipication"),
     (else_try),
       (val_mul, reg0, 100),
     (try_end),

     (try_begin),
       (eq, "$g_multiplayer_game_type", multiplayer_game_type_siege),
       (val_mul, reg0, 2),
     (try_end),

     (val_div, reg0, 10000), #100x for number of players around flag, 100x for number of players in game
     ]),

  #script_move_death_mode_flags_down
  # INPUT: none
  # OUTPUT: none
  ("move_death_mode_flags_down",
   [
     (try_begin),
       (scene_prop_get_instance, ":pole_1_id", "spr_headquarters_pole_code_only", 0),
       (prop_instance_get_position, pos0, ":pole_1_id"),
       (position_move_z, pos0, -2000), 
       (prop_instance_set_position, ":pole_1_id", pos0),
     (try_end),

     (try_begin),
       (scene_prop_get_instance, ":pole_2_id", "spr_headquarters_pole_code_only", 1),
       (prop_instance_get_position, pos1, ":pole_2_id"),
       (position_move_z, pos1, -2000), 
       (prop_instance_set_position, ":pole_2_id", pos1),
     (try_end),
    
     (try_begin),
       (scene_prop_get_instance, ":pole_1_id", "spr_headquarters_pole_code_only", 0),
       (prop_instance_get_position, pos0, ":pole_1_id"),
       (scene_prop_get_instance, ":flag_1_id", "$team_1_flag_scene_prop", 0),
       (prop_instance_stop_animating, ":flag_1_id"),
       (position_move_z, pos0, multi_headquarters_flag_initial_height),
       (prop_instance_set_position, ":flag_1_id", pos0),
     (try_end),

     (try_begin),
       (scene_prop_get_instance, ":pole_2_id", "spr_headquarters_pole_code_only", 1),
       (prop_instance_get_position, pos1, ":pole_2_id"),
       (scene_prop_get_instance, ":flag_2_id", "$team_2_flag_scene_prop", 0),
       (prop_instance_stop_animating, ":flag_2_id"),
       (position_move_z, pos1, multi_headquarters_flag_initial_height),
       (prop_instance_set_position, ":flag_2_id", pos1),
     (try_end),
   ]),

  #script_move_flag
  # INPUT: arg1 = shown_flag_id, arg2 = move time in seconds, pos0 = target position
  # OUTPUT: none
  ("move_flag",
   [
     (store_script_param, ":shown_flag_id", 1),
     (store_script_param, ":shown_flag_move_time", 2),

     (try_begin),
       (multiplayer_is_server), #added after auto-animating
     
       (try_begin),
         (eq, ":shown_flag_move_time", 0), #stop
         (prop_instance_stop_animating, ":shown_flag_id"),
       (else_try),
         (prop_instance_animate_to_position, ":shown_flag_id", pos0, ":shown_flag_move_time"),
       (try_end),
     (try_end),
   ]),

  #script_move_headquarters_flags
  # INPUT: arg1 = current_owner, arg2 = number_of_agents_around_flag_team_1, arg3 = number_of_agents_around_flag_team_2
  # OUTPUT: none
  ("move_headquarters_flags",
   [
     (store_script_param, ":flag_no", 1),
     (store_script_param, ":number_of_agents_around_flag_team_1", 2),
     (store_script_param, ":number_of_agents_around_flag_team_2", 3),

     (store_add, ":cur_flag_slot", multi_data_flag_owner_begin, ":flag_no"),
     (troop_get_slot, ":current_owner", "trp_multiplayer_data", ":cur_flag_slot"),

     (scene_prop_get_num_instances, ":num_instances", "spr_headquarters_flag_gray_code_only"),
     (try_begin),
       (assign, ":visibility", 0),
       (lt, ":flag_no", ":num_instances"),
       (scene_prop_get_instance, ":flag_id", "spr_headquarters_flag_gray_code_only", ":flag_no"),
       (scene_prop_get_visibility, ":visibility", ":flag_id"),
     (try_end),

     (try_begin),
       (eq, ":visibility", 1),
       (assign, ":shown_flag", 0),
       (assign, ":shown_flag_id", ":flag_id"),
     (else_try),
       (scene_prop_get_num_instances, ":num_instances", "$team_1_flag_scene_prop"),
       (try_begin),
         (assign, ":visibility", 0),
         (lt, ":flag_no", ":num_instances"),
         (scene_prop_get_instance, ":flag_id", "$team_1_flag_scene_prop", ":flag_no"),
         (scene_prop_get_visibility, ":visibility", ":flag_id"),
       (try_end),

       #(scene_prop_get_instance, ":flag_id", "$team_1_flag_scene_prop", ":flag_no"),
       #(scene_prop_get_visibility, ":visibility", ":flag_id"),       
       (try_begin),
         (eq, ":visibility", 1),
         (assign, ":shown_flag", 1),
         (assign, ":shown_flag_id", ":flag_id"),
       (else_try),
         (scene_prop_get_num_instances, ":num_instances", "$team_2_flag_scene_prop"),
         (try_begin),
           (assign, ":visibility", 0),
           (lt, ":flag_no", ":num_instances"),
           (scene_prop_get_instance, ":flag_id", "$team_2_flag_scene_prop", ":flag_no"),
           (scene_prop_get_visibility, ":visibility", ":flag_id"),
         (try_end),

         #(scene_prop_get_instance, ":flag_id", "$team_2_flag_scene_prop", ":flag_no"),
         #(scene_prop_get_visibility, ":visibility", ":flag_id"),              
         (try_begin),
           (eq, ":visibility", 1),
           (assign, ":shown_flag", 2),
           (assign, ":shown_flag_id", ":flag_id"),
         (try_end),
       (try_end),
     (try_end),

     (try_begin),
       (scene_prop_get_instance, ":pole_id", "spr_headquarters_pole_code_only", ":flag_no"),
     (try_end),

     (try_begin),       
       (eq, ":shown_flag", ":current_owner"), #situation 1 : (current owner is equal shown flag)
       (try_begin),
         (ge, ":number_of_agents_around_flag_team_1", 1),
         (ge, ":number_of_agents_around_flag_team_2", 1),         
         (assign, ":flag_movement", 0), #0:stop
       (else_try),  
         (eq, ":number_of_agents_around_flag_team_1", 0),
         (eq, ":number_of_agents_around_flag_team_2", 0),
         (assign, ":flag_movement", 1), #1:rise (slow)
       (else_try),
         (try_begin),
           (ge, ":number_of_agents_around_flag_team_1", 1),
           (eq, ":number_of_agents_around_flag_team_2", 0),
           (eq, ":current_owner", 1),
           (assign, ":flag_movement", 1), #1:rise (fast)
         (else_try),
           (eq, ":number_of_agents_around_flag_team_1", 0),
           (ge, ":number_of_agents_around_flag_team_2", 1),
           (eq, ":current_owner", 2),
           (assign, ":flag_movement", 1), #1:rise (fast)
         (else_try),
           (assign, ":flag_movement", -1), #-1:drop (fast)
         (try_end),
       (try_end),
     (else_try), #situation 2 : (current owner is different than shown flag)
       (try_begin),
         (ge, ":number_of_agents_around_flag_team_1", 1),
         (ge, ":number_of_agents_around_flag_team_2", 1),
         (assign, ":flag_movement", 0), #0:stop
       (else_try),  
         (eq, ":number_of_agents_around_flag_team_1", 0),
         (eq, ":number_of_agents_around_flag_team_2", 0),
         (assign, ":flag_movement", -1), #-1:drop (slow)
       (else_try),
         (try_begin),
           (ge, ":number_of_agents_around_flag_team_1", 1),
           (eq, ":number_of_agents_around_flag_team_2", 0),
           (try_begin),
             (eq, ":shown_flag", 1),
             (assign, ":flag_movement", 1), #1:rise (fast)
           (else_try),
             (neq, ":current_owner", 1),
             (assign, ":flag_movement", -1), #-1:drop (fast)
           (try_end),
         (else_try),
           (eq, ":number_of_agents_around_flag_team_1", 0),
           (ge, ":number_of_agents_around_flag_team_2", 1),
           (try_begin),
             (eq, ":shown_flag", 2),
             (assign, ":flag_movement", 1), #1:rise (fast)
           (else_try),
             (neq, ":current_owner", 2),
             (assign, ":flag_movement", -1), #-1:drop (fast)
           (try_end),
         (try_end),
       (try_end),
     (try_end),

     (store_add, ":number_of_total_agents_around_flag", ":number_of_agents_around_flag_team_1", ":number_of_agents_around_flag_team_2"),

     (try_begin),
       (eq, ":flag_movement", 0),
       (assign, reg0, 0),
     (else_try),
       (eq, ":flag_movement", 1),
       (prop_instance_get_position, pos1, ":shown_flag_id"),
       (prop_instance_get_position, pos0, ":pole_id"),
       (position_move_z, pos0, multi_headquarters_pole_height),
       (get_distance_between_positions, ":dist_between_flag_and_its_target", pos0, pos1),
       (call_script, "script_calculate_flag_move_time", ":number_of_total_agents_around_flag", ":dist_between_flag_and_its_target"),
     (else_try),  
       (eq, ":flag_movement", -1),
       (prop_instance_get_position, pos1, ":shown_flag_id"),
       (prop_instance_get_position, pos0, ":pole_id"),
       (get_distance_between_positions, ":dist_between_flag_and_its_target", pos0, pos1),
       (call_script, "script_calculate_flag_move_time", ":number_of_total_agents_around_flag", ":dist_between_flag_and_its_target"),
     (try_end),

     (call_script, "script_move_flag", ":shown_flag_id", reg0), #pos0 : target position
     ]),

  #script_set_num_agents_around_flag
  # INPUT: arg1 = flag_no, arg2 = owner_code
  # OUTPUT: none
  ("set_num_agents_around_flag",
   [
     (store_script_param, ":flag_no", 1),
     (store_script_param, ":current_owner_code", 2),

     (store_div, ":number_of_agents_around_flag_team_1", ":current_owner_code", 100),
     (store_mod, ":number_of_agents_around_flag_team_2", ":current_owner_code", 100),

     (store_add, ":cur_flag_owner_counts_slot", multi_data_flag_players_around_begin, ":flag_no"),
     (troop_set_slot, "trp_multiplayer_data", ":cur_flag_owner_counts_slot", ":current_owner_code"),

     (call_script, "script_move_headquarters_flags", ":flag_no", ":number_of_agents_around_flag_team_1", ":number_of_agents_around_flag_team_2"),
  ]),
  
  #script_change_flag_owner
  # INPUT: arg1 = flag_no, arg2 = owner_code
  # OUTPUT: none
  ("change_flag_owner",
   [
     (store_script_param, ":flag_no", 1),
     (store_script_param, ":owner_code", 2),

     (try_begin),
       (lt, ":owner_code", 0),
       (val_add, ":owner_code", 1),
       (val_mul, ":owner_code", -1),
     (try_end),
  
     (store_div, ":owner_team_no", ":owner_code", 100),
     (store_mod, ":shown_flag_no", ":owner_code", 100),
  
     (store_add, ":cur_flag_slot", multi_data_flag_owner_begin, ":flag_no"),
     (troop_get_slot, ":older_owner_team_no", "trp_multiplayer_data", ":cur_flag_slot"),

     (store_add, ":cur_flag_slot", multi_data_flag_owner_begin, ":flag_no"),
     (troop_set_slot, "trp_multiplayer_data", ":cur_flag_slot", ":owner_team_no"),

     #senchronizing flag positions
     (try_begin),
       #(this_or_next|eq, ":initial_flags", 0), #moved after auto-animating
       (multiplayer_is_server),

       (scene_prop_get_instance, ":pole_id", "spr_headquarters_pole_code_only", ":flag_no"),
       (try_begin),
         (eq, ":owner_team_no", 0), #if new owner team is 0 then flags are at bottom
         (neq, ":older_owner_team_no", -1), #clients
         (assign, ":continue", 1),
         (try_begin),
           (multiplayer_is_server),
           (eq, "$g_placing_initial_flags", 1),
           (assign, ":continue", 0),
         (try_end),
         (eq, ":continue", 1),
         (prop_instance_get_position, pos0, ":pole_id"),
         (position_move_z, pos0, multi_headquarters_distance_to_change_flag),      
       (else_try),
         (prop_instance_get_position, pos0, ":pole_id"), #if new owner team is not 0 then flags are at top
         (position_move_z, pos0, multi_headquarters_pole_height),
       (try_end),
  
       (scene_prop_get_instance, ":flag_id", "$team_1_flag_scene_prop", ":flag_no"),
         (prop_instance_stop_animating, ":flag_id"),
       (prop_instance_set_position, ":flag_id", pos0),
  
       (scene_prop_get_instance, ":flag_id", "$team_2_flag_scene_prop", ":flag_no"),
         (prop_instance_stop_animating, ":flag_id"),
       (prop_instance_set_position, ":flag_id", pos0),
  
       (scene_prop_get_instance, ":flag_id", "spr_headquarters_flag_gray_code_only", ":flag_no"),
         (prop_instance_stop_animating, ":flag_id"),
       (prop_instance_set_position, ":flag_id", pos0),          
     (try_end),

     #setting visibilities of flags
     (try_begin), 
       (eq, ":shown_flag_no", 0),
       (scene_prop_get_instance, ":flag_id", "$team_1_flag_scene_prop", ":flag_no"),
       (scene_prop_set_visibility, ":flag_id", 0),
       (scene_prop_get_instance, ":flag_id", "$team_2_flag_scene_prop", ":flag_no"),
       (scene_prop_set_visibility, ":flag_id", 0),
       (scene_prop_get_instance, ":flag_id", "spr_headquarters_flag_gray_code_only", ":flag_no"),
       (scene_prop_set_visibility, ":flag_id", 1),
     (else_try),
       (eq, ":shown_flag_no", 1),
       (scene_prop_get_instance, ":flag_id", "$team_1_flag_scene_prop", ":flag_no"),
       (scene_prop_set_visibility, ":flag_id", 1),
       (scene_prop_get_instance, ":flag_id", "$team_2_flag_scene_prop", ":flag_no"),
       (scene_prop_set_visibility, ":flag_id", 0),
       (scene_prop_get_instance, ":flag_id", "spr_headquarters_flag_gray_code_only", ":flag_no"),
       (scene_prop_set_visibility, ":flag_id", 0),
     (else_try),
       (eq, ":shown_flag_no", 2),
       (scene_prop_get_instance, ":flag_id", "$team_1_flag_scene_prop", ":flag_no"),
       (scene_prop_set_visibility, ":flag_id", 0),
       (scene_prop_get_instance, ":flag_id", "$team_2_flag_scene_prop", ":flag_no"),
       (scene_prop_set_visibility, ":flag_id", 1),
       (scene_prop_get_instance, ":flag_id", "spr_headquarters_flag_gray_code_only", ":flag_no"),
       (scene_prop_set_visibility, ":flag_id", 0),
     (try_end),

     #other
     (store_add, ":cur_flag_players_around_slot", multi_data_flag_players_around_begin, ":flag_no"),
     (troop_get_slot, ":players_around_code", "trp_multiplayer_data", ":cur_flag_players_around_slot"),
 
     (store_div, ":number_of_agents_around_flag_team_1", ":players_around_code", 100),
     (store_mod, ":number_of_agents_around_flag_team_2", ":players_around_code", 100),
  
     (call_script, "script_move_headquarters_flags", ":flag_no", ":number_of_agents_around_flag_team_1", ":number_of_agents_around_flag_team_2"),
   ]),

  #script_move_object_to_nearest_entry_point
  # INPUT: none
  # OUTPUT: none
  ("move_object_to_nearest_entry_point",
   [
     (store_script_param, ":scene_prop_no", 1),

     (scene_prop_get_num_instances, ":num_instances", ":scene_prop_no"),

     (try_for_range, ":instance_no", 0, ":num_instances"),
       (scene_prop_get_instance, ":instance_id", ":scene_prop_no", ":instance_no"),
       (prop_instance_get_position, pos0, ":instance_id"),

       (assign, ":smallest_dist", -1),
       (try_for_range, ":entry_point_no", multi_entry_points_for_usable_items_start, multi_entry_points_for_usable_items_end),
         (entry_point_get_position, pos1, ":entry_point_no"),
         (get_sq_distance_between_positions, ":dist", pos0, pos1),
         (this_or_next|eq, ":smallest_dist", -1),
         (lt, ":dist", ":smallest_dist"),
         (assign, ":smallest_dist", ":dist"),
         (assign, ":nearest_entry_point", ":entry_point_no"),
       (try_end),

       (try_begin),
         (ge, ":smallest_dist", 0),
         (lt, ":smallest_dist", 22500), #max 15m distance
         (entry_point_get_position, pos1, ":nearest_entry_point"),
         (position_rotate_x, pos1, -90),
         (prop_instance_animate_to_position, ":instance_id", pos1, 1),
       (try_end),
     (try_end),
   ]),


  #script_multiplayer_server_on_agent_spawn_common
  # INPUT: arg1 = agent_no
  # OUTPUT: none
  ("multiplayer_server_on_agent_spawn_common",
   [
     (store_script_param, ":agent_no", 1),
     (agent_set_slot, ":agent_no", slot_agent_in_duel_with, -1),
     (try_begin),
       (agent_is_non_player, ":agent_no"),
       (assign, "$g_multiplayer_ready_for_spawning_agent", 1),
     (try_end),
     ]),

  #script_multiplayer_server_player_joined_common
  # INPUT: arg1 = player_no
  # OUTPUT: none
  ("multiplayer_server_player_joined_common",
   [
     (store_script_param, ":player_no", 1),
     (try_begin),
       (this_or_next|player_is_active, ":player_no"),
       (eq, ":player_no", 0),
       (call_script, "script_multiplayer_init_player_slots", ":player_no"),
       (store_mission_timer_a, ":player_join_time"),
       (player_set_slot, ":player_no", slot_player_join_time, ":player_join_time"),
       (player_set_slot, ":player_no", slot_player_first_spawn, 1),
       #fight and destroy only
       (player_set_slot, ":player_no", slot_player_damage_given_to_target_1, 0),
       (player_set_slot, ":player_no", slot_player_damage_given_to_target_2, 0),
       #fight and destroy only end
       (try_begin),
         (multiplayer_is_server),
         (assign, ":initial_gold", multi_initial_gold_value),
         (val_mul, ":initial_gold", "$g_multiplayer_initial_gold_multiplier"),
         (val_div, ":initial_gold", 100),
         (player_set_gold, ":player_no", ":initial_gold"),
         (call_script, "script_multiplayer_send_initial_information", ":player_no"),
       (try_end),
     (try_end),
     ]),

  #script_multiplayer_server_before_mission_start_common
  # INPUT: none
  # OUTPUT: none
  ("multiplayer_server_before_mission_start_common",
   [
     (try_begin),
       (scene_allows_mounted_units),
       (assign, "$g_horses_are_avaliable", 1),
     (else_try),
       (assign, "$g_horses_are_avaliable", 0),
     (try_end),
     (scene_set_day_time, 15),
     (assign, "$g_multiplayer_mission_end_screen", 0),

     (get_max_players, ":num_players"),
     (try_for_range, ":player_no", 0, ":num_players"),
       (player_is_active, ":player_no"),
       (call_script, "script_multiplayer_init_player_slots", ":player_no"),
       (assign, ":initial_gold", multi_initial_gold_value),
       (val_mul, ":initial_gold", "$g_multiplayer_initial_gold_multiplier"),
       (val_div, ":initial_gold", 100),
       (player_set_gold, ":player_no", ":initial_gold"),
       (player_set_slot, ":player_no", slot_player_first_spawn, 1), #not required in siege, bt, fd
     (try_end),
     ]),

  #script_multiplayer_server_on_agent_killed_or_wounded_common
  # INPUT: arg1 = dead_agent_no, arg2 = killer_agent_no
  # OUTPUT: none
  ("multiplayer_server_on_agent_killed_or_wounded_common",
   [
     (store_script_param, ":dead_agent_no", 1),
     (store_script_param, ":killer_agent_no", 2),

     (call_script, "script_multiplayer_event_agent_killed_or_wounded", ":dead_agent_no", ":killer_agent_no"),
     #adding 1 score points to agent which kills enemy agent at server
     (try_begin),
       (multiplayer_is_server),
       (try_begin), #killing myself because of some reason (friend hit, fall, team change)
         (lt, ":killer_agent_no", 0),
         (ge, ":dead_agent_no", 0),
         (neg|agent_is_non_player, ":dead_agent_no"),
         (agent_get_player_id, ":dead_agent_player_id", ":dead_agent_no"),
         (player_is_active, ":dead_agent_player_id"),
         (player_get_score, ":dead_agent_player_score", ":dead_agent_player_id"),
         (val_add, ":dead_agent_player_score", -1),
         (player_set_score, ":dead_agent_player_id", ":dead_agent_player_score"),
       (else_try), #killing teammate
         (ge, ":killer_agent_no", 0),
         (ge, ":dead_agent_no", 0),
         (agent_get_team, ":killer_team_no", ":killer_agent_no"),
         (agent_get_team, ":dead_team_no", ":dead_agent_no"),
         (eq, ":killer_team_no", ":dead_team_no"),
         (neg|agent_is_non_player, ":killer_agent_no"),
         (agent_get_player_id, ":killer_agent_player_id", ":killer_agent_no"),
         (player_is_active, ":killer_agent_player_id"),
         (player_get_score, ":killer_agent_player_score", ":killer_agent_player_id"),
         (val_add, ":killer_agent_player_score", -1),
         (player_set_score, ":killer_agent_player_id", ":killer_agent_player_score"),
         #(player_get_kill_count, ":killer_agent_player_kill_count", ":killer_agent_player_id"),
         #(val_add, ":killer_agent_player_kill_count", -2),
         #(player_set_kill_count, ":killer_agent_player_id", ":killer_agent_player_kill_count"),
       (else_try), #killing enemy
         (ge, ":killer_agent_no", 0),
         (ge, ":dead_agent_no", 0),
         (agent_is_human, ":dead_agent_no"),
         (agent_is_human, ":killer_agent_no"),
         (try_begin),
           (eq, "$g_multiplayer_game_type", multiplayer_game_type_battle),
           (try_begin),
             (eq, "$g_battle_death_mode_started", 1),
             (neq, ":dead_agent_no", ":killer_agent_no"),
             (call_script, "script_calculate_new_death_waiting_time_at_death_mod"),
           (try_end),
         (try_end),
         (try_begin),
           (this_or_next|eq, "$g_multiplayer_game_type", multiplayer_game_type_battle),
           (eq, "$g_multiplayer_game_type", multiplayer_game_type_destroy),
           (agent_get_player_id, ":dead_player_no", ":dead_agent_no"),
           (try_begin),
             (ge, ":dead_player_no", 0),
             (player_is_active, ":dead_player_no"),
             (neg|agent_is_non_player, ":dead_agent_no"),         
             (try_for_agents, ":cur_agent"),
               (agent_is_non_player, ":cur_agent"),
               (agent_is_human, ":cur_agent"),
               (agent_is_alive, ":cur_agent"),
               (agent_get_group, ":agent_group", ":cur_agent"),
               (try_begin),
                 (eq, ":dead_player_no", ":agent_group"),
                 (agent_set_group, ":cur_agent", -1),                 
               (try_end),
             (try_end),
           (try_end),
         (try_end),
         (neg|agent_is_non_player, ":killer_agent_no"),
         (agent_get_player_id, ":killer_agent_player_id", ":killer_agent_no"),
         (player_is_active, ":killer_agent_player_id"),
         (player_get_score, ":killer_agent_player_score", ":killer_agent_player_id"),
         (agent_get_team, ":killer_agent_team", ":killer_agent_no"),
         (agent_get_team, ":dead_agent_team", ":dead_agent_no"),
         (try_begin),
           (neq, ":killer_agent_team", ":dead_agent_team"),
           (val_add, ":killer_agent_player_score", 1),
         (else_try),
           (val_add, ":killer_agent_player_score", -1),
         (try_end),
         (player_set_score, ":killer_agent_player_id", ":killer_agent_player_score"),
       (try_end),
     (try_end),

     (call_script, "script_add_kill_death_counts", ":killer_agent_no", ":dead_agent_no"),
     #money management
     (call_script, "script_money_management_after_agent_death", ":killer_agent_no", ":dead_agent_no"),
     ]),

  #script_multiplayer_close_gate_if_it_is_open
  # INPUT: none
  # OUTPUT: none
  ("multiplayer_close_gate_if_it_is_open",
   [
     (scene_prop_get_num_instances, ":num_instances_of_scene_prop", "spr_winch_b"),
     (try_for_range, ":cur_prop_instance", 0, ":num_instances_of_scene_prop"),
       (scene_prop_get_instance, ":prop_instance_id", "spr_winch_b", ":cur_prop_instance"),
       (scene_prop_slot_eq, ":prop_instance_id", scene_prop_open_or_close_slot, 1),
       (scene_prop_get_instance, ":effected_object_instance_id", "spr_portcullis", ":cur_prop_instance"),
       (prop_instance_get_starting_position, pos0, ":effected_object_instance_id"),      
       (prop_instance_animate_to_position, ":effected_object_instance_id", pos0, 1),
     (try_end),
   ]),  

  #script_multiplayer_move_moveable_objects_initial_positions
  # INPUT: none
  # OUTPUT: none
  ("multiplayer_move_moveable_objects_initial_positions",
   [
     (call_script, "script_move_object_to_nearest_entry_point", "spr_siege_ladder_move_6m"),
     (call_script, "script_move_object_to_nearest_entry_point", "spr_siege_ladder_move_8m"),
     (call_script, "script_move_object_to_nearest_entry_point", "spr_siege_ladder_move_10m"),
     (call_script, "script_move_object_to_nearest_entry_point", "spr_siege_ladder_move_12m"),
     (call_script, "script_move_object_to_nearest_entry_point", "spr_siege_ladder_move_14m"),
   ]),

  #script_move_belfries_to_their_first_entry_point
  # INPUT: none
  # OUTPUT: none
  ("move_belfries_to_their_first_entry_point",
   [
    (store_script_param, ":belfry_body_scene_prop", 1),
     
    (set_fixed_point_multiplier, 100),    
    (scene_prop_get_num_instances, ":num_belfries", ":belfry_body_scene_prop"),
    
    (try_for_range, ":belfry_no", 0, ":num_belfries"),
      #belfry 
      (scene_prop_get_instance, ":belfry_scene_prop_id", ":belfry_body_scene_prop", ":belfry_no"),
      (prop_instance_get_position, pos0, ":belfry_scene_prop_id"),

      (try_begin),
        (eq, ":belfry_body_scene_prop", "spr_belfry_a"),
        #belfry platform_a
        (scene_prop_get_instance, ":belfry_platform_a_scene_prop_id", "spr_belfry_platform_a", ":belfry_no"),
        #belfry platform_b
        (scene_prop_get_instance, ":belfry_platform_b_scene_prop_id", "spr_belfry_platform_b", ":belfry_no"),
      (else_try),
        #belfry platform_a
        (scene_prop_get_instance, ":belfry_platform_a_scene_prop_id", "spr_belfry_b_platform_a", ":belfry_no"),
      (try_end),
    
      #belfry wheel_1
      (store_mul, ":wheel_no", ":belfry_no", 3),
      (try_begin),
        (eq, ":belfry_body_scene_prop", "spr_belfry_b"),
        (scene_prop_get_num_instances, ":number_of_belfry_a", "spr_belfry_a"),    
        (store_mul, ":number_of_belfry_a_wheels", ":number_of_belfry_a", 3),
        (val_add, ":wheel_no", ":number_of_belfry_a_wheels"),
      (try_end),    
      (scene_prop_get_instance, ":belfry_wheel_1_scene_prop_id", "spr_belfry_wheel", ":wheel_no"),
      #belfry wheel_2
      (val_add, ":wheel_no", 1),
      (scene_prop_get_instance, ":belfry_wheel_2_scene_prop_id", "spr_belfry_wheel", ":wheel_no"),
      #belfry wheel_3
      (val_add, ":wheel_no", 1),
      (scene_prop_get_instance, ":belfry_wheel_3_scene_prop_id", "spr_belfry_wheel", ":wheel_no"),

      (store_add, ":belfry_first_entry_point_id", 11, ":belfry_no"), #belfry entry points are 110..119 and 120..129 and 130..139
      (try_begin),
        (eq, ":belfry_body_scene_prop", "spr_belfry_b"),
        (scene_prop_get_num_instances, ":number_of_belfry_a", "spr_belfry_a"),
        (val_add, ":belfry_first_entry_point_id", ":number_of_belfry_a"),
      (try_end),    
      (val_mul, ":belfry_first_entry_point_id", 10),
      (entry_point_get_position, pos1, ":belfry_first_entry_point_id"),

      #this code block is taken from module_mission_templates.py (multiplayer_server_check_belfry_movement)
      #up down rotation of belfry's next entry point
      (init_position, pos9),
      (position_set_y, pos9, -500), #go 5.0 meters back
      (position_set_x, pos9, -300), #go 3.0 meters left
      (position_transform_position_to_parent, pos10, pos1, pos9), 
      (position_get_distance_to_terrain, ":height_to_terrain_1", pos10), #learn distance between 5 meters back of entry point(pos10) and ground level at left part of belfry

      (init_position, pos9),
      (position_set_y, pos9, -500), #go 5.0 meters back
      (position_set_x, pos9, 300), #go 3.0 meters right
      (position_transform_position_to_parent, pos10, pos1, pos9), 
      (position_get_distance_to_terrain, ":height_to_terrain_2", pos10), #learn distance between 5 meters back of entry point(pos10) and ground level at right part of belfry

      (store_add, ":height_to_terrain", ":height_to_terrain_1", ":height_to_terrain_2"),
      (val_mul, ":height_to_terrain", 100), #because of fixed point multiplier

      (store_div, ":rotate_angle_of_next_entry_point", ":height_to_terrain", 24), #if there is 1 meters of distance (100cm) then next target position will rotate by 2 degrees. #ac sonra
      (init_position, pos20),    
      (position_rotate_x_floating, pos20, ":rotate_angle_of_next_entry_point"),
      (position_transform_position_to_parent, pos23, pos1, pos20),

      #right left rotation of belfry's next entry point
      (init_position, pos9),
      (position_set_x, pos9, -300), #go 3.0 meters left
      (position_transform_position_to_parent, pos10, pos1, pos9), #applying 3.0 meters in -x to position of next entry point target, final result is in pos10
      (position_get_distance_to_terrain, ":height_to_terrain_at_left", pos10), #learn distance between 3.0 meters left of entry point(pos10) and ground level
      (init_position, pos9),
      (position_set_x, pos9, 300), #go 3.0 meters left
      (position_transform_position_to_parent, pos10, pos1, pos9), #applying 3.0 meters in x to position of next entry point target, final result is in pos10
      (position_get_distance_to_terrain, ":height_to_terrain_at_right", pos10), #learn distance between 3.0 meters right of entry point(pos10) and ground level
      (store_sub, ":height_to_terrain_1", ":height_to_terrain_at_left", ":height_to_terrain_at_right"),

      (init_position, pos9),
      (position_set_x, pos9, -300), #go 3.0 meters left
      (position_set_y, pos9, -500), #go 5.0 meters forward
      (position_transform_position_to_parent, pos10, pos1, pos9), #applying 3.0 meters in -x to position of next entry point target, final result is in pos10
      (position_get_distance_to_terrain, ":height_to_terrain_at_left", pos10), #learn distance between 3.0 meters left of entry point(pos10) and ground level
      (init_position, pos9),
      (position_set_x, pos9, 300), #go 3.0 meters left
      (position_set_y, pos9, -500), #go 5.0 meters forward
      (position_transform_position_to_parent, pos10, pos1, pos9), #applying 3.0 meters in x to position of next entry point target, final result is in pos10
      (position_get_distance_to_terrain, ":height_to_terrain_at_right", pos10), #learn distance between 3.0 meters right of entry point(pos10) and ground level
      (store_sub, ":height_to_terrain_2", ":height_to_terrain_at_left", ":height_to_terrain_at_right"),

      (store_add, ":height_to_terrain", ":height_to_terrain_1", ":height_to_terrain_2"),    
      (val_mul, ":height_to_terrain", 100), #100 is because of fixed_point_multiplier
      (store_div, ":rotate_angle_of_next_entry_point", ":height_to_terrain", 24), #if there is 1 meters of distance (100cm) then next target position will rotate by 25 degrees. 
      (val_mul, ":rotate_angle_of_next_entry_point", -1),

      (init_position, pos20),
      (position_rotate_y_floating, pos20, ":rotate_angle_of_next_entry_point"),
      (position_transform_position_to_parent, pos22, pos23, pos20),

      (copy_position, pos1, pos22),
      #end of code block

      #belfry 
      (prop_instance_stop_animating, ":belfry_scene_prop_id"),
      (prop_instance_set_position, ":belfry_scene_prop_id", pos1),
    
      #belfry platforms
      (try_begin),
        (eq, ":belfry_body_scene_prop", "spr_belfry_a"),

        #belfry platform_a
        (prop_instance_get_position, pos6, ":belfry_platform_a_scene_prop_id"),
        (position_transform_position_to_local, pos7, pos0, pos6),
        (position_transform_position_to_parent, pos8, pos1, pos7),
        (try_begin),
          (neg|scene_prop_slot_eq, ":belfry_scene_prop_id", scene_prop_belfry_platform_moved, 0),
     
          (init_position, pos20),
          (position_rotate_x, pos20, 90),
          (position_transform_position_to_parent, pos8, pos8, pos20),
        (try_end),
        (prop_instance_stop_animating, ":belfry_platform_a_scene_prop_id"),
        (prop_instance_set_position, ":belfry_platform_a_scene_prop_id", pos8),    
        #belfry platform_b
        (prop_instance_get_position, pos6, ":belfry_platform_b_scene_prop_id"),
        (position_transform_position_to_local, pos7, pos0, pos6),
        (position_transform_position_to_parent, pos8, pos1, pos7),
        (prop_instance_stop_animating, ":belfry_platform_b_scene_prop_id"),
        (prop_instance_set_position, ":belfry_platform_b_scene_prop_id", pos8),
      (else_try),
        #belfry platform_a
        (prop_instance_get_position, pos6, ":belfry_platform_a_scene_prop_id"),
        (position_transform_position_to_local, pos7, pos0, pos6),
        (position_transform_position_to_parent, pos8, pos1, pos7),
        (try_begin),
          (neg|scene_prop_slot_eq, ":belfry_scene_prop_id", scene_prop_belfry_platform_moved, 0),
     
          (init_position, pos20),
          (position_rotate_x, pos20, 50),
          (position_transform_position_to_parent, pos8, pos8, pos20),
        (try_end),
        (prop_instance_stop_animating, ":belfry_platform_a_scene_prop_id"),
        (prop_instance_set_position, ":belfry_platform_a_scene_prop_id", pos8),    
      (try_end),
    
      #belfry wheel_1
      (store_mul, ":wheel_no", ":belfry_no", 3),
      (try_begin),
        (eq, ":belfry_body_scene_prop", "spr_belfry_b"),
        (scene_prop_get_num_instances, ":number_of_belfry_a", "spr_belfry_a"),    
        (store_mul, ":number_of_belfry_a_wheels", ":number_of_belfry_a", 3),
        (val_add, ":wheel_no", ":number_of_belfry_a_wheels"),
      (try_end),
      (prop_instance_get_position, pos6, ":belfry_wheel_1_scene_prop_id"),
      (position_transform_position_to_local, pos7, pos0, pos6),
      (position_transform_position_to_parent, pos8, pos1, pos7),
      (prop_instance_stop_animating, ":belfry_wheel_1_scene_prop_id"),
      (prop_instance_set_position, ":belfry_wheel_1_scene_prop_id", pos8),
      #belfry wheel_2
      (prop_instance_get_position, pos6, ":belfry_wheel_2_scene_prop_id"),
      (position_transform_position_to_local, pos7, pos0, pos6),
      (position_transform_position_to_parent, pos8, pos1, pos7),
      (prop_instance_stop_animating, ":belfry_wheel_2_scene_prop_id"),
      (prop_instance_set_position, ":belfry_wheel_2_scene_prop_id", pos8),
      #belfry wheel_3
      (prop_instance_get_position, pos6, ":belfry_wheel_3_scene_prop_id"),
      (position_transform_position_to_local, pos7, pos0, pos6),
      (position_transform_position_to_parent, pos8, pos1, pos7),
      (prop_instance_stop_animating, ":belfry_wheel_3_scene_prop_id"),
      (prop_instance_set_position, ":belfry_wheel_3_scene_prop_id", pos8),
    (try_end),
    ]),

  #script_team_set_score
  # INPUT: arg1 = team_no, arg2 = score
  # OUTPUT: none
  ("team_set_score",
   [
     (store_script_param, ":team_no", 1),
     (store_script_param, ":score", 2),
     
     (team_set_score, ":team_no", ":score"),
   ]),

  #script_player_set_score
  # INPUT: arg1 = player_no, arg2 = score
  # OUTPUT: none
  ("player_set_score",
   [
     (store_script_param, ":player_no", 1),
     (store_script_param, ":score", 2),
     
     (player_set_score, ":player_no", ":score"),
   ]),

  #script_player_set_kill_count
  # INPUT: arg1 = player_no, arg2 = score
  # OUTPUT: none
  ("player_set_kill_count",
   [
     (store_script_param, ":player_no", 1),
     (store_script_param, ":score", 2),
     
     (player_set_kill_count, ":player_no", ":score"),
   ]),

  #script_player_set_death_count
  # INPUT: arg1 = player_no, arg2 = score
  # OUTPUT: none
  ("player_set_death_count",
   [
     (store_script_param, ":player_no", 1),
     (store_script_param, ":score", 2),
     
     (player_set_death_count, ":player_no", ":score"),
   ]),

  #script_set_attached_scene_prop
  # INPUT: arg1 = agent_id, arg2 = flag_id
  # OUTPUT: none
  ("set_attached_scene_prop",
   [
     (store_script_param, ":agent_id", 1),
     (store_script_param, ":flag_id", 2),

     (try_begin), #if current mod is capture the flag and attached scene prop is flag then change flag situation of flag owner team.
       (scene_prop_get_instance, ":red_flag_id", "spr_tutorial_flag_red", 0),
       (scene_prop_get_instance, ":blue_flag_id", "spr_tutorial_flag_blue", 0),
       (assign, ":flag_owner_team", -1),
       (try_begin),
         (ge, ":red_flag_id", 0),
         (eq, ":flag_id", ":red_flag_id"),
         (assign, ":flag_owner_team", 0),
       (else_try),
         (ge, ":blue_flag_id", 0),
         (eq, ":flag_id", ":blue_flag_id"),
         (assign, ":flag_owner_team", 1),
       (try_end),
       (ge, ":flag_owner_team", 0),
       (team_set_slot, ":flag_owner_team", slot_team_flag_situation, 1), #1-stolen flag
     (try_end),
        
     (agent_set_attached_scene_prop, ":agent_id", ":flag_id"),
     (agent_set_attached_scene_prop_x, ":agent_id", 20),
     (agent_set_attached_scene_prop_z, ":agent_id", 50),
   ]),  

  #script_set_team_flag_situation
  # INPUT: arg1 = team_no, arg2 = score
  # OUTPUT: none
  ("set_team_flag_situation",
   [
     (store_script_param, ":team_no", 1),
     (store_script_param, ":flag_situation", 2),

     (team_set_slot, ":team_no", slot_team_flag_situation, ":flag_situation"),
   ]),

  #script_start_death_mode
  # INPUT: none
  # OUTPUT: none
  ("start_death_mode",
   [
     (assign, "$g_multiplayer_message_type", multiplayer_message_type_start_death_mode),
     (start_presentation, "prsnt_multiplayer_message_1"),
   ]),

  #script_calculate_new_death_waiting_time_at_death_mod
  # INPUT: none
  # OUTPUT: none
  ("calculate_new_death_waiting_time_at_death_mod",
   [
     (assign, ":num_living_players", 0), #count number of living players to find out death wait time
     (try_begin),
       (try_for_agents, ":agent_no"),
         (agent_is_human, ":agent_no"),
         (agent_is_alive, ":agent_no"),
         (val_add, ":num_living_players", 1),
       (try_end),
     (try_end),

     (val_add, ":num_living_players", multiplayer_battle_formula_value_a),
     (set_fixed_point_multiplier, 100),
     (store_mul, ":num_living_players", ":num_living_players", 100),
     (store_sqrt, ":sqrt_num_living_players", ":num_living_players"),
     (store_div, "$g_battle_waiting_seconds", multiplayer_battle_formula_value_b, ":sqrt_num_living_players"),
     (store_mission_timer_a, "$g_death_mode_part_1_start_time"),
   ]),
  
  #script_calculate_number_of_targets_destroyed
  # INPUT: none
  # OUTPUT: none

  ("calculate_number_of_targets_destroyed",
   [
     (assign, "$g_number_of_targets_destroyed", 0),
     (scene_prop_get_num_instances, ":num_instances_of_scene_prop", "spr_catapult_destructible"),
     (try_for_range, ":cur_instance", 0, ":num_instances_of_scene_prop"),
       (scene_prop_get_instance, ":cur_instance_id", "spr_catapult_destructible", ":cur_instance"),
       (prop_instance_get_starting_position, pos0, ":cur_instance_id"),
       (prop_instance_get_position, pos1, ":cur_instance_id"),
       (get_sq_distance_between_positions_in_meters, ":dist", pos0, pos1),
       (gt, ":dist", 2), #this can be 0 or 1 too.
       (val_add, "$g_number_of_targets_destroyed", 1),
     (try_end),    

     (scene_prop_get_num_instances, ":num_instances_of_scene_prop", "spr_trebuchet_destructible"),     
     (try_for_range, ":cur_instance", 0, ":num_instances_of_scene_prop"),
       (scene_prop_get_instance, ":cur_instance_id", "spr_trebuchet_destructible", ":cur_instance"),
       (prop_instance_get_starting_position, pos0, ":cur_instance_id"),
       (prop_instance_get_position, pos1, ":cur_instance_id"),
       (get_sq_distance_between_positions_in_meters, ":dist", pos0, pos1),
       (gt, ":dist", 2), #this can be 0 or 1 too.
       (val_add, "$g_number_of_targets_destroyed", 1),
     (try_end),    
     ]),

  #script_initialize_objects
  # INPUT: none
  # OUTPUT: none
  ("initialize_objects",
   [
     (assign, ":number_of_players", 0),
     (get_max_players, ":num_players"),
     (try_for_range, ":player_no", 0, ":num_players"),
       (player_is_active, ":player_no"),
       (val_add, ":number_of_players", 1),
     (try_end),

     #1 player = (Sqrt(1) - 1) * 200 + 1200 = 1200, 1800 (minimum)
     #4 player = (Sqrt(4) - 1) * 200 + 1200 = 1400, 2100
     #9 player = (Sqrt(9) - 1) * 200 + 1200 = 1600, 2400
     #16 player = (Sqrt(16) - 1) * 200 + 1200 = 1800, 2700 (general used)
     #25 player = (Sqrt(25) - 1) * 200 + 1200 = 2000, 3000 (average)
     #36 player = (Sqrt(36) - 1) * 200 + 1200 = 2200, 3300
     #49 player = (Sqrt(49) - 1) * 200 + 1200 = 2400, 3600
     #64 player = (Sqrt(49) - 1) * 200 + 1200 = 2600, 3900

     (set_fixed_point_multiplier, 100),
     (val_mul, ":number_of_players", 100),
     (store_sqrt, ":number_of_players", ":number_of_players"),
     (val_sub, ":number_of_players", 100),
     (val_max, ":number_of_players", 0),
     (store_mul, ":effect_of_number_of_players", ":number_of_players", 2),
     (store_add, ":health_catapult", multi_minimum_target_health, ":effect_of_number_of_players"),     
     (store_mul, ":health_trebuchet", ":health_catapult", 15), #trebuchet's health is 1.5x of catapult's     
     (val_div, ":health_trebuchet", 10),
     (store_mul, ":health_sally_door", ":health_catapult", 18), #sally door's health is 1.8x of catapult's     
     (val_div, ":health_sally_door", 10),
     (store_mul, ":health_sally_door_double", ":health_sally_door", 2),

     (assign, "$g_number_of_targets_destroyed", 0),
     
     (scene_prop_get_num_instances, ":num_instances_of_scene_prop", "spr_catapult_destructible"),
     (try_for_range, ":cur_instance", 0, ":num_instances_of_scene_prop"),
       (scene_prop_get_instance, ":cur_instance_id", "spr_catapult_destructible", ":cur_instance"),     
       (prop_instance_get_starting_position, pos0, ":cur_instance_id"),
       (prop_instance_stop_animating, ":cur_instance_id"),
       (prop_instance_set_position, ":cur_instance_id", pos0),
       (prop_instance_enable_physics, ":cur_instance_id", 1),
       (scene_prop_set_hit_points, ":cur_instance_id", ":health_catapult"),
     (try_end),    

     (scene_prop_get_num_instances, ":num_instances_of_scene_prop", "spr_trebuchet_destructible"),     
     (try_for_range, ":cur_instance", 0, ":num_instances_of_scene_prop"),
       (scene_prop_get_instance, ":cur_instance_id", "spr_trebuchet_destructible", ":cur_instance"),
       (prop_instance_get_starting_position, pos0, ":cur_instance_id"),
       (prop_instance_stop_animating, ":cur_instance_id"),
       (prop_instance_set_position, ":cur_instance_id", pos0),
       (prop_instance_enable_physics, ":cur_instance_id", 1),
       (scene_prop_set_hit_points, ":cur_instance_id", ":health_trebuchet"),
     (try_end),

     (scene_prop_get_num_instances, ":num_instances_of_scene_prop", "spr_castle_e_sally_door_a"),     
     (try_for_range, ":cur_instance", 0, ":num_instances_of_scene_prop"),
       (scene_prop_get_instance, ":cur_instance_id", "spr_castle_e_sally_door_a", ":cur_instance"),
       (prop_instance_get_starting_position, pos0, ":cur_instance_id"),
       (prop_instance_stop_animating, ":cur_instance_id"),
       (prop_instance_set_position, ":cur_instance_id", pos0),
       (prop_instance_enable_physics, ":cur_instance_id", 1),
       (scene_prop_set_hit_points, ":cur_instance_id", ":health_sally_door"),
     (try_end),
     
     (scene_prop_get_num_instances, ":num_instances_of_scene_prop", "spr_castle_f_sally_door_a"),     
     (try_for_range, ":cur_instance", 0, ":num_instances_of_scene_prop"),
       (scene_prop_get_instance, ":cur_instance_id", "spr_castle_f_sally_door_a", ":cur_instance"),
       (prop_instance_get_starting_position, pos0, ":cur_instance_id"),
       (prop_instance_stop_animating, ":cur_instance_id"),
       (prop_instance_set_position, ":cur_instance_id", pos0),
       (prop_instance_enable_physics, ":cur_instance_id", 1),
       (scene_prop_set_hit_points, ":cur_instance_id", ":health_sally_door"),
     (try_end),

     (scene_prop_get_num_instances, ":num_instances_of_scene_prop", "spr_earth_sally_gate_left"),     
     (try_for_range, ":cur_instance", 0, ":num_instances_of_scene_prop"),
       (scene_prop_get_instance, ":cur_instance_id", "spr_earth_sally_gate_left", ":cur_instance"),
       (prop_instance_get_starting_position, pos0, ":cur_instance_id"),
       (prop_instance_stop_animating, ":cur_instance_id"),
       (prop_instance_set_position, ":cur_instance_id", pos0),
       (prop_instance_enable_physics, ":cur_instance_id", 1),
       (scene_prop_set_hit_points, ":cur_instance_id", ":health_sally_door_double"),
     (try_end),

     (scene_prop_get_num_instances, ":num_instances_of_scene_prop", "spr_earth_sally_gate_right"),     
     (try_for_range, ":cur_instance", 0, ":num_instances_of_scene_prop"),
       (scene_prop_get_instance, ":cur_instance_id", "spr_earth_sally_gate_right", ":cur_instance"),
       (prop_instance_get_starting_position, pos0, ":cur_instance_id"),
       (prop_instance_stop_animating, ":cur_instance_id"),
       (prop_instance_set_position, ":cur_instance_id", pos0),
       (prop_instance_enable_physics, ":cur_instance_id", 1),
       (scene_prop_set_hit_points, ":cur_instance_id", ":health_sally_door_double"),
     (try_end),

     (scene_prop_get_num_instances, ":num_instances_of_scene_prop", "spr_viking_keep_destroy_sally_door_left"),     
     (try_for_range, ":cur_instance", 0, ":num_instances_of_scene_prop"),
       (scene_prop_get_instance, ":cur_instance_id", "spr_viking_keep_destroy_sally_door_left", ":cur_instance"),
       (prop_instance_get_starting_position, pos0, ":cur_instance_id"),
       (prop_instance_stop_animating, ":cur_instance_id"),
       (prop_instance_set_position, ":cur_instance_id", pos0),
       (prop_instance_enable_physics, ":cur_instance_id", 1),
       (scene_prop_set_hit_points, ":cur_instance_id", ":health_sally_door"),
     (try_end),     

     (scene_prop_get_num_instances, ":num_instances_of_scene_prop", "spr_viking_keep_destroy_sally_door_right"),     
     (try_for_range, ":cur_instance", 0, ":num_instances_of_scene_prop"),
       (scene_prop_get_instance, ":cur_instance_id", "spr_viking_keep_destroy_sally_door_right", ":cur_instance"),
       (prop_instance_get_starting_position, pos0, ":cur_instance_id"),
       (prop_instance_stop_animating, ":cur_instance_id"),
       (prop_instance_set_position, ":cur_instance_id", pos0),
       (prop_instance_enable_physics, ":cur_instance_id", 1),
       (scene_prop_set_hit_points, ":cur_instance_id", ":health_sally_door"),
     (try_end),     

     (store_div, ":health_sally_door_div_3", ":health_sally_door", 3),

     (scene_prop_get_num_instances, ":num_instances_of_scene_prop", "spr_castle_f_door_a"),     
     (try_for_range, ":cur_instance", 0, ":num_instances_of_scene_prop"),
       (scene_prop_get_instance, ":cur_instance_id", "spr_castle_f_door_a", ":cur_instance"),
       (prop_instance_get_starting_position, pos0, ":cur_instance_id"),
       (prop_instance_stop_animating, ":cur_instance_id"),
       (prop_instance_set_position, ":cur_instance_id", pos0),
       (prop_instance_enable_physics, ":cur_instance_id", 1),
       (scene_prop_set_hit_points, ":cur_instance_id", ":health_sally_door_div_3"),
     (try_end),     

     (scene_prop_get_num_instances, ":num_instances_of_scene_prop", "spr_castle_f_door_b"),     
     (try_for_range, ":cur_instance", 0, ":num_instances_of_scene_prop"),
       (scene_prop_get_instance, ":cur_instance_id", "spr_castle_f_door_b", ":cur_instance"),
       (prop_instance_get_starting_position, pos0, ":cur_instance_id"),
       (prop_instance_stop_animating, ":cur_instance_id"),
       (prop_instance_set_position, ":cur_instance_id", pos0),
       (prop_instance_enable_physics, ":cur_instance_id", 1),
       (scene_prop_set_hit_points, ":cur_instance_id", ":health_sally_door_div_3"),
     (try_end),     
     ]),
  
  #script_initialize_objects_clients
  # INPUT: none
  # OUTPUT: none
  ("initialize_objects_clients",
   [
     (assign, ":number_of_players", 0),
     (get_max_players, ":num_players"),
     (try_for_range, ":player_no", 0, ":num_players"),
       (player_is_active, ":player_no"),
       (val_add, ":number_of_players", 1),
     (try_end),

     #1 player = (Sqrt(1) - 1) * 200 + 1200 = 1200, 1800 (minimum)
     #4 player = (Sqrt(4) - 1) * 200 + 1200 = 1400, 2100
     #9 player = (Sqrt(9) - 1) * 200 + 1200 = 1600, 2400
     #16 player = (Sqrt(16) - 1) * 200 + 1200 = 1800, 2700 (general used)
     #25 player = (Sqrt(25) - 1) * 200 + 1200 = 2000, 3000 (average)
     #36 player = (Sqrt(36) - 1) * 200 + 1200 = 2200, 3300
     #49 player = (Sqrt(49) - 1) * 200 + 1200 = 2400, 3600
     #64 player = (Sqrt(49) - 1) * 200 + 1200 = 2600, 3900

     (set_fixed_point_multiplier, 100),
     (val_mul, ":number_of_players", 100),
     (store_sqrt, ":number_of_players", ":number_of_players"),
     (val_sub, ":number_of_players", 100),
     (val_max, ":number_of_players", 0),
     (store_mul, ":effect_of_number_of_players", ":number_of_players", 2),
     (store_add, ":health_catapult", multi_minimum_target_health, ":effect_of_number_of_players"),     
     (store_mul, ":health_trebuchet", ":health_catapult", 15), #trebuchet's health is 1.5x of catapult's
     (val_div, ":health_trebuchet", 10),
     (store_mul, ":health_sally_door", ":health_catapult", 18), #trebuchet's health is 1.8x of trebuchet's
     (val_div, ":health_sally_door", 10),
     (store_mul, ":health_sally_door_double", ":health_sally_door", 2),

     (assign, "$g_number_of_targets_destroyed", 0),
     
     (scene_prop_get_num_instances, ":num_instances_of_scene_prop", "spr_catapult_destructible"),
     (try_for_range, ":cur_instance", 0, ":num_instances_of_scene_prop"),
       (scene_prop_get_instance, ":cur_instance_id", "spr_catapult_destructible", ":cur_instance"),     
       (prop_instance_enable_physics, ":cur_instance_id", 1),
       (scene_prop_set_hit_points, ":cur_instance_id", ":health_catapult"),
     (try_end),    

     (scene_prop_get_num_instances, ":num_instances_of_scene_prop", "spr_trebuchet_destructible"),     
     (try_for_range, ":cur_instance", 0, ":num_instances_of_scene_prop"),
       (scene_prop_get_instance, ":cur_instance_id", "spr_trebuchet_destructible", ":cur_instance"),
       (prop_instance_enable_physics, ":cur_instance_id", 1),
       (scene_prop_set_hit_points, ":cur_instance_id", ":health_trebuchet"),
     (try_end),

     (scene_prop_get_num_instances, ":num_instances_of_scene_prop", "spr_castle_e_sally_door_a"),     
     (try_for_range, ":cur_instance", 0, ":num_instances_of_scene_prop"),
       (scene_prop_get_instance, ":cur_instance_id", "spr_castle_e_sally_door_a", ":cur_instance"),
       (prop_instance_enable_physics, ":cur_instance_id", 1),
       (scene_prop_set_hit_points, ":cur_instance_id", ":health_sally_door"),
     (try_end),
     
     (scene_prop_get_num_instances, ":num_instances_of_scene_prop", "spr_castle_f_sally_door_a"),     
     (try_for_range, ":cur_instance", 0, ":num_instances_of_scene_prop"),
       (scene_prop_get_instance, ":cur_instance_id", "spr_castle_f_sally_door_a", ":cur_instance"),
       (prop_instance_enable_physics, ":cur_instance_id", 1),
       (scene_prop_set_hit_points, ":cur_instance_id", ":health_sally_door"),
     (try_end),

     (scene_prop_get_num_instances, ":num_instances_of_scene_prop", "spr_earth_sally_gate_left"),     
     (try_for_range, ":cur_instance", 0, ":num_instances_of_scene_prop"),
       (scene_prop_get_instance, ":cur_instance_id", "spr_earth_sally_gate_left", ":cur_instance"),
       (prop_instance_enable_physics, ":cur_instance_id", 1),
       (scene_prop_set_hit_points, ":cur_instance_id", ":health_sally_door_double"),
     (try_end),

     (scene_prop_get_num_instances, ":num_instances_of_scene_prop", "spr_earth_sally_gate_right"),     
     (try_for_range, ":cur_instance", 0, ":num_instances_of_scene_prop"),
       (scene_prop_get_instance, ":cur_instance_id", "spr_earth_sally_gate_right", ":cur_instance"),
       (prop_instance_enable_physics, ":cur_instance_id", 1),
       (scene_prop_set_hit_points, ":cur_instance_id", ":health_sally_door_double"),
     (try_end),

     (scene_prop_get_num_instances, ":num_instances_of_scene_prop", "spr_viking_keep_destroy_sally_door_left"),     
     (try_for_range, ":cur_instance", 0, ":num_instances_of_scene_prop"),
       (scene_prop_get_instance, ":cur_instance_id", "spr_viking_keep_destroy_sally_door_left", ":cur_instance"),
       (prop_instance_enable_physics, ":cur_instance_id", 1),
       (scene_prop_set_hit_points, ":cur_instance_id", ":health_sally_door"),
     (try_end),             

     (scene_prop_get_num_instances, ":num_instances_of_scene_prop", "spr_viking_keep_destroy_sally_door_right"),     
     (try_for_range, ":cur_instance", 0, ":num_instances_of_scene_prop"),
       (scene_prop_get_instance, ":cur_instance_id", "spr_viking_keep_destroy_sally_door_right", ":cur_instance"),
       (prop_instance_enable_physics, ":cur_instance_id", 1),
       (scene_prop_set_hit_points, ":cur_instance_id", ":health_sally_door"),
     (try_end),             

     (store_div, ":health_sally_door_div_3", ":health_sally_door", 3),

     (scene_prop_get_num_instances, ":num_instances_of_scene_prop", "spr_castle_f_door_a"),     
     (try_for_range, ":cur_instance", 0, ":num_instances_of_scene_prop"),
       (scene_prop_get_instance, ":cur_instance_id", "spr_castle_f_door_a", ":cur_instance"),
       (prop_instance_enable_physics, ":cur_instance_id", 1),
       (scene_prop_set_hit_points, ":cur_instance_id", ":health_sally_door_div_3"),
     (try_end),     

     (scene_prop_get_num_instances, ":num_instances_of_scene_prop", "spr_castle_f_door_b"),     
     (try_for_range, ":cur_instance", 0, ":num_instances_of_scene_prop"),
       (scene_prop_get_instance, ":cur_instance_id", "spr_castle_f_door_b", ":cur_instance"),
       (prop_instance_enable_physics, ":cur_instance_id", 1),
       (scene_prop_set_hit_points, ":cur_instance_id", ":health_sally_door_div_3"),
     (try_end),     
     ]),

  #script_show_multiplayer_message
  # INPUT: arg1 = multiplayer_message_type
  # OUTPUT: none
  ("show_multiplayer_message",
   [
    (store_script_param, ":multiplayer_message_type", 1),
    (store_script_param, ":value", 2),

    (assign, "$g_multiplayer_message_type", ":multiplayer_message_type"),

    (try_begin),
      (eq, ":multiplayer_message_type", multiplayer_message_type_round_result_in_battle_mode),
      (assign, "$g_multiplayer_message_value_1", ":value"),
      (start_presentation, "prsnt_multiplayer_message_1"),
      
      (try_begin), #end of round in clients
        (neg|multiplayer_is_server),
        (assign, "$g_battle_death_mode_started", 0),
      (try_end),  
    (else_try),
      (eq, ":multiplayer_message_type", multiplayer_message_type_auto_team_balance_done),
      (assign, "$g_multiplayer_message_value_1", ":value"),
      (start_presentation, "prsnt_multiplayer_message_2"),
      (assign, "$g_team_balance_next_round", 0), 
    (else_try),
      (eq, ":multiplayer_message_type", multiplayer_message_type_auto_team_balance_next),
      (assign, "$g_team_balance_next_round", 1),
      (call_script, "script_warn_player_about_auto_team_balance"),
    (else_try),
      (eq, ":multiplayer_message_type", multiplayer_message_type_auto_team_balance_no_need),
      (assign, "$g_team_balance_next_round", 0),
    (else_try),
      (eq, ":multiplayer_message_type", multiplayer_message_type_capture_the_flag_score),
      (assign, "$g_multiplayer_message_value_1", ":value"),
      (start_presentation, "prsnt_multiplayer_message_1"),
    (else_try),
      (eq, ":multiplayer_message_type", multiplayer_message_type_flag_returned_home),
      (assign, "$g_multiplayer_message_value_1", ":value"),    
      (start_presentation, "prsnt_multiplayer_message_1"),
    (else_try),
      (eq, ":multiplayer_message_type", multiplayer_message_type_capture_the_flag_stole),
      (assign, "$g_multiplayer_message_value_1", ":value"),
      (start_presentation, "prsnt_multiplayer_message_1"),
    (else_try),
      (eq, ":multiplayer_message_type", multiplayer_message_type_poll_result),
      (assign, "$g_multiplayer_message_value_3", ":value"),
      (start_presentation, "prsnt_multiplayer_message_3"),
    (else_try),
      (eq, ":multiplayer_message_type", multiplayer_message_type_flag_neutralized),      
      (assign, "$g_multiplayer_message_value_1", ":value"),
      (start_presentation, "prsnt_multiplayer_message_1"),
    (else_try),
      (eq, ":multiplayer_message_type", multiplayer_message_type_flag_captured),
      (assign, "$g_multiplayer_message_value_1", ":value"),
      (start_presentation, "prsnt_multiplayer_message_1"),
    (else_try),
      (eq, ":multiplayer_message_type", multiplayer_message_type_flag_is_pulling),
      (assign, "$g_multiplayer_message_value_1", ":value"),
      (start_presentation, "prsnt_multiplayer_message_1"),
    (else_try),
      (eq, ":multiplayer_message_type", multiplayer_message_type_round_draw),
      (start_presentation, "prsnt_multiplayer_message_1"),
    (else_try),
      (eq, ":multiplayer_message_type", multiplayer_message_type_target_destroyed),
    
      (try_begin), #destroy score (condition : a target destroyed)
        (eq, "$g_defender_team", 0),
        (assign, ":attacker_team_no", 1),
      (else_try),
        (assign, ":attacker_team_no", 0),
      (try_end),
       
      (team_get_score, ":team_score", ":attacker_team_no"),
      (val_add, ":team_score", 1),
      (call_script, "script_team_set_score", ":attacker_team_no", ":team_score"), #destroy score end

      (assign, "$g_multiplayer_message_value_1", ":value"),
      (start_presentation, "prsnt_multiplayer_message_1"),
    (else_try),
      (eq, ":multiplayer_message_type", multiplayer_message_type_defenders_saved_n_targets),      
      (assign, "$g_multiplayer_message_value_1", ":value"),
      (start_presentation, "prsnt_multiplayer_message_1"),
    (else_try),
      (eq, ":multiplayer_message_type", multiplayer_message_type_attackers_won_the_round),
      (try_begin),
        (eq, "$g_defender_team", 0),
        (assign, "$g_multiplayer_message_value_1", 1),
      (else_try),
        (assign, "$g_multiplayer_message_value_1", 0),
      (try_end),
      (start_presentation, "prsnt_multiplayer_message_1"),
    (try_end),
    ]),

  #script_get_headquarters_scores
  # INPUT: none
  # OUTPUT: reg0 = team_1_num_flags, reg1 = team_2_num_flags
  ("get_headquarters_scores",
   [
     (assign, ":team_1_num_flags", 0),
     (assign, ":team_2_num_flags", 0),
     (try_for_range, ":flag_no", 0, "$g_number_of_flags"),
       (store_add, ":cur_flag_owner_slot", multi_data_flag_owner_begin, ":flag_no"),
       (troop_get_slot, ":cur_flag_owner", "trp_multiplayer_data", ":cur_flag_owner_slot"),
       (neq, ":cur_flag_owner", 0),
       (try_begin),
         (eq, ":cur_flag_owner", 1),
         (val_add, ":team_1_num_flags", 1),
       (else_try),
         (val_add, ":team_2_num_flags", 1),
       (try_end),
     (try_end),
     (assign, reg0, ":team_1_num_flags"),
     (assign, reg1, ":team_2_num_flags"),
     ]),


  #script_draw_this_round
  # INPUT: arg1 = value
  ("draw_this_round",
   [
    (store_script_param, ":value", 1),
    (try_begin),
      (eq, ":value", -9), #destroy mod round end
      (assign, "$g_round_ended", 1),
      (store_mission_timer_a, "$g_round_finish_time"),
      #(assign, "$g_multiplayer_message_value_1", -1),
      #(assign, "$g_multiplayer_message_type", multiplayer_message_type_round_draw),
      #(start_presentation, "prsnt_multiplayer_message_1"),
    (else_try),
      (eq, ":value", -1), #draw
      (assign, "$g_round_ended", 1),
      (store_mission_timer_a, "$g_round_finish_time"),
      (assign, "$g_multiplayer_message_value_1", -1),
      (assign, "$g_multiplayer_message_type", multiplayer_message_type_round_draw),
      (start_presentation, "prsnt_multiplayer_message_1"),
    (else_try), 
      (eq, ":value", 0), #defender wins
      #THIS_IS_OUR_LAND achievement
      (try_begin),
        (eq, "$g_multiplayer_game_type", multiplayer_game_type_siege),
        (multiplayer_get_my_player, ":my_player_no"),
        (is_between, ":my_player_no", 0, multiplayer_max_possible_player_id),
        (player_get_agent_id, ":my_player_agent", ":my_player_no"),
        (ge, ":my_player_agent", 0),
        (agent_is_alive, ":my_player_agent"),
        (agent_get_team, ":my_player_agent_team_no", ":my_player_agent"),
        (eq, ":my_player_agent_team_no", 0), #defender
        (unlock_achievement, ACHIEVEMENT_THIS_IS_OUR_LAND),
      (try_end),
      #THIS_IS_OUR_LAND achievement end
      (assign, "$g_round_ended", 1),
      (store_mission_timer_a, "$g_round_finish_time"),
        
      (team_get_faction, ":faction_of_winner_team", 0),
      (team_get_score, ":team_1_score", 0),
      (val_add, ":team_1_score", 1),
      (team_set_score, 0, ":team_1_score"),
      (assign, "$g_winner_team", 0),
      (str_store_faction_name, s1, ":faction_of_winner_team"),

      (assign, "$g_multiplayer_message_value_1", ":value"),
      (try_begin),
        (neq, "$g_multiplayer_game_type", multiplayer_game_type_battle),    
        (neq, "$g_multiplayer_game_type", multiplayer_game_type_destroy),
        (assign, "$g_multiplayer_message_type", multiplayer_message_type_round_result_in_siege_mode),
      (else_try),
        (assign, "$g_multiplayer_message_type", multiplayer_message_type_round_result_in_battle_mode),
      (try_end),
      (start_presentation, "prsnt_multiplayer_message_1"),
    (else_try), 
      (eq, ":value", 1), #attacker wins
      (assign, "$g_round_ended", 1),
      (store_mission_timer_a, "$g_round_finish_time"),
  
      (team_get_faction, ":faction_of_winner_team", 1),
      (team_get_score, ":team_2_score", 1),
      (val_add, ":team_2_score", 1),
      (team_set_score, 1, ":team_2_score"),
      (assign, "$g_winner_team", 1),
      (str_store_faction_name, s1, ":faction_of_winner_team"),

      (assign, "$g_multiplayer_message_value_1", ":value"),
      (try_begin),
        (neq, "$g_multiplayer_game_type", multiplayer_game_type_battle),    
        (neq, "$g_multiplayer_game_type", multiplayer_game_type_destroy),
        (assign, "$g_multiplayer_message_type", multiplayer_message_type_round_result_in_siege_mode),
      (else_try),
        (assign, "$g_multiplayer_message_type", multiplayer_message_type_round_result_in_battle_mode),
      (try_end),
      (start_presentation, "prsnt_multiplayer_message_1"),
    (try_end),
    #LAST_MAN_STANDING achievement
    (try_begin),
      (is_between, ":value", 0, 2), #defender or attacker wins
      (try_begin),
        (eq, "$g_multiplayer_game_type", multiplayer_game_type_battle),
        (multiplayer_get_my_player, ":my_player_no"),
        (is_between, ":my_player_no", 0, multiplayer_max_possible_player_id),
        (player_get_agent_id, ":my_player_agent", ":my_player_no"),
        (ge, ":my_player_agent", 0),
        (agent_is_alive, ":my_player_agent"),
        (agent_get_team, ":my_player_agent_team_no", ":my_player_agent"),
        (eq, ":my_player_agent_team_no", ":value"), #winner team
        (unlock_achievement, ACHIEVEMENT_LAST_MAN_STANDING),
      (try_end),
    (try_end),
    #LAST_MAN_STANDING achievement end
    ]),   
    
  #script_check_achievement_last_man_standing
  #INPUT: arg1 = value
  ("check_achievement_last_man_standing",
   [
   #LAST_MAN_STANDING achievement
	  (try_begin),
	    (store_script_param, ":value", 1),
		(is_between, ":value", 0, 2), #defender or attacker wins
	    (try_begin),
		  (eq, "$g_multiplayer_game_type", multiplayer_game_type_battle),
		  (multiplayer_get_my_player, ":my_player_no"),
		  (is_between, ":my_player_no", 0, multiplayer_max_possible_player_id),
		  (player_get_agent_id, ":my_player_agent", ":my_player_no"),
		  (ge, ":my_player_agent", 0),
		  (agent_is_alive, ":my_player_agent"),
		  (agent_get_team, ":my_player_agent_team_no", ":my_player_agent"),
		  (eq, ":my_player_agent_team_no", ":value"), #winner team
		  (unlock_achievement, ACHIEVEMENT_LAST_MAN_STANDING),
		(try_end),
	  (try_end),
    #LAST_MAN_STANDING achievement end
    ]),

  #script_find_most_suitable_bot_to_control
  # INPUT: arg1 = value
  ("find_most_suitable_bot_to_control",
   [
      (set_fixed_point_multiplier, 100),
      (store_script_param, ":player_no", 1),
      (player_get_team_no, ":player_team", ":player_no"),

      (player_get_slot, ":x_coor", ":player_no", slot_player_death_pos_x),
      (player_get_slot, ":y_coor", ":player_no", slot_player_death_pos_y),
      (player_get_slot, ":z_coor", ":player_no", slot_player_death_pos_z),

      (init_position, pos0),
      (position_set_x, pos0, ":x_coor"),
      (position_set_y, pos0, ":y_coor"),
      (position_set_z, pos0, ":z_coor"),

      (assign, ":most_suitable_bot", -1),
      (assign, ":max_bot_score", -1),

      (try_for_agents, ":cur_agent"),
        (agent_is_alive, ":cur_agent"),
        (agent_is_human, ":cur_agent"),
        (agent_is_non_player, ":cur_agent"),
        (agent_get_team ,":cur_team", ":cur_agent"),
        (eq, ":cur_team", ":player_team"),
        (agent_get_position, pos1, ":cur_agent"),

        #getting score for distance of agent to death point (0..3000)
        (get_distance_between_positions_in_meters, ":dist", pos0, pos1),

        (try_begin),
          (lt, ":dist", 500),
          (store_sub, ":bot_score", 500, ":dist"),
        (else_try),
          (assign, ":bot_score", 0),
        (try_end),
        (val_mul, ":bot_score", 6),

        #getting score for distance of agent to enemy & friend agents (0..300 x agents)
        (try_for_agents, ":cur_agent_2"),
          (agent_is_alive, ":cur_agent_2"),
          (agent_is_human, ":cur_agent_2"),
          (neq, ":cur_agent", ":cur_agent_2"),      
          (agent_get_team ,":cur_team_2", ":cur_agent_2"),
          (try_begin),
            (neq, ":cur_team_2", ":player_team"),
            (agent_get_position, pos1, ":cur_agent_2"),
            (get_distance_between_positions, ":dist_2", pos0, pos1),
            (try_begin),
              (lt, ":dist_2", 300),
              (assign, ":enemy_near_score", ":dist_2"),
            (else_try),
              (assign, ":enemy_near_score", 300),
            (try_end),
            (val_add, ":bot_score", ":enemy_near_score"),
          (else_try),
            (agent_get_position, pos1, ":cur_agent_2"),
            (get_distance_between_positions, ":dist_2", pos0, pos1),
            (try_begin),
              (lt, ":dist_2", 300),
              (assign, ":friend_near_score", 300, ":dist_2"),
            (else_try),
              (assign, ":friend_near_score", 0),
            (try_end),
            (val_add, ":bot_score", ":friend_near_score"),
          (try_end),
        (try_end),

        #getting score for health (0..200)
        (store_agent_hit_points, ":agent_hit_points", ":cur_agent"),
        (val_mul, ":agent_hit_points", 2),
        (val_add, ":bot_score", ":agent_hit_points"),

        (ge, ":bot_score", ":max_bot_score"),
        (assign, ":max_bot_score", ":bot_score"),
        (assign, ":most_suitable_bot", ":cur_agent"),
      (try_end),

      (assign, reg0, ":most_suitable_bot"),
    ]),

  #script_game_receive_url_response
  #response format should be like this:
  #  [a number or a string]|[another number or a string]|[yet another number or a string] ...
  # here is an example response:
  # 12|Player|100|another string|142|323542|34454|yet another string
  # INPUT: arg1 = num_integers, arg2 = num_strings
  # reg0, reg1, reg2, ... up to 128 registers contain the integer values
  # s0, s1, s2, ... up to 128 strings contain the string values
  ("game_receive_url_response",
    [
      #here is an example usage
##      (store_script_param, ":num_integers", 1),
##      (store_script_param, ":num_strings", 2),
##      (try_begin),
##        (gt, ":num_integers", 4),
##        (display_message, "@{reg0}, {reg1}, {reg2}, {reg3}, {reg4}"),
##      (try_end),
##      (try_begin),
##        (gt, ":num_strings", 4),
##        (display_message, "@{s0}, {s1}, {s2}, {s3}, {s4}"),
##      (try_end),
      ]),
      
  ("game_get_cheat_mode",
  [
    (assign, reg0, "$cheat_mode"),
  ]),    
  
  #script_game_receive_network_message
  # This script is called from the game engine when a new network message is received.
  # INPUT: arg1 = player_no, arg2 = event_type, arg3 = value, arg4 = value_2, arg5 = value_3, arg6 = value_4
  ("game_receive_network_message",
    [
      (store_script_param, ":player_no", 1),
      (store_script_param, ":event_type", 2),
      (try_begin),
        ###############
        #SERVER EVENTS#
        ###############
        (eq, ":event_type", multiplayer_event_set_item_selection),
        (store_script_param, ":slot_no", 3),
        (store_script_param, ":value", 4),
        (try_begin),
          #valid slot check
          (is_between, ":slot_no", slot_player_selected_item_indices_begin, slot_player_selected_item_indices_end),
          #valid item check
          (assign, ":valid_item", 0),
          (try_begin),
            (eq, ":value", -1),
            (assign, ":valid_item", 1),
          (else_try),
            (ge, ":value", 0),
            (player_get_troop_id, ":player_troop_no", ":player_no"),
            (is_between, ":player_troop_no", multiplayer_troops_begin, multiplayer_troops_end),
            (store_sub, ":troop_index", ":player_troop_no", multiplayer_troops_begin),
            (val_add, ":troop_index", slot_item_multiplayer_availability_linked_list_begin),
            (item_get_slot, ":prev_next_item_ids", ":value", ":troop_index"),
            (gt, ":prev_next_item_ids", 0), #0 if the item is not valid for the multiplayer mode
            (assign, ":valid_item", 1),
            (try_begin),
              (neq, "$g_horses_are_avaliable", 1),
              (item_get_slot, ":item_class", ":value", slot_item_multiplayer_item_class),
              (is_between, ":item_class", multi_item_class_type_horses_begin, multi_item_class_type_horses_end),
              (assign, ":valid_item", 0),
            (try_end),
            (try_begin),
              (eq, "$g_multiplayer_disallow_ranged_weapons", 1),
              (item_get_slot, ":item_class", ":value", slot_item_multiplayer_item_class),
              (is_between, ":item_class", multi_item_class_type_ranged_weapons_begin, multi_item_class_type_ranged_weapons_end),
              (assign, ":valid_item", 0),
            (try_end),
          (try_end),
          (eq, ":valid_item", 1),
          #condition checks are done
          (player_set_slot, ":player_no", ":slot_no", ":value"),
        (try_end),
      (else_try),
        (eq, ":event_type", multiplayer_event_set_bot_selection),
        (store_script_param, ":slot_no", 3),
        (store_script_param, ":value", 4),
        (try_begin),
          #condition check
          (is_between, ":slot_no", slot_player_bot_type_1_wanted, slot_player_bot_type_4_wanted + 1),
          (is_between, ":value", 0, 2),
          #condition checks are done
          (player_set_slot, ":player_no", ":slot_no", ":value"),
        (try_end),
      (else_try),
        (eq, ":event_type", multiplayer_event_change_team_no),
        (store_script_param, ":value", 3),
        (try_begin),
          #validity check
          (player_get_team_no, ":player_team", ":player_no"),
          (neq, ":player_team", ":value"),

          #condition checks are done
          (try_begin),
            #check if available
            (call_script, "script_cf_multiplayer_team_is_available", ":player_no", ":value"),
            #reset troop_id to -1
            (player_set_troop_id, ":player_no", -1),
            (player_set_team_no, ":player_no", ":value"),
            (try_begin),
              (neq, ":value", multi_team_spectator),
              (neq, ":value", multi_team_unassigned),
      
              (store_mission_timer_a, ":player_last_team_select_time"),         
              (player_set_slot, ":player_no", slot_player_last_team_select_time, ":player_last_team_select_time"),
      
              (multiplayer_send_message_to_player, ":player_no", multiplayer_event_return_confirmation),
            (try_end),
          (else_try),
            #reject request
            (multiplayer_send_message_to_player, ":player_no", multiplayer_event_return_rejection),
          (try_end),
        (try_end),
      (else_try),
        (eq, ":event_type", multiplayer_event_change_troop_id),
        (store_script_param, ":value", 3),
        #troop-faction validity check
        (try_begin),
          (eq, ":value", -1),
          (player_set_troop_id, ":player_no", -1),
        (else_try),
          (is_between, ":value", multiplayer_troops_begin, multiplayer_troops_end),
          (player_get_team_no, ":player_team", ":player_no"),
          (is_between, ":player_team", 0, multi_team_spectator),
          (team_get_faction, ":team_faction", ":player_team"),
          (store_troop_faction, ":new_troop_faction", ":value"),
          (eq, ":new_troop_faction", ":team_faction"),
          (player_set_troop_id, ":player_no", ":value"),
          (call_script, "script_multiplayer_clear_player_selected_items", ":player_no"),
        (try_end),
      (else_try),
        (eq, ":event_type", multiplayer_event_admin_start_map),
        (store_script_param, ":value", 3),
        (store_script_param, ":value_2", 4),
        (try_begin),
          #validity check
          (player_is_admin, ":player_no"),
          (is_between, ":value", multiplayer_scenes_begin, multiplayer_scenes_end),
          (is_between, ":value_2", 0, multiplayer_num_game_types),
          (server_get_changing_game_type_allowed, "$g_multiplayer_changing_game_type_allowed"),
          (this_or_next|eq, "$g_multiplayer_changing_game_type_allowed", 1),
          (eq, "$g_multiplayer_game_type", ":value_2"),
          (call_script, "script_multiplayer_fill_map_game_types", ":value_2"),
          (assign, ":num_maps", reg0),
          (assign, ":is_valid", 0),
          (store_add, ":end_cond", multi_data_maps_for_game_type_begin, ":num_maps"),
          (try_for_range, ":i_map", multi_data_maps_for_game_type_begin, ":end_cond"),
            (troop_slot_eq, "trp_multiplayer_data", ":i_map", ":value"),
            (assign, ":is_valid", 1),
            (assign, ":end_cond", 0),
          (try_end),
          (eq, ":is_valid", 1),
          #condition checks are done
          (assign, "$g_multiplayer_game_type", ":value_2"),
          (assign, "$g_multiplayer_selected_map", ":value"),
          (team_set_faction, 0, "$g_multiplayer_next_team_1_faction"),
          (team_set_faction, 1, "$g_multiplayer_next_team_2_faction"),
          (call_script, "script_game_multiplayer_get_game_type_mission_template", "$g_multiplayer_game_type"),
          (start_multiplayer_mission, reg0, "$g_multiplayer_selected_map", 1),
        (try_end),
      (else_try),
        (eq, ":event_type", multiplayer_event_admin_set_max_num_players),
        (store_script_param, ":value", 3),
        (try_begin),
          #validity check
          (player_is_admin, ":player_no"),
          (is_between, ":value", 2, 201),
          #condition checks are done
          (server_set_max_num_players, ":value"),      
        (try_end),
      (else_try),
        (eq, ":event_type", multiplayer_event_admin_set_num_bots_in_team),
        (store_script_param, ":value", 3),
        (store_script_param, ":value_2", 4),
        (try_begin),
          #validity check
          (player_is_admin, ":player_no"),
          (is_between, ":value", 1, 3),
          (is_between, ":value_2", 0, "$g_multiplayer_max_num_bots"),
          #condition checks are done
          (try_begin),
            (eq, ":value", 1),
            (assign, "$g_multiplayer_num_bots_team_1", ":value_2"),
          (else_try),
            (assign, "$g_multiplayer_num_bots_team_2", ":value_2"),
          (try_end),
          (get_max_players, ":num_players"),                               
          (try_for_range, ":cur_player", 1, ":num_players"),
            (player_is_active, ":cur_player"),
            (multiplayer_send_2_int_to_player, ":cur_player", multiplayer_event_return_num_bots_in_team, ":value", ":value_2"),
          (try_end),            
        (try_end),
      (else_try),
        (eq, ":event_type", multiplayer_event_admin_set_anti_cheat),
        (store_script_param, ":value", 3),
        (try_begin),
          #validity check
          (player_is_admin, ":player_no"),
          (is_between, ":value", 0, 2),
          #condition checks are done
          (server_set_anti_cheat, ":value"),
        (try_end),
      (else_try),
        (eq, ":event_type", multiplayer_event_admin_set_friendly_fire),
        (store_script_param, ":value", 3),
        (try_begin),
          #validity check
          (player_is_admin, ":player_no"),
          (is_between, ":value", 0, 2),
          #condition checks are done
          (server_set_friendly_fire, ":value"),
        (try_end),
      (else_try),
        (eq, ":event_type", multiplayer_event_admin_set_melee_friendly_fire),
        (store_script_param, ":value", 3),
        (try_begin),
          #validity check
          (player_is_admin, ":player_no"),
          (is_between, ":value", 0, 2),
          #condition checks are done
          (server_set_melee_friendly_fire, ":value"),
        (try_end),
      (else_try),
        (eq, ":event_type", multiplayer_event_admin_set_friendly_fire_damage_self_ratio),
        (store_script_param, ":value", 3),
        (try_begin),
          #validity check
          (player_is_admin, ":player_no"),
          (is_between, ":value", 0, 101),
          #condition checks are done
          (server_set_friendly_fire_damage_self_ratio, ":value"),
        (try_end),
      (else_try),
        (eq, ":event_type", multiplayer_event_admin_set_friendly_fire_damage_friend_ratio),
        (store_script_param, ":value", 3),
        (try_begin),
          #validity check
          (player_is_admin, ":player_no"),
          (is_between, ":value", 0, 101),
          #condition checks are done
          (server_set_friendly_fire_damage_friend_ratio, ":value"),
        (try_end),
      (else_try),
        (eq, ":event_type", multiplayer_event_admin_set_ghost_mode),
        (store_script_param, ":value", 3),
        (try_begin),
          #validity check
          (player_is_admin, ":player_no"),
          (is_between, ":value", 0, 4),
          #condition checks are done
          (server_set_ghost_mode, ":value"),
        (try_end),
      (else_try),
        (eq, ":event_type", multiplayer_event_admin_set_control_block_dir),
        (store_script_param, ":value", 3),
        (try_begin),
          #validity check
          (player_is_admin, ":player_no"),
          (is_between, ":value", 0, 2),
          #condition checks are done
          (server_set_control_block_dir, ":value"),
        (try_end),
      (else_try),
        (eq, ":event_type", multiplayer_event_admin_set_combat_speed),
        (store_script_param, ":value", 3),
        (try_begin),
          #validity check
          (player_is_admin, ":player_no"),
          (is_between, ":value", 0, 5),
          #condition checks are done
          (server_set_combat_speed, ":value"),
        (try_end),
      (else_try),
        (eq, ":event_type", multiplayer_event_admin_set_respawn_count),
        (store_script_param, ":value", 3),
        #validity check
        (player_is_admin, ":player_no"),
        (is_between, ":value", 0, 6),
        #condition checks are done       
        (assign, "$g_multiplayer_number_of_respawn_count", ":value"),
        (get_max_players, ":num_players"),
        (try_for_range, ":cur_player", 1, ":num_players"),
          (player_is_active, ":cur_player"),
          (multiplayer_send_int_to_player, ":cur_player", multiplayer_event_return_respawn_count, ":value"),
        (try_end),                  
      (else_try),
        (eq, ":event_type", multiplayer_event_admin_set_add_to_servers_list),
        (store_script_param, ":value", 3),
        (try_begin),
          #validity check
          (player_is_admin, ":player_no"),
          #condition checks are done
          (server_set_add_to_game_servers_list, ":value"),
        (try_end),
      (else_try),
        (eq, ":event_type", multiplayer_event_admin_set_respawn_period), 
        (store_script_param, ":value", 3),
        (try_begin),
          #validity check
          (player_is_admin, ":player_no"),
          (is_between, ":value", 3, 31),
          #condition checks are done
          (assign, "$g_multiplayer_respawn_period", ":value"),
          (get_max_players, ":num_players"),
          (try_for_range, ":cur_player", 1, ":num_players"),
            (player_is_active, ":cur_player"),
            (multiplayer_send_int_to_player, ":cur_player", multiplayer_event_return_respawn_period, ":value"),
          (try_end),            
        (try_end),
      (else_try),
        (eq, ":event_type", multiplayer_event_admin_set_game_max_minutes),
        (store_script_param, ":value", 3),
        (try_begin),
          #validity check
          (player_is_admin, ":player_no"),
          (is_between, ":value", 5, 121),
          #condition checks are done
          (assign, "$g_multiplayer_game_max_minutes", ":value"),
        (try_end),
      (else_try),
        (eq, ":event_type", multiplayer_event_admin_set_round_max_seconds),
        (store_script_param, ":value", 3),
        (try_begin),
          #validity check
          (player_is_admin, ":player_no"),
          (is_between, ":value", 60, 901),
          #condition checks are done
          (assign, "$g_multiplayer_round_max_seconds", ":value"),
          (get_max_players, ":num_players"),
          (try_for_range, ":cur_player", 1, ":num_players"),
            (player_is_active, ":cur_player"),
            (multiplayer_send_int_to_player, ":cur_player", multiplayer_event_return_round_max_seconds, ":value"),
          (try_end),            
        (try_end),
      (else_try),
        (eq, ":event_type", multiplayer_event_admin_set_player_respawn_as_bot),
        (store_script_param, ":value", 3),
        (try_begin),
          #validity check
          (player_is_admin, ":player_no"),
          (is_between, ":value", 0, 2),
          #condition checks are done
          (assign, "$g_multiplayer_player_respawn_as_bot", ":value"),
          (get_max_players, ":num_players"),
          (try_for_range, ":cur_player", 1, ":num_players"),
            (player_is_active, ":cur_player"),
            (multiplayer_send_int_to_player, ":cur_player", multiplayer_event_return_player_respawn_as_bot, ":value"),
          (try_end),            
        (try_end),
      (else_try),
        (eq, ":event_type", multiplayer_event_admin_set_game_max_points),
        (store_script_param, ":value", 3),
        (try_begin),
          #validity check
          (player_is_admin, ":player_no"),
          (is_between, ":value", 3, 1001),
          #condition checks are done
          (assign, "$g_multiplayer_game_max_points", ":value"),
        (try_end),
      (else_try),
        (eq, ":event_type", multiplayer_event_admin_set_point_gained_from_flags),
        (store_script_param, ":value", 3),
        (try_begin),
          #validity check
          (player_is_admin, ":player_no"),
          (is_between, ":value", 25, 401),
          #condition checks are done
          (assign, "$g_multiplayer_point_gained_from_flags", ":value"),
        (try_end),
      (else_try),
        (eq, ":event_type", multiplayer_event_admin_set_point_gained_from_capturing_flag),
        (store_script_param, ":value", 3),
        (try_begin),
          #validity check
          (player_is_admin, ":player_no"),
          (is_between, ":value", 0, 11),
          #condition checks are done
          (assign, "$g_multiplayer_point_gained_from_capturing_flag", ":value"),
        (try_end),
      (else_try),
        (eq, ":event_type", multiplayer_event_admin_set_initial_gold_multiplier),
        (store_script_param, ":value", 3),
        (try_begin),
          #validity check
          (player_is_admin, ":player_no"),
          (is_between, ":value", 0, 1001),
          #condition checks are done
          (assign, "$g_multiplayer_initial_gold_multiplier", ":value"),
        (try_end),
      (else_try),
        (eq, ":event_type", multiplayer_event_admin_set_battle_earnings_multiplier),
        (store_script_param, ":value", 3),
        (try_begin),
          #validity check
          (player_is_admin, ":player_no"),
          (is_between, ":value", 0, 1001),
          #condition checks are done
          (assign, "$g_multiplayer_battle_earnings_multiplier", ":value"),
        (try_end),
      (else_try),
        (eq, ":event_type", multiplayer_event_admin_set_round_earnings_multiplier),
        (store_script_param, ":value", 3),
        (try_begin),
          #validity check
          (player_is_admin, ":player_no"),
          (is_between, ":value", 0, 1001),
          #condition checks are done
          (assign, "$g_multiplayer_round_earnings_multiplier", ":value"),
        (try_end),
      (else_try),
        (eq, ":event_type", multiplayer_event_admin_set_server_name),
        (try_begin),
          #validity check
          (player_is_admin, ":player_no"),
          (server_get_renaming_server_allowed, "$g_multiplayer_renaming_server_allowed"),
          (eq, "$g_multiplayer_renaming_server_allowed", 1),
          #condition checks are done
          (server_set_name, s0), #validity is checked inside this function
        (try_end),
      (else_try),
        (eq, ":event_type", multiplayer_event_admin_set_game_password),
        (try_begin),
          #validity check
          (player_is_admin, ":player_no"),
          #condition checks are done
          (server_set_password, s0), #validity is checked inside this function
        (try_end),
      (else_try),
        (eq, ":event_type", multiplayer_event_admin_set_welcome_message),
        (try_begin),
          #validity check
          (player_is_admin, ":player_no"),
          #condition checks are done
          (server_set_welcome_message, s0), #validity is checked inside this function
        (try_end),
      (else_try),
        (eq, ":event_type", multiplayer_event_admin_set_team_faction),
        (store_script_param, ":value", 3),
        (store_script_param, ":value_2", 4),
        (try_begin),
          #validity check
          (player_is_admin, ":player_no"),
          (is_between, ":value", 1, 3),
          (is_between, ":value_2", npc_kingdoms_begin, npc_kingdoms_end),
##          (assign, ":is_valid", 0),
##          (try_begin),
##            (eq, ":value", 1),
##            (neq, ":value_2", "$g_multiplayer_next_team_2_faction"),
##            (assign, ":is_valid", 1),
##          (else_try),
##            (neq, ":value_2", "$g_multiplayer_next_team_1_faction"),
##            (assign, ":is_valid", 1),
##          (try_end),
##          (eq, ":is_valid", 1),
          #condition checks are done
          (try_begin),
            (eq, ":value", 1),
            (assign, "$g_multiplayer_next_team_1_faction", ":value_2"),
          (else_try),
            (assign, "$g_multiplayer_next_team_2_faction", ":value_2"),
          (try_end),
        (try_end),
      (else_try),
        (eq, ":event_type", multiplayer_event_open_game_rules),
        (try_begin),
          #no validity check
          (server_get_max_num_players, ":max_num_players"),
          (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_max_num_players, ":max_num_players"),
          (multiplayer_send_2_int_to_player, ":player_no", multiplayer_event_return_next_team_faction, 1, "$g_multiplayer_next_team_1_faction"),
          (multiplayer_send_2_int_to_player, ":player_no", multiplayer_event_return_next_team_faction, 2, "$g_multiplayer_next_team_2_faction"),
          (multiplayer_send_2_int_to_player, ":player_no", multiplayer_event_return_num_bots_in_team, 1, "$g_multiplayer_num_bots_team_1"),
          (multiplayer_send_2_int_to_player, ":player_no", multiplayer_event_return_num_bots_in_team, 2, "$g_multiplayer_num_bots_team_2"),
          (server_get_anti_cheat, ":server_anti_cheat"),
          (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_anti_cheat, ":server_anti_cheat"),
          (server_get_friendly_fire, ":server_friendly_fire"),
          (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_friendly_fire, ":server_friendly_fire"),
          (server_get_melee_friendly_fire, ":server_melee_friendly_fire"),
          (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_melee_friendly_fire, ":server_melee_friendly_fire"),
          (server_get_friendly_fire_damage_self_ratio, ":friendly_fire_damage_self_ratio"),
          (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_friendly_fire_damage_self_ratio, ":friendly_fire_damage_self_ratio"),
          (server_get_friendly_fire_damage_friend_ratio, ":friendly_fire_damage_friend_ratio"),
          (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_friendly_fire_damage_friend_ratio, ":friendly_fire_damage_friend_ratio"),
          (server_get_ghost_mode, ":server_ghost_mode"),
          (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_ghost_mode, ":server_ghost_mode"),
          (server_get_control_block_dir, ":server_control_block_dir"),
          (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_control_block_dir, ":server_control_block_dir"),
          (server_get_combat_speed, ":server_combat_speed"),
          (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_combat_speed, ":server_combat_speed"),
          (server_get_add_to_game_servers_list, ":server_add_to_servers_list"),
          (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_add_to_servers_list, ":server_add_to_servers_list"),
          (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_respawn_period, "$g_multiplayer_respawn_period"),
          (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_game_max_minutes, "$g_multiplayer_game_max_minutes"),
          (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_round_max_seconds, "$g_multiplayer_round_max_seconds"),
          (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_player_respawn_as_bot, "$g_multiplayer_player_respawn_as_bot"),
          (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_game_max_points, "$g_multiplayer_game_max_points"),
          (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_point_gained_from_flags, "$g_multiplayer_point_gained_from_flags"),
          (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_point_gained_from_capturing_flag, "$g_multiplayer_point_gained_from_capturing_flag"),
          (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_initial_gold_multiplier, "$g_multiplayer_initial_gold_multiplier"),
          (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_battle_earnings_multiplier, "$g_multiplayer_battle_earnings_multiplier"),
          (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_round_earnings_multiplier, "$g_multiplayer_round_earnings_multiplier"),
          (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_valid_vote_ratio, "$g_multiplayer_valid_vote_ratio"),
          (str_store_server_name, s0),
          (multiplayer_send_string_to_player, ":player_no", multiplayer_event_return_server_name, s0),
          (multiplayer_send_message_to_player, ":player_no", multiplayer_event_return_open_game_rules),
        (try_end),
      (else_try),
        (eq, ":event_type", multiplayer_event_open_admin_panel),
        (try_begin),
          #validity check
          (player_is_admin, ":player_no"),
          #condition checks are done
          (server_get_renaming_server_allowed, "$g_multiplayer_renaming_server_allowed"),
          (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_renaming_server_allowed, "$g_multiplayer_renaming_server_allowed"),
          (server_get_changing_game_type_allowed, "$g_multiplayer_changing_game_type_allowed"),
          (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_changing_game_type_allowed, "$g_multiplayer_changing_game_type_allowed"),
          (server_get_max_num_players, ":max_num_players"),
          (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_max_num_players, ":max_num_players"),
          (multiplayer_send_2_int_to_player, ":player_no", multiplayer_event_return_next_team_faction, 1, "$g_multiplayer_next_team_1_faction"),
          (multiplayer_send_2_int_to_player, ":player_no", multiplayer_event_return_next_team_faction, 2, "$g_multiplayer_next_team_2_faction"),
          (multiplayer_send_2_int_to_player, ":player_no", multiplayer_event_return_num_bots_in_team, 1, "$g_multiplayer_num_bots_team_1"),
          (multiplayer_send_2_int_to_player, ":player_no", multiplayer_event_return_num_bots_in_team, 2, "$g_multiplayer_num_bots_team_2"),
          (server_get_anti_cheat, ":server_anti_cheat"),
          (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_anti_cheat, ":server_anti_cheat"),
          (server_get_friendly_fire, ":server_friendly_fire"),
          (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_friendly_fire, ":server_friendly_fire"),
          (server_get_melee_friendly_fire, ":server_melee_friendly_fire"),
          (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_melee_friendly_fire, ":server_melee_friendly_fire"),
          (server_get_friendly_fire_damage_self_ratio, ":friendly_fire_damage_self_ratio"),
          (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_friendly_fire_damage_self_ratio, ":friendly_fire_damage_self_ratio"),
          (server_get_friendly_fire_damage_friend_ratio, ":friendly_fire_damage_friend_ratio"),
          (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_friendly_fire_damage_friend_ratio, ":friendly_fire_damage_friend_ratio"),
          (server_get_ghost_mode, ":server_ghost_mode"),
          (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_ghost_mode, ":server_ghost_mode"),
          (server_get_control_block_dir, ":server_control_block_dir"),
          (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_control_block_dir, ":server_control_block_dir"),
          (server_get_combat_speed, ":server_combat_speed"),
          (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_combat_speed, ":server_combat_speed"),
          (server_get_add_to_game_servers_list, ":server_add_to_servers_list"),
          (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_add_to_servers_list, ":server_add_to_servers_list"),
          (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_respawn_period, "$g_multiplayer_respawn_period"),
          (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_game_max_minutes, "$g_multiplayer_game_max_minutes"),
          (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_round_max_seconds, "$g_multiplayer_round_max_seconds"),
          (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_player_respawn_as_bot, "$g_multiplayer_player_respawn_as_bot"),
          (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_game_max_points, "$g_multiplayer_game_max_points"),
          (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_point_gained_from_flags, "$g_multiplayer_point_gained_from_flags"),
          (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_point_gained_from_capturing_flag, "$g_multiplayer_point_gained_from_capturing_flag"),
          (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_initial_gold_multiplier, "$g_multiplayer_initial_gold_multiplier"),
          (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_battle_earnings_multiplier, "$g_multiplayer_battle_earnings_multiplier"),
          (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_round_earnings_multiplier, "$g_multiplayer_round_earnings_multiplier"),
          (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_valid_vote_ratio, "$g_multiplayer_valid_vote_ratio"),
          (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_max_num_bots, "$g_multiplayer_max_num_bots"),
          (str_store_server_name, s0),
          (multiplayer_send_string_to_player, ":player_no", multiplayer_event_return_server_name, s0),
          (str_store_server_password, s0),
          (multiplayer_send_string_to_player, ":player_no", multiplayer_event_return_game_password, s0),
        (try_end),
      (else_try),
        (eq, ":event_type", multiplayer_event_start_new_poll),
        (try_begin),
          (store_script_param, ":value", 3),
          (store_script_param, ":value_2", 4),
           #validity check
          (eq, "$g_multiplayer_poll_running", 0),
          (store_mission_timer_a, ":mission_timer"),
          (player_get_slot, ":poll_disable_time", ":player_no", slot_player_poll_disabled_until_time),
          (ge, ":mission_timer", ":poll_disable_time"),
          (assign, ":continue", 0),
          (try_begin),
            (eq, ":value", 1), # kicking a player
            (try_begin),
              (eq, "$g_multiplayer_kick_voteable", 1),
              (player_is_active, ":value_2"),
              (assign, ":continue", 1),
            (try_end),
          (else_try),
            (eq, ":value", 2), # banning a player
            (try_begin),
              (eq, "$g_multiplayer_ban_voteable", 1),
              (player_is_active, ":value_2"),
              (save_ban_info_of_player, ":value_2"),
              (assign, ":continue", 1),
            (try_end),
          (else_try), # vote for map
            (eq, ":value", 0),
            (try_begin),
              (eq, "$g_multiplayer_maps_voteable", 1),
              (call_script, "script_multiplayer_fill_map_game_types", "$g_multiplayer_game_type"),
              (assign, ":num_maps", reg0),
              (try_for_range, ":i_map", 0, ":num_maps"),
                (store_add, ":map_slot", ":i_map", multi_data_maps_for_game_type_begin),
                (troop_slot_eq, "trp_multiplayer_data", ":map_slot", ":value_2"),
                (assign, ":continue", 1),
                (assign, ":num_maps", 0), #break
              (try_end),
            (try_end),
          (else_try),
            (eq, ":value", 3), #vote for map and factions
            (try_begin),
              (eq, "$g_multiplayer_factions_voteable", 1),
              (store_script_param, ":value_3", 5),
              (store_script_param, ":value_4", 6),
              (call_script, "script_multiplayer_fill_map_game_types", "$g_multiplayer_game_type"),
              (assign, ":num_maps", reg0),
              (try_for_range, ":i_map", 0, ":num_maps"),
                (store_add, ":map_slot", ":i_map", multi_data_maps_for_game_type_begin),
                (troop_slot_eq, "trp_multiplayer_data", ":map_slot", ":value_2"),
                (assign, ":continue", 1),
                (assign, ":num_maps", 0), #break
              (try_end),
              (try_begin),
                (eq, ":continue", 1),
                (this_or_next|neg|is_between, ":value_3", npc_kingdoms_begin, npc_kingdoms_end),
                (this_or_next|neg|is_between, ":value_4", npc_kingdoms_begin, npc_kingdoms_end),
                (eq, ":value_3", ":value_4"),
                (assign, ":continue", 0),
              (try_end),
            (try_end),
          (else_try),
            (eq, ":value", 4), #vote for number of bots
            (store_script_param, ":value_3", 5),
            (store_add, ":upper_limit", "$g_multiplayer_num_bots_voteable", 1),
            (is_between, ":value_2", 0, ":upper_limit"),
            (is_between, ":value_3", 0, ":upper_limit"),
            (assign, ":continue", 1),
          (try_end),
          (eq, ":continue", 1),
          #condition checks are done
          (str_store_player_username, s0, ":player_no"),
          (try_begin),
            (eq, ":value", 1), #kicking a player
            (str_store_player_username, s1, ":value_2"),
            (server_add_message_to_log, "str_poll_kick_player_s1_by_s0"),
          (else_try),
            (eq, ":value", 2), #banning a player
            (str_store_player_username, s1, ":value_2"),
            (server_add_message_to_log, "str_poll_ban_player_s1_by_s0"),
          (else_try),
            (eq, ":value", 0), #vote for map
            (store_sub, ":string_index", ":value_2", multiplayer_scenes_begin),
            (val_add, ":string_index", multiplayer_scene_names_begin),
            (str_store_string, s1, ":string_index"),
            (server_add_message_to_log, "str_poll_change_map_to_s1_by_s0"),
          (else_try),
            (eq, ":value", 3), #vote for map and factions
            (store_sub, ":string_index", ":value_2", multiplayer_scenes_begin),
            (val_add, ":string_index", multiplayer_scene_names_begin),
            (str_store_string, s1, ":string_index"),
            (str_store_faction_name, s2, ":value_3"),
            (str_store_faction_name, s3, ":value_4"),
            (server_add_message_to_log, "str_poll_change_map_to_s1_and_factions_to_s2_and_s3_by_s0"),
          (else_try),
            (eq, ":value", 4), #vote for number of bots
            (assign, reg0, ":value_2"),
            (assign, reg1, ":value_3"),
            (server_add_message_to_log, "str_poll_change_number_of_bots_to_reg0_and_reg1_by_s0"),
          (try_end),
          (assign, "$g_multiplayer_poll_running", 1),
          (assign, "$g_multiplayer_poll_ended", 0),
          (assign, "$g_multiplayer_poll_num_sent", 0),
          (assign, "$g_multiplayer_poll_yes_count", 0),
          (assign, "$g_multiplayer_poll_no_count", 0),
          (assign, "$g_multiplayer_poll_to_show", ":value"),
          (assign, "$g_multiplayer_poll_value_to_show", ":value_2"),
          (try_begin),
            (eq, ":value", 3),
            (assign, "$g_multiplayer_poll_value_2_to_show", ":value_3"),
            (assign, "$g_multiplayer_poll_value_3_to_show", ":value_4"),
          (else_try),
            (eq, ":value", 4),
            (assign, "$g_multiplayer_poll_value_2_to_show", ":value_3"),
            (assign, "$g_multiplayer_poll_value_3_to_show", -1),
          (else_try),
            (assign, "$g_multiplayer_poll_value_2_to_show", -1),
            (assign, "$g_multiplayer_poll_value_3_to_show", -1),
          (try_end),
          (store_add, ":poll_disable_until", ":mission_timer", multiplayer_poll_disable_period),
          (player_set_slot, ":player_no", slot_player_poll_disabled_until_time, ":poll_disable_until"),
          (store_add, "$g_multiplayer_poll_end_time", ":mission_timer", 60),
          (get_max_players, ":num_players"),
          (try_for_range, ":cur_player", 0, ":num_players"),
            (player_is_active, ":cur_player"),
            (player_set_slot, ":cur_player", slot_player_can_answer_poll, 1),
            (val_add, "$g_multiplayer_poll_num_sent", 1),
            (multiplayer_send_4_int_to_player, ":cur_player", multiplayer_event_ask_for_poll, "$g_multiplayer_poll_to_show", "$g_multiplayer_poll_value_to_show", "$g_multiplayer_poll_value_2_to_show", "$g_multiplayer_poll_value_3_to_show"),
          (try_end),
        (try_end),
      (else_try),
        (eq, ":event_type", multiplayer_event_answer_to_poll),
        (try_begin),
          (store_script_param, ":value", 3),
          #validity check
          (eq, "$g_multiplayer_poll_running", 1),
          (is_between, ":value", 0, 2),
          (player_slot_eq, ":player_no", slot_player_can_answer_poll, 1),
          #condition checks are done
          (player_set_slot, ":player_no", slot_player_can_answer_poll, 0),
          (try_begin),
            (eq, ":value", 0),
            (val_add, "$g_multiplayer_poll_no_count", 1),
          (else_try),
            (eq, ":value", 1),
            (val_add, "$g_multiplayer_poll_yes_count", 1),
          (try_end),
        (try_end),
      (else_try),
        (eq, ":event_type", multiplayer_event_admin_kick_player),
        (try_begin),
          (store_script_param, ":value", 3),
          #validity check
          (player_is_admin, ":player_no"),
          (player_is_active, ":value"),
          #condition checks are done
          (kick_player, ":value"),
        (try_end),
      (else_try),
        (eq, ":event_type", multiplayer_event_admin_ban_player),
        (try_begin),
          (store_script_param, ":value", 3),
          #validity check
          (player_is_admin, ":player_no"),
          (player_is_active, ":value"),
          #condition checks are done
          (ban_player, ":value", 0, ":player_no"),
        (try_end),
      (else_try),
        (eq, ":event_type", multiplayer_event_admin_set_valid_vote_ratio),
        (try_begin),
          (store_script_param, ":value", 3),
          #validity check
          (player_is_admin, ":player_no"),
          (is_between, ":value", 50, 101),
          #condition checks are done
          (assign, "$g_multiplayer_valid_vote_ratio", ":value"),
        (try_end),
      (else_try),
        (eq, ":event_type", multiplayer_event_admin_set_auto_team_balance_limit),
        (try_begin),
          (store_script_param, ":value", 3),
          #validity check
          (player_is_admin, ":player_no"),
          (this_or_next|is_between, ":value", 2, 7),
          (eq, ":value", 1000),
          #condition checks are done
          (assign, "$g_multiplayer_auto_team_balance_limit", ":value"),
          (get_max_players, ":num_players"),
          (try_for_range, ":cur_player", 1, ":num_players"),
            (player_is_active, ":cur_player"),
            (multiplayer_send_int_to_player, ":cur_player", multiplayer_event_return_auto_team_balance_limit, ":value"),
          (try_end),
        (try_end),
      (else_try),
        (eq, ":event_type", multiplayer_event_admin_set_num_bots_voteable),
        (try_begin),
          (store_script_param, ":value", 3),
          #validity check
          (player_is_admin, ":player_no"),
          (is_between, ":value", 0, 51),
          (is_between, ":value", "$g_multiplayer_max_num_bots"),
          #condition checks are done
          (assign, "$g_multiplayer_num_bots_voteable", ":value"),
          (get_max_players, ":num_players"),
          (try_for_range, ":cur_player", 1, ":num_players"),
            (player_is_active, ":cur_player"),
            (multiplayer_send_int_to_player, ":cur_player", multiplayer_event_return_num_bots_voteable, ":value"),
          (try_end),
        (try_end),
      (else_try),
        (eq, ":event_type", multiplayer_event_admin_set_factions_voteable),
        (try_begin),
          (store_script_param, ":value", 3),
          #validity check
          (player_is_admin, ":player_no"),
          (is_between, ":value", 0, 2),
          #condition checks are done
          (assign, "$g_multiplayer_factions_voteable", ":value"),
          (get_max_players, ":num_players"),
          (try_for_range, ":cur_player", 1, ":num_players"),
            (player_is_active, ":cur_player"),
            (multiplayer_send_int_to_player, ":cur_player", multiplayer_event_return_factions_voteable, ":value"),
          (try_end),
        (try_end),
      (else_try),
        (eq, ":event_type", multiplayer_event_admin_set_maps_voteable),
        (try_begin),
          (store_script_param, ":value", 3),
          #validity check
          (player_is_admin, ":player_no"),
          (is_between, ":value", 0, 2),
          #condition checks are done
          (assign, "$g_multiplayer_maps_voteable", ":value"),
          (get_max_players, ":num_players"),
          (try_for_range, ":cur_player", 1, ":num_players"),
            (player_is_active, ":cur_player"),
            (multiplayer_send_int_to_player, ":cur_player", multiplayer_event_return_maps_voteable, ":value"),
          (try_end),
        (try_end),
      (else_try),
        (eq, ":event_type", multiplayer_event_admin_set_kick_voteable),
        (try_begin),
          (store_script_param, ":value", 3),
          #validity check
          (player_is_admin, ":player_no"),
          (is_between, ":value", 0, 2),
          #condition checks are done
          (assign, "$g_multiplayer_kick_voteable", ":value"),
          (get_max_players, ":num_players"),
          (try_for_range, ":cur_player", 1, ":num_players"),
            (player_is_active, ":cur_player"),
            (multiplayer_send_int_to_player, ":cur_player", multiplayer_event_return_kick_voteable, ":value"),
          (try_end),
        (try_end),
      (else_try),
        (eq, ":event_type", multiplayer_event_admin_set_ban_voteable),
        (try_begin),
          (store_script_param, ":value", 3),
          #validity check
          (player_is_admin, ":player_no"),
          (is_between, ":value", 0, 2),
          #condition checks are done
          (assign, "$g_multiplayer_ban_voteable", ":value"),
          (get_max_players, ":num_players"),
          (try_for_range, ":cur_player", 1, ":num_players"),
            (player_is_active, ":cur_player"),
            (multiplayer_send_int_to_player, ":cur_player", multiplayer_event_return_ban_voteable, ":value"),
          (try_end),
        (try_end),
      (else_try),
        (eq, ":event_type", multiplayer_event_admin_set_allow_player_banners),
        (try_begin),
          (store_script_param, ":value", 3),
          #validity check
          (player_is_admin, ":player_no"),
          (is_between, ":value", 0, 2),
          #condition checks are done
          (assign, "$g_multiplayer_allow_player_banners", ":value"),
        (try_end),
      (else_try),
        (eq, ":event_type", multiplayer_event_admin_set_force_default_armor),
        (try_begin),
          (store_script_param, ":value", 3),
          #validity check
          (player_is_admin, ":player_no"),
          (is_between, ":value", 0, 2),
          #condition checks are done
          (assign, "$g_multiplayer_force_default_armor", ":value"),
        (try_end),
      (else_try),
        (eq, ":event_type", multiplayer_event_offer_duel),
        (try_begin),
          (store_script_param, ":value", 3),
          #validity check
          (eq, "$g_multiplayer_game_type", multiplayer_game_type_duel),
          (agent_is_active, ":value"),
          (agent_is_alive, ":value"),
          (agent_is_human, ":value"),
          (player_get_agent_id, ":player_agent_no", ":player_no"),
          (agent_is_active, ":player_agent_no"),
          (agent_is_alive, ":player_agent_no"),
          (agent_get_position, pos0, ":player_agent_no"),
          (agent_get_position, pos1, ":value"),
          (get_sq_distance_between_positions_in_meters, ":agent_dist_sq", pos0, pos1),
          (le, ":agent_dist_sq", 49),
          #allow duelists to receive new offers
          (this_or_next|agent_check_offer_from_agent, ":player_agent_no", ":value"),
          (agent_slot_eq, ":player_agent_no", slot_agent_in_duel_with, -1),
          (neg|agent_slot_eq, ":player_agent_no", slot_agent_in_duel_with, ":value"), #don't allow spamming duel offers during countdown
          #condition checks are done
          (try_begin),
            #accepting a duel
            (agent_check_offer_from_agent, ":player_agent_no", ":value"),
            (call_script, "script_multiplayer_accept_duel", ":player_agent_no", ":value"),
          (else_try),
            #sending a duel request
            (assign, ":display_notification", 1),
            (try_begin),
              (agent_check_offer_from_agent, ":value", ":player_agent_no"),
              (assign, ":display_notification", 0),
            (try_end),
            (agent_add_offer_with_timeout, ":value", ":player_agent_no", 10000), #10 second timeout
            (agent_get_player_id, ":value_player", ":value"),
            (try_begin),
              (player_is_active, ":value_player"), #might be AI
              (try_begin),
                (eq, ":display_notification", 1),
                (multiplayer_send_int_to_player, ":value_player", multiplayer_event_show_duel_request, ":player_agent_no"),
              (try_end),
            (else_try),
              (call_script, "script_multiplayer_accept_duel", ":value", ":player_agent_no"),
            (try_end),
          (try_end),
        (try_end),
      (else_try),
        (eq, ":event_type", multiplayer_event_admin_set_disallow_ranged_weapons),
        (try_begin),
          (store_script_param, ":value", 3),
          #validity check
          (player_is_admin, ":player_no"),
          (is_between, ":value", 0, 2),
          #condition checks are done
          (assign, "$g_multiplayer_disallow_ranged_weapons", ":value"),
        (try_end),
      (else_try),
        ###############
        #CLIENT EVENTS#
        ###############
        (neg|multiplayer_is_dedicated_server),
        (try_begin),      
          (eq, ":event_type", multiplayer_event_return_renaming_server_allowed),
          (store_script_param, ":value", 3),
          (assign, "$g_multiplayer_renaming_server_allowed", ":value"),
        (else_try),
          (eq, ":event_type", multiplayer_event_return_changing_game_type_allowed),
          (store_script_param, ":value", 3),
          (assign, "$g_multiplayer_changing_game_type_allowed", ":value"),
        (else_try),
          (eq, ":event_type", multiplayer_event_return_max_num_players),
          (store_script_param, ":value", 3),
          (server_set_max_num_players, ":value"),
        (else_try),
          (eq, ":event_type", multiplayer_event_return_next_team_faction),
          (store_script_param, ":value", 3),
          (store_script_param, ":value_2", 4),
          (try_begin),
            (eq, ":value", 1),
            (assign, "$g_multiplayer_next_team_1_faction", ":value_2"),
          (else_try),
            (assign, "$g_multiplayer_next_team_2_faction", ":value_2"),
          (try_end),
        (else_try),
          (eq, ":event_type", multiplayer_event_return_num_bots_in_team),
          (store_script_param, ":value", 3),
          (store_script_param, ":value_2", 4),
          (try_begin),
            (eq, ":value", 1),
            (assign, "$g_multiplayer_num_bots_team_1", ":value_2"),
          (else_try),
            (assign, "$g_multiplayer_num_bots_team_2", ":value_2"),
          (try_end),
        (else_try),
          (eq, ":event_type", multiplayer_event_return_anti_cheat),
          (store_script_param, ":value", 3),
          (server_set_anti_cheat, ":value"),
        (else_try),
          (eq, ":event_type", multiplayer_event_return_friendly_fire),
          (store_script_param, ":value", 3),
          (server_set_friendly_fire, ":value"),
        (else_try),
          (eq, ":event_type", multiplayer_event_return_melee_friendly_fire),
          (store_script_param, ":value", 3),
          (server_set_melee_friendly_fire, ":value"),
        (else_try),
          (eq, ":event_type", multiplayer_event_return_friendly_fire_damage_self_ratio),
          (store_script_param, ":value", 3),
          (server_set_friendly_fire_damage_self_ratio, ":value"),
        (else_try),
          (eq, ":event_type", multiplayer_event_return_friendly_fire_damage_friend_ratio),
          (store_script_param, ":value", 3),
          (server_set_friendly_fire_damage_friend_ratio, ":value"),
        (else_try),
          (eq, ":event_type", multiplayer_event_return_ghost_mode),
          (store_script_param, ":value", 3),
          (server_set_ghost_mode, ":value"),
        (else_try),
          (eq, ":event_type", multiplayer_event_return_control_block_dir),
          (store_script_param, ":value", 3),
          (server_set_control_block_dir, ":value"),
        (else_try),
          (eq, ":event_type", multiplayer_event_return_add_to_servers_list),
          (store_script_param, ":value", 3),
          (server_set_add_to_game_servers_list, ":value"),
        (else_try),
          (eq, ":event_type", multiplayer_event_return_respawn_period),
          (store_script_param, ":value", 3),
          (assign, "$g_multiplayer_respawn_period", ":value"),
        (else_try),
          (eq, ":event_type", multiplayer_event_return_game_max_minutes),
          (store_script_param, ":value", 3),
          (assign, "$g_multiplayer_game_max_minutes", ":value"),
        (else_try),
          (eq, ":event_type", multiplayer_event_return_round_max_seconds),
          (store_script_param, ":value", 3),
          (assign, "$g_multiplayer_round_max_seconds", ":value"),
        (else_try),
          (eq, ":event_type", multiplayer_event_return_player_respawn_as_bot),
          (store_script_param, ":value", 3),
          (assign, "$g_multiplayer_player_respawn_as_bot", ":value"),
        (else_try),
          (eq, ":event_type", multiplayer_event_return_game_max_points),
          (store_script_param, ":value", 3),
          (assign, "$g_multiplayer_game_max_points", ":value"),
        (else_try),
          (eq, ":event_type", multiplayer_event_return_point_gained_from_flags),
          (store_script_param, ":value", 3),
          (assign, "$g_multiplayer_point_gained_from_flags", ":value"),
        (else_try),
          (eq, ":event_type", multiplayer_event_return_point_gained_from_capturing_flag),
          (store_script_param, ":value", 3),
          (assign, "$g_multiplayer_point_gained_from_capturing_flag", ":value"),
        (else_try),
          (eq, ":event_type", multiplayer_event_return_initial_gold_multiplier),
          (store_script_param, ":value", 3),
          (assign, "$g_multiplayer_initial_gold_multiplier", ":value"),
        (else_try),
          (eq, ":event_type", multiplayer_event_return_battle_earnings_multiplier),
          (store_script_param, ":value", 3),
          (assign, "$g_multiplayer_battle_earnings_multiplier", ":value"),
        (else_try),
          (eq, ":event_type", multiplayer_event_return_round_earnings_multiplier),
          (store_script_param, ":value", 3),
          (assign, "$g_multiplayer_round_earnings_multiplier", ":value"),
        (else_try),
          (eq, ":event_type", multiplayer_event_return_respawn_count),
          (store_script_param, ":value", 3),
          (assign, "$g_multiplayer_number_of_respawn_count", ":value"),          
        (else_try),
          (eq, ":event_type", multiplayer_event_return_server_name),
          (server_set_name, s0),
        (else_try),
          (eq, ":event_type", multiplayer_event_return_game_password),
          (server_set_password, s0),
          #this is the last option in admin panel, so start the presentation
          (start_presentation, "prsnt_game_multiplayer_admin_panel"),
        (else_try),
          (eq, ":event_type", multiplayer_event_return_open_game_rules),
          #this is the last message for game rules, so start the presentation
          (assign, "$g_multiplayer_show_server_rules", 1),
          (start_presentation, "prsnt_multiplayer_welcome_message"),
        (else_try),
          (eq, ":event_type", multiplayer_event_return_game_type),
          (store_script_param, ":value", 3),
          (assign, "$g_multiplayer_game_type", ":value"),
        (else_try),
          (eq, ":event_type", multiplayer_event_return_valid_vote_ratio),
          (store_script_param, ":value", 3),
          (assign, "$g_multiplayer_valid_vote_ratio", ":value"),
        (else_try),
          (eq, ":event_type", multiplayer_event_return_max_num_bots),
          (store_script_param, ":value", 3),
          (assign, "$g_multiplayer_max_num_bots", ":value"),
        (else_try),
          (eq, ":event_type", multiplayer_event_return_server_mission_timer_while_player_joined),
          (store_script_param, ":value", 3),
          (assign, "$server_mission_timer_while_player_joined", ":value"),
        (else_try),
          (eq, ":event_type", multiplayer_event_return_auto_team_balance_limit),
          (store_script_param, ":value", 3),
          (assign, "$g_multiplayer_auto_team_balance_limit", ":value"),
        (else_try),
          (eq, ":event_type", multiplayer_event_return_num_bots_voteable),
          (store_script_param, ":value", 3),
          (assign, "$g_multiplayer_num_bots_voteable", ":value"),
        (else_try),
          (eq, ":event_type", multiplayer_event_return_factions_voteable),
          (store_script_param, ":value", 3),
          (assign, "$g_multiplayer_factions_voteable", ":value"),
        (else_try),
          (eq, ":event_type", multiplayer_event_return_maps_voteable),
          (store_script_param, ":value", 3),
          (assign, "$g_multiplayer_maps_voteable", ":value"),
        (else_try),
          (eq, ":event_type", multiplayer_event_return_kick_voteable),
          (store_script_param, ":value", 3),
          (assign, "$g_multiplayer_kick_voteable", ":value"),
        (else_try),
          (eq, ":event_type", multiplayer_event_return_ban_voteable),
          (store_script_param, ":value", 3),
          (assign, "$g_multiplayer_ban_voteable", ":value"),
        (else_try),
          (eq, ":event_type", multiplayer_event_return_allow_player_banners),
          (store_script_param, ":value", 3),
          (assign, "$g_multiplayer_allow_player_banners", ":value"),
        (else_try),
          (eq, ":event_type", multiplayer_event_return_force_default_armor),
          (store_script_param, ":value", 3),
          (assign, "$g_multiplayer_force_default_armor", ":value"),
        (else_try),
          (eq, ":event_type", multiplayer_event_return_disallow_ranged_weapons),
          (store_script_param, ":value", 3),
          (assign, "$g_multiplayer_disallow_ranged_weapons", ":value"),
        (else_try),
          (eq, ":event_type", multiplayer_event_return_confirmation),
          (assign, "$g_confirmation_result", 1),
        (else_try),
          (eq, ":event_type", multiplayer_event_return_rejection),
          (assign, "$g_confirmation_result", -1),
        (else_try),
          (eq, ":event_type", multiplayer_event_show_multiplayer_message),
          (store_script_param, ":value", 3),
          (store_script_param, ":value_2", 4),
          (call_script, "script_show_multiplayer_message", ":value", ":value_2"),
        (else_try),
          (eq, ":event_type", multiplayer_event_draw_this_round),
          (store_script_param, ":value", 3),          
          (call_script, "script_draw_this_round", ":value"),
        (else_try),
          (eq, ":event_type", multiplayer_event_set_attached_scene_prop),
          (store_script_param, ":value", 3),
          (store_script_param, ":value_2", 4),
          (call_script, "script_set_attached_scene_prop", ":value", ":value_2"), 
          (try_begin),
            (eq, "$g_multiplayer_game_type", multiplayer_game_type_capture_the_flag),
            (try_begin),
              (neq, ":value_2", -1),
              (agent_set_horse_speed_factor, ":value", 75),
            (else_try),
              (agent_set_horse_speed_factor, ":value", 100),
            (try_end),              
          (try_end),  
        (else_try),
          (eq, ":event_type", multiplayer_event_set_team_flag_situation),
          (store_script_param, ":value", 3),
          (store_script_param, ":value_2", 4),
          (call_script, "script_set_team_flag_situation", ":value", ":value_2"),
        (else_try),
          (eq, ":event_type", multiplayer_event_set_team_score),
          (store_script_param, ":value", 3),
          (store_script_param, ":value_2", 4),
          (call_script, "script_team_set_score", ":value", ":value_2"),
        (else_try),
          (eq, ":event_type", multiplayer_event_set_player_score_kill_death), 
          (store_script_param, ":value", 3),
          (store_script_param, ":value_2", 4),
          (store_script_param, ":value_3", 5),
          (store_script_param, ":value_4", 6),
          (call_script, "script_player_set_score", ":value", ":value_2"),
          (call_script, "script_player_set_kill_count", ":value", ":value_3"),
          (call_script, "script_player_set_death_count", ":value", ":value_4"),
        (else_try),
          (eq, ":event_type", multiplayer_event_set_num_agents_around_flag),
          (store_script_param, ":flag_no", 3),
          (store_script_param, ":current_owner_code", 4),
          (call_script, "script_set_num_agents_around_flag", ":flag_no", ":current_owner_code"),
        (else_try),
          (eq, ":event_type", multiplayer_event_ask_for_poll),
          (store_script_param, ":value", 3),
          (store_script_param, ":value_2", 4),
          (store_script_param, ":value_3", 5),
          (store_script_param, ":value_4", 6),
          (assign, ":continue_to_poll", 0),
          (try_begin),
            (this_or_next|eq, ":value", 1),
            (eq, ":value", 2),
            (player_is_active, ":value_2"), #might go offline before here
            (assign, ":continue_to_poll", 1),
          (else_try),
            (assign, ":continue_to_poll", 1),
          (try_end),
          (try_begin),
            (eq, ":continue_to_poll", 1),
            (assign, "$g_multiplayer_poll_to_show", ":value"),
            (assign, "$g_multiplayer_poll_value_to_show", ":value_2"),
            (assign, "$g_multiplayer_poll_value_2_to_show", ":value_3"),
            (assign, "$g_multiplayer_poll_value_3_to_show", ":value_4"),
            (store_mission_timer_a, ":mission_timer"),
            (store_add, "$g_multiplayer_poll_client_end_time", ":mission_timer", 60),
            (start_presentation, "prsnt_multiplayer_poll"),
          (try_end),
        (else_try),
          (eq, ":event_type", multiplayer_event_change_flag_owner),
          (store_script_param, ":flag_no", 3),
          (store_script_param, ":owner_code", 4),
          (call_script, "script_change_flag_owner", ":flag_no", ":owner_code"),
        (else_try),
          (eq, ":event_type", multiplayer_event_use_item),
          (store_script_param, ":value", 3),
          (store_script_param, ":value_2", 4),
          (call_script, "script_use_item", ":value", ":value_2"),
        (else_try),
          (eq, ":event_type", multiplayer_event_set_scene_prop_open_or_close),
          (store_script_param, ":instance_id", 3),       
        
          (scene_prop_set_slot, ":instance_id", scene_prop_open_or_close_slot, 1),

          (prop_instance_get_scene_prop_kind, ":scene_prop_id", ":instance_id"),

          (try_begin),
            (eq, ":scene_prop_id", "spr_winch_b"),
            (assign, ":effected_object", "spr_portcullis"),
          (else_try),
            (this_or_next|eq, ":scene_prop_id", "spr_castle_e_sally_door_a"),
            (this_or_next|eq, ":scene_prop_id", "spr_castle_f_sally_door_a"),     
            (this_or_next|eq, ":scene_prop_id", "spr_earth_sally_gate_left"),     
            (this_or_next|eq, ":scene_prop_id", "spr_earth_sally_gate_right"),     
            (this_or_next|eq, ":scene_prop_id", "spr_viking_keep_destroy_sally_door_left"),                             
            (this_or_next|eq, ":scene_prop_id", "spr_viking_keep_destroy_sally_door_right"),                             
            (this_or_next|eq, ":scene_prop_id", "spr_castle_f_door_a"),
            (this_or_next|eq, ":scene_prop_id", "spr_door_destructible"),
            (this_or_next|eq, ":scene_prop_id", "spr_castle_f_door_b"),
            (this_or_next|eq, ":scene_prop_id", "spr_siege_ladder_move_6m"),
            (this_or_next|eq, ":scene_prop_id", "spr_siege_ladder_move_8m"),
            (this_or_next|eq, ":scene_prop_id", "spr_siege_ladder_move_10m"),
            (this_or_next|eq, ":scene_prop_id", "spr_siege_ladder_move_12m"),
            (eq, ":scene_prop_id", "spr_siege_ladder_move_14m"),
            (assign, ":effected_object", ":scene_prop_id"),
          (try_end),

          (try_begin),
            (eq, ":effected_object", "spr_portcullis"),

            (assign, ":smallest_dist", -1),
            (prop_instance_get_position, pos0, ":instance_id"),
            (scene_prop_get_num_instances, ":num_instances_of_effected_object", ":effected_object"),     
            (try_for_range, ":cur_instance", 0, ":num_instances_of_effected_object"),
              (scene_prop_get_instance, ":cur_instance_id", ":effected_object", ":cur_instance"),
              (prop_instance_get_position, pos1, ":cur_instance_id"),
              (get_sq_distance_between_positions, ":dist", pos0, pos1),
              (this_or_next|eq, ":smallest_dist", -1),
              (lt, ":dist", ":smallest_dist"),
              (assign, ":smallest_dist", ":dist"),
              (assign, ":effected_object_instance_id", ":cur_instance_id"),
            (try_end),

            (ge, ":smallest_dist", 0),
            (prop_instance_is_animating, ":is_animating", ":effected_object_instance_id"),
            (eq, ":is_animating", 0),

            (prop_instance_get_starting_position, pos0, ":effected_object_instance_id"),      
            (position_move_z, pos0, 375),
            (prop_instance_animate_to_position, ":effected_object_instance_id", pos0, 1),
          (else_try),
            (this_or_next|eq, ":scene_prop_id", "spr_castle_e_sally_door_a"),
            (this_or_next|eq, ":scene_prop_id", "spr_castle_f_sally_door_a"),     
            (this_or_next|eq, ":scene_prop_id", "spr_earth_sally_gate_left"),     
            (this_or_next|eq, ":scene_prop_id", "spr_earth_sally_gate_right"),     
            (this_or_next|eq, ":scene_prop_id", "spr_viking_keep_destroy_sally_door_left"),     
            (this_or_next|eq, ":scene_prop_id", "spr_viking_keep_destroy_sally_door_right"),     
            (this_or_next|eq, ":scene_prop_id", "spr_castle_f_door_a"),
            (this_or_next|eq, ":scene_prop_id", "spr_door_destructible"),
            (eq, ":scene_prop_id", "spr_castle_f_door_b"),
            (assign, ":effected_object_instance_id", ":instance_id"),  
            (prop_instance_get_starting_position, pos0, ":effected_object_instance_id"),
            (position_rotate_z, pos0, -80),
            (prop_instance_animate_to_position, ":effected_object_instance_id", pos0, 1),
          (else_try),
            (assign, ":effected_object_instance_id", ":instance_id"),
            (prop_instance_is_animating, ":is_animating", ":effected_object_instance_id"),
            (eq, ":is_animating", 0),
            (prop_instance_get_starting_position, pos0, ":effected_object_instance_id"),      
            (prop_instance_animate_to_position, ":effected_object_instance_id", pos0, 1),          
          (try_end),
        (else_try),
          (eq, ":event_type", multiplayer_event_set_round_start_time),
          (store_script_param, ":value", 3),

          (try_begin),
            (neq, ":value", -9999),
            (assign, "$g_round_start_time", ":value"),
          (else_try),
            (store_mission_timer_a, "$g_round_start_time"),

            #if round start time is assigning to current time (so new round is starting) then also initialize moveable object slots too.
            (call_script, "script_initialize_scene_prop_slots", "spr_siege_ladder_move_6m"),
            (call_script, "script_initialize_scene_prop_slots", "spr_siege_ladder_move_8m"),
            (call_script, "script_initialize_scene_prop_slots", "spr_siege_ladder_move_10m"),
            (call_script, "script_initialize_scene_prop_slots", "spr_siege_ladder_move_12m"),
            (call_script, "script_initialize_scene_prop_slots", "spr_siege_ladder_move_14m"),
            (call_script, "script_initialize_scene_prop_slots", "spr_winch_b"),         
          (try_end),
        (else_try),
          (eq, ":event_type", multiplayer_event_force_start_team_selection),
          (try_begin),
            (is_presentation_active, "prsnt_multiplayer_item_select"),
            (assign, "$g_close_equipment_selection", 1),
          (try_end),
          (start_presentation, "prsnt_multiplayer_troop_select"),
        (else_try),     
          (eq, ":event_type", multiplayer_event_start_death_mode),
          (assign, "$g_battle_death_mode_started", 2),
          (start_presentation, "prsnt_multiplayer_flag_projection_display_bt"),
          (call_script, "script_start_death_mode"),
        (else_try),
          (eq, ":event_type", multiplayer_event_return_player_respawn_spent),
          (store_script_param, ":value", 3),
          (try_begin),
            (gt, "$g_my_spawn_count", 0),
            (store_add, "$g_my_spawn_count", "$g_my_spawn_count", ":value"),
          (else_try),
            (assign, "$g_my_spawn_count", ":value"),      
          (try_end),
        (else_try),
          (eq, ":event_type", multiplayer_event_show_duel_request),
          (store_script_param, ":value", 3),
          (try_begin),
            (agent_is_active, ":value"),
            (agent_get_player_id, ":value_player_no", ":value"),
            (try_begin),
              (player_is_active, ":value_player_no"),
              (str_store_player_username, s0, ":value_player_no"),
            (else_try),
              (str_store_agent_name, s0, ":value"),
            (try_end),
            (display_message, "str_s0_offers_a_duel_with_you"),
            (try_begin),
              (get_player_agent_no, ":player_agent"),
              (agent_is_active, ":player_agent"),
              (agent_add_offer_with_timeout, ":player_agent", ":value", 10000), #10 second timeout
            (try_end),
          (try_end),
        (else_try),
          (eq, ":event_type", multiplayer_event_start_duel),
          (store_script_param, ":value", 3),
          (store_mission_timer_a, ":mission_timer"),
          (try_begin),
            (agent_is_active, ":value"),
            (get_player_agent_no, ":player_agent"),
            (agent_is_active, ":player_agent"),
            (agent_get_player_id, ":value_player_no", ":value"),
            (try_begin),
              (player_is_active, ":value_player_no"),
              (str_store_player_username, s0, ":value_player_no"),
            (else_try),
              (str_store_agent_name, s0, ":value"),
            (try_end),
            (display_message, "str_a_duel_between_you_and_s0_will_start_in_3_seconds"),
            (assign, "$g_multiplayer_duel_start_time", ":mission_timer"),
            (start_presentation, "prsnt_multiplayer_duel_start_counter"),
            (agent_set_slot, ":player_agent", slot_agent_in_duel_with, ":value"),
            (agent_set_slot, ":value", slot_agent_in_duel_with, ":player_agent"),
            (agent_set_slot, ":player_agent", slot_agent_duel_start_time, ":mission_timer"),
            (agent_set_slot, ":value", slot_agent_duel_start_time, ":mission_timer"),
            (agent_clear_relations_with_agents, ":player_agent"),
            (agent_clear_relations_with_agents, ":value"),
##            (agent_add_relation_with_agent, ":player_agent", ":value", -1),
          (try_end),
        (else_try),
          (eq, ":event_type", multiplayer_event_cancel_duel),
          (store_script_param, ":value", 3),
          (try_begin),
            (agent_is_active, ":value"),
            (agent_get_player_id, ":value_player_no", ":value"),
            (try_begin),
              (player_is_active, ":value_player_no"),
              (str_store_player_username, s0, ":value_player_no"),
            (else_try),
              (str_store_agent_name, s0, ":value"),
            (try_end),
            (display_message, "str_your_duel_with_s0_is_cancelled"),
          (try_end),
          (try_begin),
            (get_player_agent_no, ":player_agent"),
            (agent_is_active, ":player_agent"),
            (agent_set_slot, ":player_agent", slot_agent_in_duel_with, -1),
            (agent_clear_relations_with_agents, ":player_agent"),
          (try_end),
        (else_try),
          (eq, ":event_type", multiplayer_event_show_server_message),
          (display_message, "str_server_s0", 0xFFFF6666),
        (try_end),
      (try_end),
     ]),

  # script_cf_multiplayer_evaluate_poll
  # Input: none
  # Output: none (can fail)
  ("cf_multiplayer_evaluate_poll",
   [
     (assign, ":result", 0),
     (assign, "$g_multiplayer_poll_ended", 1),
     (store_add, ":total_votes", "$g_multiplayer_poll_yes_count", "$g_multiplayer_poll_no_count"),
     (store_sub, ":abstain_votes", "$g_multiplayer_poll_num_sent", ":total_votes"),
     (store_mul, ":nos_from_abstains", 3, ":abstain_votes"),
     (val_div, ":nos_from_abstains", 10), #30% of abstains are counted as no
     (val_add, ":total_votes", ":nos_from_abstains"),
     (val_max, ":total_votes", 1), #if someone votes and only 1-3 abstain occurs?
     (store_mul, ":vote_ratio", 100, "$g_multiplayer_poll_yes_count"),
     (val_div, ":vote_ratio", ":total_votes"),
     (try_begin),
       (ge, ":vote_ratio", "$g_multiplayer_valid_vote_ratio"),
       (assign, ":result", 1),
       (try_begin),
         (eq, "$g_multiplayer_poll_to_show", 1), #kick player
         (try_begin),
           (player_is_active, "$g_multiplayer_poll_value_to_show"),
           (kick_player, "$g_multiplayer_poll_value_to_show"),
         (try_end),
       (else_try),
         (eq, "$g_multiplayer_poll_to_show", 2), #ban player
         (ban_player_using_saved_ban_info), #already loaded at the beginning of the poll
       (else_try),
         (eq, "$g_multiplayer_poll_to_show", 3), #change map with factions
         (team_set_faction, 0, "$g_multiplayer_poll_value_2_to_show"),
         (team_set_faction, 1, "$g_multiplayer_poll_value_3_to_show"),
       (else_try),
         (eq, "$g_multiplayer_poll_to_show", 4), #change number of bots
         (assign, "$g_multiplayer_num_bots_team_1", "$g_multiplayer_poll_value_to_show"),
         (assign, "$g_multiplayer_num_bots_team_2", "$g_multiplayer_poll_value_2_to_show"),
         (get_max_players, ":num_players"),                               
         (try_for_range, ":cur_player", 1, ":num_players"),
           (player_is_active, ":cur_player"),
           (multiplayer_send_2_int_to_player, ":cur_player", multiplayer_event_return_num_bots_in_team, 1, "$g_multiplayer_num_bots_team_1"),
           (multiplayer_send_2_int_to_player, ":cur_player", multiplayer_event_return_num_bots_in_team, 2, "$g_multiplayer_num_bots_team_2"),
         (try_end),
       (try_end),
     (else_try),
       (assign, "$g_multiplayer_poll_running", 0), #end immediately if poll fails. but end after some time if poll succeeds (apply the results first)
     (try_end),
     (get_max_players, ":num_players"),
     #for only server itself-----------------------------------------------------------------------------------------------
     (call_script, "script_show_multiplayer_message", multiplayer_message_type_poll_result, ":result"), #0 is useless here
     #for only server itself-----------------------------------------------------------------------------------------------     
     (try_for_range, ":cur_player", 1, ":num_players"),
       (player_is_active, ":cur_player"),
       (multiplayer_send_2_int_to_player, ":cur_player", multiplayer_event_show_multiplayer_message, multiplayer_message_type_poll_result, ":result"),
     (try_end),
     (eq, ":result", 1),
     ]),

  # script_multiplayer_accept_duel
  # Input: arg1 = agent_no, arg2 = agent_no_offerer
  # Output: none
  ("multiplayer_accept_duel",
   [
     (store_script_param, ":agent_no", 1),
     (store_script_param, ":agent_no_offerer", 2),
     (try_begin),
       (agent_slot_ge, ":agent_no", slot_agent_in_duel_with, 0),
       (agent_get_slot, ":ex_duelist", ":agent_no", slot_agent_in_duel_with),
       (agent_is_active, ":ex_duelist"),
       (agent_clear_relations_with_agents, ":ex_duelist"),
       (agent_set_slot, ":ex_duelist", slot_agent_in_duel_with, -1),
       (agent_get_player_id, ":player_no", ":ex_duelist"),
       (try_begin),
         (player_is_active, ":player_no"), #might be AI
         (multiplayer_send_int_to_player, ":player_no", multiplayer_event_cancel_duel, ":agent_no"),
       (else_try),
         (agent_force_rethink, ":ex_duelist"),
       (try_end),
     (try_end),
     (try_begin),
       (agent_slot_ge, ":agent_no_offerer", slot_agent_in_duel_with, 0),
       (agent_get_slot, ":ex_duelist", ":agent_no_offerer", slot_agent_in_duel_with),
       (agent_is_active, ":ex_duelist"),
       (agent_clear_relations_with_agents, ":ex_duelist"),
       (agent_set_slot, ":ex_duelist", slot_agent_in_duel_with, -1),
       (try_begin),
         (player_is_active, ":player_no"), #might be AI
         (multiplayer_send_int_to_player, ":player_no", multiplayer_event_cancel_duel, ":agent_no_offerer"),
       (else_try),
         (agent_force_rethink, ":ex_duelist"),
       (try_end),
     (try_end),
     (agent_set_slot, ":agent_no", slot_agent_in_duel_with, ":agent_no_offerer"),
     (agent_set_slot, ":agent_no_offerer", slot_agent_in_duel_with, ":agent_no"),
     (agent_clear_relations_with_agents, ":agent_no"),
     (agent_clear_relations_with_agents, ":agent_no_offerer"),
##     (agent_add_relation_with_agent, ":agent_no", ":agent_no_offerer", -1),
##     (agent_add_relation_with_agent, ":agent_no_offerer", ":agent_no", -1),
     (agent_get_player_id, ":player_no", ":agent_no"),
     (store_mission_timer_a, ":mission_timer"),
     (try_begin),
       (player_is_active, ":player_no"), #might be AI
       (multiplayer_send_int_to_player, ":player_no", multiplayer_event_start_duel, ":agent_no_offerer"),
     (else_try),
       (agent_force_rethink, ":agent_no"),
     (try_end),
     (agent_set_slot, ":agent_no", slot_agent_duel_start_time, ":mission_timer"),
     (agent_get_player_id, ":agent_no_offerer_player", ":agent_no_offerer"),
     (try_begin),
       (player_is_active, ":agent_no_offerer_player"), #might be AI
       (multiplayer_send_int_to_player, ":agent_no_offerer_player", multiplayer_event_start_duel, ":agent_no"),
     (else_try),
       (agent_force_rethink, ":agent_no_offerer"),
     (try_end),
     (agent_set_slot, ":agent_no_offerer", slot_agent_duel_start_time, ":mission_timer"),
     ]),

  # script_game_get_multiplayer_server_option_for_mission_template
  # Input: arg1 = mission_template_id, arg2 = option_index
  # Output: trigger_result = 1 for option available, 0 for not available
  # reg0 = option_value
  ("game_get_multiplayer_server_option_for_mission_template",
   [
     (store_script_param, ":mission_template_id", 1),
     (store_script_param, ":option_index", 2),
     (try_begin),
       (eq, ":option_index", 0),
       (assign, reg0, "$g_multiplayer_team_1_faction"),
       (set_trigger_result, 1),
     (else_try),
       (eq, ":option_index", 1),
       (assign, reg0, "$g_multiplayer_team_2_faction"),
       (set_trigger_result, 1),
     (else_try),
       (eq, ":option_index", 2),
       (assign, reg0, "$g_multiplayer_num_bots_team_1"),
       (set_trigger_result, 1),
     (else_try),
       (eq, ":option_index", 3),
       (assign, reg0, "$g_multiplayer_num_bots_team_2"),
       (set_trigger_result, 1),
     (else_try),
       (eq, ":option_index", 4),
       (server_get_friendly_fire, reg0),
       (set_trigger_result, 1),
     (else_try),
       (eq, ":option_index", 5),
       (server_get_melee_friendly_fire, reg0),
       (set_trigger_result, 1),
     (else_try),
       (eq, ":option_index", 6),
       (server_get_friendly_fire_damage_self_ratio, reg0),
       (set_trigger_result, 1),
     (else_try),
       (eq, ":option_index", 7),
       (server_get_friendly_fire_damage_friend_ratio, reg0),
       (set_trigger_result, 1),
     (else_try),
       (eq, ":option_index", 8),
       (server_get_ghost_mode, reg0),
       (set_trigger_result, 1),
     (else_try),
       (eq, ":option_index", 9),
       (server_get_control_block_dir, reg0),       
       (set_trigger_result, 1),
     (else_try),
       (eq, ":option_index", 10),
       (server_get_combat_speed, reg0),
       (set_trigger_result, 1),
     (else_try),
       (try_begin),
         (eq, ":mission_template_id", "mt_multiplayer_hq"),
         (val_add, ":option_index", 1), #max game time
       (try_end),
       (eq, ":option_index", 11),
       (assign, reg0, "$g_multiplayer_game_max_minutes"),
       (set_trigger_result, 1),
     (else_try),
       (try_begin),
         (neq, ":mission_template_id", "mt_multiplayer_bt"),
         (neq, ":mission_template_id", "mt_multiplayer_fd"),
         (neq, ":mission_template_id", "mt_multiplayer_sg"),
         (val_add, ":option_index", 1), #max round time
       (try_end),
       (eq, ":option_index", 12),
       (assign, reg0, "$g_multiplayer_round_max_seconds"),
       (set_trigger_result, 1),
     (else_try),
       (try_begin),
         (neq, ":mission_template_id", "mt_multiplayer_bt"),
         (neq, ":mission_template_id", "mt_multiplayer_fd"),
         (val_add, ":option_index", 1), #respawn as bot
       (try_end),
       (eq, ":option_index", 13),
       (assign, reg0, "$g_multiplayer_player_respawn_as_bot"),
       (set_trigger_result, 1),
     (else_try),
       (try_begin),
         (neq, ":mission_template_id", "mt_multiplayer_sg"),
         (val_add, ":option_index", 1), #respawn limit
       (try_end),
       (eq, ":option_index", 14),
       (assign, reg0, "$g_multiplayer_number_of_respawn_count"),
       (set_trigger_result, 1),
     (else_try),
       (eq, ":option_index", 15),
       (assign, reg0, "$g_multiplayer_game_max_points"),
       (set_trigger_result, 1),
     (else_try),
       (try_begin),
         (neq, ":mission_template_id", "mt_multiplayer_hq"),
         (val_add, ":option_index", 1), #point gained from flags
       (try_end),
       (eq, ":option_index", 16),
       (assign, reg0, "$g_multiplayer_point_gained_from_flags"),
       (set_trigger_result, 1),
     (else_try),
       (try_begin),
         (neq, ":mission_template_id", "mt_multiplayer_cf"),
         (val_add, ":option_index", 1), #point gained from capturing flag
       (try_end),
       (eq, ":option_index", 17),
       (assign, reg0, "$g_multiplayer_point_gained_from_capturing_flag"),
       (set_trigger_result, 1),
     (else_try),
       (eq, ":option_index", 18),
       (assign, reg0, "$g_multiplayer_respawn_period"),
       (set_trigger_result, 1),
     (else_try),
       (eq, ":option_index", 19),
       (assign, reg0, "$g_multiplayer_initial_gold_multiplier"),
       (set_trigger_result, 1),
     (else_try),
       (eq, ":option_index", 20),
       (assign, reg0, "$g_multiplayer_battle_earnings_multiplier"),
       (set_trigger_result, 1),
     (else_try),
       (try_begin),
         (neq, ":mission_template_id", "mt_multiplayer_bt"),
         (neq, ":mission_template_id", "mt_multiplayer_fd"),
         (neq, ":mission_template_id", "mt_multiplayer_sg"),
         (val_add, ":option_index", 1),
       (try_end),
       (eq, ":option_index", 21),
       (assign, reg0, "$g_multiplayer_round_earnings_multiplier"),
       (set_trigger_result, 1),
     (try_end),     
     ]),

  # script_game_multiplayer_server_option_for_mission_template_to_string
  # Input: arg1 = mission_template_id, arg2 = option_index, arg3 = option_value
  # Output: s0 = option_text
  ("game_multiplayer_server_option_for_mission_template_to_string",
   [
     (store_script_param, ":mission_template_id", 1),
     (store_script_param, ":option_index", 2),
     (store_script_param, ":option_value", 3),
     (str_clear, s0),
     (try_begin),
       (eq, ":option_index", 0),
       (assign, reg1, 1),
       (str_store_string, s0, "str_team_reg1_faction"),
       (str_store_faction_name, s1, ":option_value"),
       (str_store_string, s0, "str_s0_s1"),
     (else_try),
       (eq, ":option_index", 1),
       (assign, reg1, 2),
       (str_store_string, s0, "str_team_reg1_faction"),
       (str_store_faction_name, s1, ":option_value"),
       (str_store_string, s0, "str_s0_s1"),
     (else_try),
       (eq, ":option_index", 2),
       (assign, reg1, 1),
       (str_store_string, s0, "str_number_of_bots_in_team_reg1"),
       (assign, reg0, ":option_value"),
       (str_store_string, s0, "str_s0_reg0"),
     (else_try),
       (eq, ":option_index", 3),
       (assign, reg1, 2),
       (str_store_string, s0, "str_number_of_bots_in_team_reg1"),
       (assign, reg0, ":option_value"),
       (str_store_string, s0, "str_s0_reg0"),
     (else_try),
       (eq, ":option_index", 4),
       (str_store_string, s0, "str_allow_friendly_fire"),
       (try_begin),
         (eq, ":option_value", 0),
         (str_store_string, s1, "str_no_wo_dot"),
       (else_try),
         (str_store_string, s1, "str_yes_wo_dot"),
       (try_end),
       (str_store_string, s0, "str_s0_s1"),
     (else_try),
       (eq, ":option_index", 5),
       (str_store_string, s0, "str_allow_melee_friendly_fire"),
       (try_begin),
         (eq, ":option_value", 0),
         (str_store_string, s1, "str_no_wo_dot"),
       (else_try),
         (str_store_string, s1, "str_yes_wo_dot"),
       (try_end),
       (str_store_string, s0, "str_s0_s1"),
     (else_try),
       (eq, ":option_index", 6),
       (str_store_string, s0, "str_friendly_fire_damage_self_ratio"),
       (assign, reg0, ":option_value"),
       (str_store_string, s0, "str_s0_reg0"),
     (else_try),
       (eq, ":option_index", 7),
       (str_store_string, s0, "str_friendly_fire_damage_friend_ratio"),
       (assign, reg0, ":option_value"),
       (str_store_string, s0, "str_s0_reg0"),
     (else_try),
       (eq, ":option_index", 8),
       (str_store_string, s0, "str_spectator_camera"),
       (try_begin),
         (eq, ":option_value", 0),
         (str_store_string, s1, "str_free"),
       (else_try),
         (eq, ":option_value", 1),
         (str_store_string, s1, "str_stick_to_any_player"),
       (else_try),
         (eq, ":option_value", 2),
         (str_store_string, s1, "str_stick_to_team_members"),
       (else_try),
         (str_store_string, s1, "str_stick_to_team_members_view"),
       (try_end),
       (str_store_string, s0, "str_s0_s1"),
     (else_try),
       (eq, ":option_index", 9),
       (str_store_string, s0, "str_control_block_direction"),
       (try_begin),
         (eq, ":option_value", 0),
         (str_store_string, s1, "str_automatic"),
       (else_try),
         (str_store_string, s1, "str_by_mouse_movement"),
       (try_end),
       (str_store_string, s0, "str_s0_s1"),
     (else_try),
       (eq, ":option_index", 10),
       (str_store_string, s0, "str_combat_speed"),
       (try_begin),
         (eq, ":option_value", 0),
         (str_store_string, s1, "str_combat_speed_0"),
       (else_try),
         (eq, ":option_value", 1),
         (str_store_string, s1, "str_combat_speed_1"),
       (else_try),
         (eq, ":option_value", 2),
         (str_store_string, s1, "str_combat_speed_2"),
       (else_try),
         (eq, ":option_value", 3),
         (str_store_string, s1, "str_combat_speed_3"),
       (else_try),
         (str_store_string, s1, "str_combat_speed_4"),
       (try_end),
       (str_store_string, s0, "str_s0_s1"),
     (else_try),
       (try_begin),
         (eq, ":mission_template_id", "mt_multiplayer_hq"),
         (val_add, ":option_index", 1), #max game time
       (try_end),
       (eq, ":option_index", 11),
       (str_store_string, s0, "str_map_time_limit"),
       (assign, reg0, ":option_value"),
       (str_store_string, s0, "str_s0_reg0"),
     (else_try),
       (try_begin),
         (neq, ":mission_template_id", "mt_multiplayer_bt"),
         (neq, ":mission_template_id", "mt_multiplayer_fd"),
         (neq, ":mission_template_id", "mt_multiplayer_sg"),
         (val_add, ":option_index", 1), #max round time
       (try_end),
       (eq, ":option_index", 12),
       (str_store_string, s0, "str_round_time_limit"),
       (assign, reg0, ":option_value"),
       (str_store_string, s0, "str_s0_reg0"),
     (else_try),
       (try_begin),
         (neq, ":mission_template_id", "mt_multiplayer_bt"),
         (neq, ":mission_template_id", "mt_multiplayer_fd"),
         (val_add, ":option_index", 1), #respawn as bot
       (try_end),
       (eq, ":option_index", 13),
       (str_store_string, s0, "str_players_take_control_of_a_bot_after_death"),
       (try_begin),
         (eq, ":option_value", 0),
         (str_store_string, s1, "str_no_wo_dot"),
       (else_try),
         (str_store_string, s1, "str_yes_wo_dot"),
       (try_end),
       (str_store_string, s0, "str_s0_s1"),
     (else_try),
       (try_begin),
         (neq, ":mission_template_id", "mt_multiplayer_sg"),
         (val_add, ":option_index", 1), #respawn limit
       (try_end),
       (eq, ":option_index", 14),
       (str_store_string, s0, "str_defender_spawn_count_limit"),
       (try_begin),
         (eq, ":option_value", 0),
         (str_store_string, s1, "str_unlimited"),
       (else_try),
         (assign, reg1, ":option_value"),
         (str_store_string, s1, "str_reg1"),
       (try_end),
       (str_store_string, s0, "str_s0_s1"),
     (else_try),
       (eq, ":option_index", 15),
       (str_store_string, s0, "str_team_points_limit"),
       (assign, reg0, ":option_value"),
       (str_store_string, s0, "str_s0_reg0"),
     (else_try),
       (try_begin),
         (neq, ":mission_template_id", "mt_multiplayer_hq"),
         (val_add, ":option_index", 1), #point gained from flags
       (try_end),
       (eq, ":option_index", 16),
       (str_store_string, s0, "str_point_gained_from_flags"),
       (assign, reg0, ":option_value"),
       (str_store_string, s0, "str_s0_reg0"),
     (else_try),
       (try_begin),
         (neq, ":mission_template_id", "mt_multiplayer_cf"),
         (val_add, ":option_index", 1), #point gained from capturing flag
       (try_end),
       (eq, ":option_index", 17),
       (str_store_string, s0, "str_point_gained_from_capturing_flag"),
       (assign, reg0, ":option_value"),
       (str_store_string, s0, "str_s0_reg0"),
     (else_try),
       (eq, ":option_index", 18),
       (str_store_string, s0, "str_respawn_period"),
       (assign, reg0, ":option_value"),
       (str_store_string, s0, "str_s0_reg0"),
     (else_try),
       (eq, ":option_index", 19),
       (str_store_string, s0, "str_initial_gold_multiplier"),
       (assign, reg0, ":option_value"),
       (str_store_string, s0, "str_s0_reg0"),
     (else_try),
       (eq, ":option_index", 20),
       (str_store_string, s0, "str_battle_earnings_multiplier"),
       (assign, reg0, ":option_value"),
       (str_store_string, s0, "str_s0_reg0"),
     (else_try),
       (try_begin),
         (neq, ":mission_template_id", "mt_multiplayer_bt"),
         (neq, ":mission_template_id", "mt_multiplayer_fd"),
         (neq, ":mission_template_id", "mt_multiplayer_sg"),
         (val_add, ":option_index", 1),
       (try_end),
       (eq, ":option_index", 21),
       (str_store_string, s0, "str_round_earnings_multiplier"),
       (assign, reg0, ":option_value"),
       (str_store_string, s0, "str_s0_reg0"),
     (try_end),
     ]),

  # script_cf_multiplayer_team_is_available
  # Input: arg1 = player_no, arg2 = team_no
  # Output: none, true or false 
  ("cf_multiplayer_team_is_available",
   [
     (store_script_param, ":player_no", 1),
     (store_script_param, ":team_no", 2),
     (assign, ":continue_change_team", 1),
     (try_begin),
       (neq, "$g_multiplayer_game_type", multiplayer_game_type_deathmatch),
       (neq, "$g_multiplayer_game_type", multiplayer_game_type_duel),
       (is_between, ":team_no", 0, multi_team_spectator),
       (neg|teams_are_enemies, ":team_no", ":team_no"), #checking if it is a deathmatch or not
       (assign, ":continue_change_team", 0),
       #counting number of players for team balance checks
       (assign, ":number_of_players_at_team_1", 0),
       (assign, ":number_of_players_at_team_2", 0),
       (get_max_players, ":num_players"),
       (try_for_range, ":cur_player", 0, ":num_players"),
         (player_is_active, ":cur_player"),
         (neq, ":cur_player", ":player_no"),
         (player_get_team_no, ":player_team", ":cur_player"),
         (try_begin),
           (eq, ":player_team", 0),
           (val_add, ":number_of_players_at_team_1", 1),
         (else_try),
           (eq, ":player_team", 1),
           (val_add, ":number_of_players_at_team_2", 1),
         (try_end),
       (try_end),
       (store_sub, ":difference_of_number_of_players", ":number_of_players_at_team_1", ":number_of_players_at_team_2"),

       (try_begin),
         (ge, ":difference_of_number_of_players", 0),
         (val_add, ":difference_of_number_of_players", 1),
       (else_try),
         (val_add, ":difference_of_number_of_players", -1),
       (try_end),
     
       (try_begin),
         (eq, ":team_no", 0),
         (lt, ":difference_of_number_of_players", "$g_multiplayer_auto_team_balance_limit"),
         (assign, ":continue_change_team", 1),
       (else_try),
         (eq, ":team_no", 1),
         (store_mul, ":checked_value", "$g_multiplayer_auto_team_balance_limit", -1),
         (gt, ":difference_of_number_of_players", ":checked_value"),
         (assign, ":continue_change_team", 1),
       (try_end),
     (try_end),
     (eq, ":continue_change_team", 1),
     ]),

  # script_find_number_of_agents_constant
  # Input: none
  # Output: reg0 = 100xconstant (100..500)
  ("find_number_of_agents_constant",
   [
     (assign, ":num_dead_or_alive_agents", 0),
     
     (try_for_agents, ":cur_agent"),
       (agent_is_human, ":cur_agent"),
       (val_add, ":num_dead_or_alive_agents", 1),     
     (try_end),

     (try_begin),
       (le, ":num_dead_or_alive_agents", 2), #2
       (assign, reg0, 100),
     (else_try),
       (le, ":num_dead_or_alive_agents", 4), #2+2
       (assign, reg0, 140),
     (else_try),
       (le, ":num_dead_or_alive_agents", 7), #2+2+3
       (assign, reg0, 180),
     (else_try),
       (le, ":num_dead_or_alive_agents", 11), #2+2+3+4
       (assign, reg0, 220),
     (else_try),
       (le, ":num_dead_or_alive_agents", 17), #2+2+3+4+6
       (assign, reg0, 260),
     (else_try),
       (le, ":num_dead_or_alive_agents", 25), #2+2+3+4+6+8
       (assign, reg0, 300),
     (else_try),
       (le, ":num_dead_or_alive_agents", 36), #2+2+3+4+6+8+11
       (assign, reg0, 340),
     (else_try),
       (le, ":num_dead_or_alive_agents", 50), #2+2+3+4+6+8+11+14
       (assign, reg0, 380),
     (else_try),
       (le, ":num_dead_or_alive_agents", 68), #2+2+3+4+6+8+11+14+18
       (assign, reg0, 420),
     (else_try),
       (le, ":num_dead_or_alive_agents", 91), #2+2+3+4+6+8+11+14+18+23
       (assign, reg0, 460),
     (else_try),
       (assign, reg0, 500),
     (try_end),
     ]),

  # script_game_multiplayer_event_duel_offered
  # Input: arg1 = agent_no
  # Output: none
  ("game_multiplayer_event_duel_offered",
   [
     (store_script_param, ":agent_no", 1),
     (get_player_agent_no, ":player_agent_no"),
     (try_begin),
       (agent_is_active, ":player_agent_no"),
       (this_or_next|agent_slot_eq, ":player_agent_no", slot_agent_in_duel_with, -1),
       (agent_check_offer_from_agent, ":player_agent_no", ":agent_no"),
       (neg|agent_slot_eq, ":player_agent_no", slot_agent_in_duel_with, ":agent_no"), #don't allow spamming duel offers during countdown
       (multiplayer_send_int_to_server, multiplayer_event_offer_duel, ":agent_no"),
       (agent_get_player_id, ":player_no", ":agent_no"),
       (try_begin),
         (player_is_active, ":player_no"),
         (str_store_player_username, s0, ":player_no"),
       (else_try),
         (str_store_agent_name, s0, ":agent_no"),
       (try_end),
       (display_message, "str_a_duel_request_is_sent_to_s0"),
     (try_end),
     ]),
	 
  # script_game_get_multiplayer_game_type_enum
  # Input: none
  # Output: reg0:first type, reg1:type count
  ("game_get_multiplayer_game_type_enum",
   [
     (assign, reg0, multiplayer_game_type_deathmatch),
	 (assign, reg1, multiplayer_num_game_types),
	 ]),

  # script_game_multiplayer_get_game_type_mission_template
  # Input: arg1 = game_type
  # Output: mission_template 
  ("game_multiplayer_get_game_type_mission_template",
   [
     (assign, ":selected_mt", -1),
     (store_script_param, ":game_type", 1),
     (try_begin),
       (eq, ":game_type", multiplayer_game_type_deathmatch),
       (assign, ":selected_mt", "mt_multiplayer_dm"),
     (else_try),
       (eq, ":game_type", multiplayer_game_type_team_deathmatch),
       (assign, ":selected_mt", "mt_multiplayer_tdm"),
     (else_try),
       (eq, ":game_type", multiplayer_game_type_battle),
       (assign, ":selected_mt", "mt_multiplayer_bt"),
     (else_try),
       (eq, ":game_type", multiplayer_game_type_destroy),
       (assign, ":selected_mt", "mt_multiplayer_fd"),
     (else_try),
       (eq, ":game_type", multiplayer_game_type_capture_the_flag),
       (assign, ":selected_mt", "mt_multiplayer_cf"),
     (else_try),
       (eq, ":game_type", multiplayer_game_type_headquarters),
       (assign, ":selected_mt", "mt_multiplayer_hq"),
     (else_try),
       (eq, ":game_type", multiplayer_game_type_siege),
       (assign, ":selected_mt", "mt_multiplayer_sg"),
     (else_try),
       (eq, ":game_type", multiplayer_game_type_duel),
       (assign, ":selected_mt", "mt_multiplayer_duel"),
     (try_end),
     (assign, reg0, ":selected_mt"),
     ]),

  # script_multiplayer_get_mission_template_game_type
  # Input: arg1 = mission_template_no
  # Output: game_type 
  ("multiplayer_get_mission_template_game_type",
   [
     (store_script_param, ":mission_template_no", 1),
     (assign, ":game_type", -1),
     (try_begin),
       (eq, ":mission_template_no", "mt_multiplayer_dm"),
       (assign, ":game_type", multiplayer_game_type_deathmatch),
     (else_try),
       (eq, ":mission_template_no", "mt_multiplayer_tdm"),
       (assign, ":game_type", multiplayer_game_type_team_deathmatch),
     (else_try),
       (eq, ":mission_template_no", "mt_multiplayer_bt"),
       (assign, ":game_type", multiplayer_game_type_battle),
     (else_try),
       (eq, ":mission_template_no", "mt_multiplayer_fd"),
       (assign, ":game_type", multiplayer_game_type_destroy),
     (else_try),
       (eq, ":mission_template_no", "mt_multiplayer_cf"),
       (assign, ":game_type", multiplayer_game_type_capture_the_flag),
     (else_try),
       (eq, ":mission_template_no", "mt_multiplayer_hq"),
       (assign, ":game_type", multiplayer_game_type_headquarters),
     (else_try),
       (eq, ":mission_template_no", "mt_multiplayer_sg"),
       (assign, ":game_type", multiplayer_game_type_siege),
     (else_try),
       (eq, ":mission_template_no", "mt_multiplayer_duel"),
       (assign, ":game_type", multiplayer_game_type_duel),
     (try_end),
     (assign, reg0, ":game_type"),
     ]),


  # script_multiplayer_fill_available_factions_combo_button
  # Input: arg1 = overlay_id, arg2 = selected_faction_no, arg3 = opposite_team_selected_faction_no
  # Output: none 
  ("multiplayer_fill_available_factions_combo_button",
   [
     (store_script_param, ":overlay_id", 1),
     (store_script_param, ":selected_faction_no", 2),
##     (store_script_param, ":opposite_team_selected_faction_no", 3),
##     (try_for_range, ":cur_faction", "fac_kingdom_1", "fac_kingdoms_end"),
##       (try_begin),
##         (eq, ":opposite_team_selected_faction_no", ":cur_faction"),
##         (try_begin),
##           (gt, ":selected_faction_no", ":opposite_team_selected_faction_no"),
##           (val_sub, ":selected_faction_no", 1),
##         (try_end),
##       (else_try),
##         (str_store_faction_name, s0, ":cur_faction"),
##         (overlay_add_item, ":overlay_id", s0),
##       (try_end),
##     (try_end),
##     (val_sub, ":selected_faction_no", "fac_kingdom_1"),
##     (overlay_set_val, ":overlay_id", ":selected_faction_no"),
     (try_for_range, ":cur_faction", npc_kingdoms_begin, npc_kingdoms_end),
       (str_store_faction_name, s0, ":cur_faction"),
       (overlay_add_item, ":overlay_id", s0),
     (try_end),
     (val_sub, ":selected_faction_no", "fac_kingdom_1"),
     (overlay_set_val, ":overlay_id", ":selected_faction_no"),
     ]),
  

  # script_multiplayer_get_troop_class
  # Input: arg1 = troop_no
  # Output: reg0: troop_class 
  ("multiplayer_get_troop_class",
   [
     (store_script_param_1, ":troop_no"),
     (assign, ":troop_class", multi_troop_class_other),
     (try_begin),
       (this_or_next|eq, ":troop_no", "trp_vaegir_archer_multiplayer"),
       (this_or_next|eq, ":troop_no", "trp_nord_archer_multiplayer"),
       (eq, ":troop_no", "trp_sarranid_archer_multiplayer"),
       (assign, ":troop_class", multi_troop_class_archer),
     (else_try),
       (this_or_next|eq, ":troop_no", "trp_swadian_man_at_arms_multiplayer"),
       (this_or_next|eq, ":troop_no", "trp_nord_scout_multiplayer"),
       (this_or_next|eq, ":troop_no", "trp_rhodok_horseman_multiplayer"),
       (this_or_next|eq, ":troop_no", "trp_sarranid_mamluke_multiplayer"),
       (eq, ":troop_no", "trp_vaegir_horseman_multiplayer"),
       (assign, ":troop_class", multi_troop_class_cavalry),
     (else_try),
       (eq, ":troop_no", "trp_khergit_veteran_horse_archer_multiplayer"),
       (assign, ":troop_class", multi_troop_class_mounted_archer),
#     (else_try),
#       (eq, ":troop_no", "trp_swadian_mounted_crossbowman_multiplayer"),
#       (assign, ":troop_class", multi_troop_class_mounted_crossbowman),
     (else_try),
       (this_or_next|eq, ":troop_no", "trp_swadian_crossbowman_multiplayer"),
       (eq, ":troop_no", "trp_rhodok_veteran_crossbowman_multiplayer"),
       (assign, ":troop_class", multi_troop_class_crossbowman),
     (else_try),
       (this_or_next|eq, ":troop_no", "trp_swadian_infantry_multiplayer"),
       (this_or_next|eq, ":troop_no", "trp_sarranid_footman_multiplayer"),
       (eq, ":troop_no", "trp_nord_veteran_multiplayer"),
       (assign, ":troop_class", multi_troop_class_infantry),
     (else_try),
       (eq, ":troop_no", "trp_vaegir_spearman_multiplayer"),
       (assign, ":troop_class", multi_troop_class_spearman),
     (try_end),
     (assign, reg0, ":troop_class"),
     ]),

  #script_multiplayer_clear_player_selected_items
  # Input: arg1 = player_no
  # Output: none
  ("multiplayer_clear_player_selected_items",
   [
     (store_script_param, ":player_no", 1),
     (try_for_range, ":slot_no", slot_player_selected_item_indices_begin, slot_player_selected_item_indices_end),
       (player_set_slot, ":player_no", ":slot_no", -1),
     (try_end),
     ]),
  

  #script_multiplayer_init_player_slots
  # Input: arg1 = player_no
  # Output: none
  ("multiplayer_init_player_slots",
   [
     (store_script_param, ":player_no", 1),
     (call_script, "script_multiplayer_clear_player_selected_items", ":player_no"),
     (player_set_slot, ":player_no", slot_player_spawned_this_round, 0),
     (player_set_slot, ":player_no", slot_player_last_rounds_used_item_earnings, 0),
     (player_set_slot, ":player_no", slot_player_poll_disabled_until_time, 0),

     (player_set_slot, ":player_no", slot_player_bot_type_1_wanted, 0),
     (player_set_slot, ":player_no", slot_player_bot_type_2_wanted, 0),
     (player_set_slot, ":player_no", slot_player_bot_type_3_wanted, 0),
     (player_set_slot, ":player_no", slot_player_bot_type_4_wanted, 0),
     ]),

  #script_multiplayer_initialize_belfry_wheel_rotations
  # Input: none
  # Output: none
  ("multiplayer_initialize_belfry_wheel_rotations",
   [
##    (scene_prop_get_num_instances, ":num_belfries", "spr_belfry_a"),
##    (try_for_range, ":belfry_no", 0, ":num_belfries"),
##      (store_mul, ":wheel_no", ":belfry_no", 3),
##      (scene_prop_get_instance, ":belfry_wheel_1_scene_prop_id", "spr_belfry_wheel", ":wheel_no"),
##      (prop_instance_initialize_rotation_angles, ":belfry_wheel_1_scene_prop_id"),
##      #belfry wheel_2
##      (val_add, ":wheel_no", 1),
##      (scene_prop_get_instance, ":belfry_wheel_2_scene_prop_id", "spr_belfry_wheel", ":wheel_no"),
##      (prop_instance_initialize_rotation_angles, ":belfry_wheel_2_scene_prop_id"),
##      #belfry wheel_3
##      (val_add, ":wheel_no", 1),
##      (scene_prop_get_instance, ":belfry_wheel_3_scene_prop_id", "spr_belfry_wheel", ":wheel_no"),
##      (prop_instance_initialize_rotation_angles, ":belfry_wheel_3_scene_prop_id"),   
##    (try_end),
##
##    (scene_prop_get_num_instances, ":num_belfries_a", "spr_belfry_a"),
##
##    (scene_prop_get_num_instances, ":num_belfries", "spr_belfry_b"),
##    (try_for_range, ":belfry_no", 0, ":num_belfries"),
##      (store_add, ":wheel_no_plus_num_belfries_a", ":wheel_no", ":num_belfries_a"),
##      (store_mul, ":wheel_no_plus_num_belfries_a", ":belfry_no", 3),
##      (scene_prop_get_instance, ":belfry_wheel_1_scene_prop_id", "spr_belfry_wheel", ":wheel_no_plus_num_belfries_a"),
##      (prop_instance_initialize_rotation_angles, ":belfry_wheel_1_scene_prop_id"),
##      #belfry wheel_2
##      (val_add, ":wheel_no_plus_num_belfries_a", 1),
##      (scene_prop_get_instance, ":belfry_wheel_2_scene_prop_id", "spr_belfry_wheel", ":wheel_no_plus_num_belfries_a"),
##      (prop_instance_initialize_rotation_angles, ":belfry_wheel_2_scene_prop_id"),
##      #belfry wheel_3
##      (val_add, ":wheel_no_plus_num_belfries_a", 1),
##      (scene_prop_get_instance, ":belfry_wheel_3_scene_prop_id", "spr_belfry_wheel", ":wheel_no_plus_num_belfries_a"),
##      (prop_instance_initialize_rotation_angles, ":belfry_wheel_3_scene_prop_id"),   
##    (try_end),

      (scene_prop_get_num_instances, ":num_wheel", "spr_belfry_wheel"),
      (try_for_range, ":wheel_no", 0, ":num_wheel"),
        (scene_prop_get_instance, ":wheel_id", "spr_belfry_wheel", ":wheel_no"),
        (prop_instance_initialize_rotation_angles, ":wheel_id"),   
      (try_end),

      (scene_prop_get_num_instances, ":num_winch", "spr_winch"),
      (try_for_range, ":winch_no", 0, ":num_winch"),
        (scene_prop_get_instance, ":winch_id", "spr_winch", ":winch_no"),
        (prop_instance_initialize_rotation_angles, ":winch_id"),   
      (try_end),

      (scene_prop_get_num_instances, ":num_winch_b", "spr_winch_b"),
      (try_for_range, ":winch_b_no", 0, ":num_winch_b"),
        (scene_prop_get_instance, ":winch_b_id", "spr_winch_b", ":winch_b_no"),
        (prop_instance_initialize_rotation_angles, ":winch_b_id"),   
      (try_end),
     ]),

  #script_send_open_close_information_of_object
  # Input: arg1 = mission_object_id
  # Output: none
  ("send_open_close_information_of_object",
   [
     (store_script_param, ":player_no", 1),
     (store_script_param, ":scene_prop_no", 2),
     
     (scene_prop_get_num_instances, ":num_instances", ":scene_prop_no"),

     (try_for_range, ":instance_no", 0, ":num_instances"),
       (scene_prop_get_instance, ":instance_id", ":scene_prop_no", ":instance_no"),
       (scene_prop_get_slot, ":opened_or_closed", ":instance_id", scene_prop_open_or_close_slot),
       (try_begin),
         (eq, ":opened_or_closed", 1),
         (multiplayer_send_int_to_player, ":player_no", multiplayer_event_set_scene_prop_open_or_close, ":instance_id"),
       (try_end),
     (try_end),
     ]),

  #script_multiplayer_send_initial_information
  # Input: arg1 = player_no
  # Output: none
  ("multiplayer_send_initial_information",
   [
     (store_script_param, ":player_no", 1),
          
     (multiplayer_send_2_int_to_player, ":player_no", multiplayer_event_return_num_bots_in_team, 1, "$g_multiplayer_num_bots_team_1"),
     (multiplayer_send_2_int_to_player, ":player_no", multiplayer_event_return_num_bots_in_team, 2, "$g_multiplayer_num_bots_team_2"),
     (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_auto_team_balance_limit, "$g_multiplayer_auto_team_balance_limit"),
     (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_num_bots_voteable, "$g_multiplayer_num_bots_voteable"),
     (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_factions_voteable, "$g_multiplayer_factions_voteable"),
     (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_maps_voteable, "$g_multiplayer_maps_voteable"),
     (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_kick_voteable, "$g_multiplayer_kick_voteable"),
     (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_ban_voteable, "$g_multiplayer_ban_voteable"),
     (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_allow_player_banners, "$g_multiplayer_allow_player_banners"),
     (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_force_default_armor, "$g_multiplayer_force_default_armor"),
     (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_disallow_ranged_weapons, "$g_multiplayer_disallow_ranged_weapons"),
     (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_respawn_period, "$g_multiplayer_respawn_period"),
     (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_round_max_seconds, "$g_multiplayer_round_max_seconds"),
     (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_game_type, "$g_multiplayer_game_type"),
     (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_player_respawn_as_bot, "$g_multiplayer_player_respawn_as_bot"),
     
     (store_mission_timer_a, ":mission_timer"),
     (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_server_mission_timer_while_player_joined, ":mission_timer"),

     (try_begin),
       (eq, "$g_multiplayer_game_type", multiplayer_game_type_siege),
       (multiplayer_send_int_to_player, ":player_no", multiplayer_event_return_respawn_count, "$g_multiplayer_number_of_respawn_count"),
     (try_end),

     (try_for_agents, ":cur_agent"), #send if any agent is carrying any scene object
       (agent_is_human, ":cur_agent"),
       (agent_get_attached_scene_prop, ":attached_scene_prop", ":cur_agent"),
       (ge, ":attached_scene_prop", 0),
       (multiplayer_send_2_int_to_player, ":player_no", multiplayer_event_set_attached_scene_prop, ":cur_agent", ":attached_scene_prop"),
     (try_end),

     (call_script, "script_send_open_close_information_of_object", ":player_no", "spr_siege_ladder_move_6m"),
     (call_script, "script_send_open_close_information_of_object", ":player_no", "spr_siege_ladder_move_8m"),
     (call_script, "script_send_open_close_information_of_object", ":player_no", "spr_siege_ladder_move_10m"),
     (call_script, "script_send_open_close_information_of_object", ":player_no", "spr_siege_ladder_move_12m"),
     (call_script, "script_send_open_close_information_of_object", ":player_no", "spr_siege_ladder_move_14m"),
     (call_script, "script_send_open_close_information_of_object", ":player_no", "spr_winch_b"),
     (call_script, "script_send_open_close_information_of_object", ":player_no", "spr_castle_e_sally_door_a"),
     (call_script, "script_send_open_close_information_of_object", ":player_no", "spr_castle_f_sally_door_a"),
     (call_script, "script_send_open_close_information_of_object", ":player_no", "spr_earth_sally_gate_left"),
     (call_script, "script_send_open_close_information_of_object", ":player_no", "spr_earth_sally_gate_right"),
     (call_script, "script_send_open_close_information_of_object", ":player_no", "spr_viking_keep_destroy_sally_door_left"),     
     (call_script, "script_send_open_close_information_of_object", ":player_no", "spr_viking_keep_destroy_sally_door_right"),     
     (call_script, "script_send_open_close_information_of_object", ":player_no", "spr_castle_f_door_a"),
     (call_script, "script_send_open_close_information_of_object", ":player_no", "spr_door_destructible"),
     (call_script, "script_send_open_close_information_of_object", ":player_no", "spr_castle_f_door_b"),

     (try_begin),
       (this_or_next|eq, "$g_multiplayer_game_type", multiplayer_game_type_battle),
       (this_or_next|eq, "$g_multiplayer_game_type", multiplayer_game_type_destroy),
       (eq, "$g_multiplayer_game_type", multiplayer_game_type_siege),

       (store_mission_timer_a, ":current_time"),
       (val_sub, ":current_time", "$g_round_start_time"),
       (val_mul, ":current_time", -1),

       (multiplayer_send_int_to_player, ":player_no", multiplayer_event_set_round_start_time, ":current_time"),
     (else_try),
       (eq, "$g_multiplayer_game_type", multiplayer_game_type_capture_the_flag),
       #if game type is capture the flag send current flag situations to each player.
       (team_get_slot, ":flag_situation_team_1", 0, slot_team_flag_situation),
       (multiplayer_send_2_int_to_player, ":player_no", multiplayer_event_set_team_flag_situation, 0, ":flag_situation_team_1"),
       (team_get_slot, ":flag_situation_team_2", 1, slot_team_flag_situation),
       (multiplayer_send_2_int_to_player, ":player_no", multiplayer_event_set_team_flag_situation, 1, ":flag_situation_team_2"),
     (else_try),
       (this_or_next|eq, "$g_multiplayer_game_type", multiplayer_game_type_headquarters),
       (eq, "$g_multiplayer_game_type", multiplayer_game_type_siege),
       #if game type is headquarters send number of agents placed around each pole's around to player.
       (try_for_range, ":flag_no", 0, "$g_number_of_flags"),
         (assign, ":number_of_agents_around_flag_team_1", 0),
         (assign, ":number_of_agents_around_flag_team_2", 0),

         (scene_prop_get_instance, ":pole_id", "spr_headquarters_pole_code_only", ":flag_no"), 
         (prop_instance_get_position, pos0, ":pole_id"), #pos0 holds pole position. 

         (try_for_agents, ":cur_agent"),
           (agent_is_human, ":cur_agent"),
           (agent_is_alive, ":cur_agent"),
           (neg|agent_is_non_player, ":cur_agent"),
           (agent_get_team, ":cur_agent_team", ":cur_agent"),
           (agent_get_position, pos1, ":cur_agent"), #pos1 holds agent's position.
           (get_sq_distance_between_positions, ":squared_dist", pos0, pos1),
           (get_sq_distance_between_position_heights, ":squared_height_dist", pos0, pos1),
           (val_add, ":squared_dist", ":squared_height_dist"),
           (lt, ":squared_dist", multi_headquarters_max_distance_sq_to_raise_flags),
           (try_begin),
             (eq, ":cur_agent_team", 0),
             (val_add, ":number_of_agents_around_flag_team_1", 1),
           (else_try),
             (eq, ":cur_agent_team", 1),
             (val_add, ":number_of_agents_around_flag_team_2", 1),
           (try_end),
         (try_end),

         (store_mul, ":current_owner_code", ":number_of_agents_around_flag_team_1", 100),
         (val_add, ":current_owner_code", ":number_of_agents_around_flag_team_2"),        
         (multiplayer_send_2_int_to_player, ":player_no", multiplayer_event_set_num_agents_around_flag, ":flag_no", ":current_owner_code"),
       (try_end),

       #if game type is headquarters send owners of each pole to player.
       (assign, "$g_placing_initial_flags", 1),
       (try_for_range, ":cur_flag", 0, "$g_number_of_flags"),
         (store_add, ":cur_flag_slot", multi_data_flag_owner_begin, ":cur_flag"),
         (troop_get_slot, ":cur_flag_owner", "trp_multiplayer_data", ":cur_flag_slot"),
         (store_mul, ":cur_flag_owner_code", ":cur_flag_owner", 100),
         (val_add, ":cur_flag_owner_code", ":cur_flag_owner"),
         (val_add, ":cur_flag_owner_code", 1),
         (val_mul, ":cur_flag_owner_code", -1),
         (multiplayer_send_2_int_to_player, ":player_no", multiplayer_event_change_flag_owner, ":cur_flag", ":cur_flag_owner_code"),
       (try_end),
       (assign, "$g_placing_initial_flags", 0),
     (try_end),

     #(multiplayer_send_2_int_to_player, ":player_no", multiplayer_event_set_day_time, "$g_round_day_time"),
    ]),

  #script_multiplayer_remove_headquarters_flags
  # Input: none
  # Output: none
  ("multiplayer_remove_headquarters_flags",
   [
     (store_add, ":end_cond", "spr_headquarters_flag_gray", 1),
     (try_for_range, ":headquarters_flag_no", "spr_headquarters_flag_red", ":end_cond"),
       (replace_scene_props, ":headquarters_flag_no", "spr_empty"),
     (try_end),
     ]),

  #script_multiplayer_remove_destroy_mod_targets
  # Input: none
  # Output: none
  ("multiplayer_remove_destroy_mod_targets",
   [
       (replace_scene_props, "spr_catapult_destructible", "spr_empty"),
       (replace_scene_props, "spr_trebuchet_destructible", "spr_empty"),
     ]),
  
  #script_multiplayer_init_mission_variables
  ("multiplayer_init_mission_variables",
   [
     (assign, "$g_multiplayer_team_1_first_spawn", 1),
     (assign, "$g_multiplayer_team_2_first_spawn", 1),
     (assign, "$g_multiplayer_poll_running", 0),
##     (assign, "$g_multiplayer_show_poll_when_suitable", 0),
     (assign, "$g_waiting_for_confirmation_to_terminate", 0),
     (assign, "$g_confirmation_result", 0),
     (assign, "$g_team_balance_next_round", 0),
     (team_get_faction, "$g_multiplayer_team_1_faction", 0),
     (team_get_faction, "$g_multiplayer_team_2_faction", 1),
     (assign, "$g_multiplayer_next_team_1_faction", "$g_multiplayer_team_1_faction"),
     (assign, "$g_multiplayer_next_team_2_faction", "$g_multiplayer_team_2_faction"),

     (assign, "$g_multiplayer_bot_type_1_wanted", 0),
     (assign, "$g_multiplayer_bot_type_2_wanted", 0),
     (assign, "$g_multiplayer_bot_type_3_wanted", 0),
     (assign, "$g_multiplayer_bot_type_4_wanted", 0),

     (call_script, "script_music_set_situation_with_culture", mtf_sit_multiplayer_fight),
     ]),

  #script_multiplayer_event_mission_end
  # Input: none
  # Output: none
  ("multiplayer_event_mission_end",
   [
     #EVERY_BREATH_YOU_TAKE achievement
     (try_begin),
       (multiplayer_get_my_player, ":my_player_no"),
       (is_between, ":my_player_no", 0, multiplayer_max_possible_player_id),
       (player_get_kill_count, ":kill_count", ":my_player_no"),
       (player_get_death_count, ":death_count", ":my_player_no"),
       (gt, ":kill_count", ":death_count"),
       (unlock_achievement, ACHIEVEMENT_EVERY_BREATH_YOU_TAKE),
     (try_end),
     #EVERY_BREATH_YOU_TAKE achievement end
     ]),
  

  #script_multiplayer_event_agent_killed_or_wounded
  # Input: arg1 = dead_agent_no, arg2 = killer_agent_no
  # Output: none
  ("multiplayer_event_agent_killed_or_wounded",
   [
     (store_script_param, ":dead_agent_no", 1),
     (store_script_param, ":killer_agent_no", 2),
     
     (multiplayer_get_my_player, ":my_player_no"),
     (try_begin),
       (is_between, ":my_player_no", 0, multiplayer_max_possible_player_id),
       (player_get_agent_id, ":my_player_agent", ":my_player_no"),
       (ge, ":my_player_agent", 0),
       (try_begin),
         (eq, ":my_player_agent", ":dead_agent_no"),
         (store_mission_timer_a, "$g_multiplayer_respawn_start_time"),
       (try_end),
       (try_begin),
         (eq, ":my_player_agent", ":killer_agent_no"),
         (neq, ":my_player_agent", ":dead_agent_no"),
         (agent_is_human, ":dead_agent_no"),
         (agent_is_alive, ":my_player_agent"),
         (neg|agent_is_ally, ":dead_agent_no"),
         (agent_get_horse, ":my_horse_agent", ":my_player_agent"),
         (agent_get_wielded_item, ":my_wielded_item", ":my_player_agent", 0),
         (assign, ":my_item_class", -1),
         (try_begin),
           (ge, ":my_wielded_item", 0),
           (item_get_slot, ":my_item_class", ":my_wielded_item", slot_item_multiplayer_item_class),
         (try_end),
         #SPOIL_THE_CHARGE achievement
         (try_begin),
           (lt, ":my_horse_agent", 0),
           (agent_get_horse, ":dead_agent_horse_agent", ":dead_agent_no"),
           (ge, ":dead_agent_horse_agent", 0),
           (get_achievement_stat, ":achievement_stat", ACHIEVEMENT_SPOIL_THE_CHARGE, 0),
           (lt, ":achievement_stat", 50),
           (val_add, ":achievement_stat", 1),
           (set_achievement_stat, ACHIEVEMENT_SPOIL_THE_CHARGE, 0, ":achievement_stat"),
           (ge, ":achievement_stat", 50),
           (unlock_achievement, ACHIEVEMENT_SPOIL_THE_CHARGE),
         (try_end),
         #SPOIL_THE_CHARGE achievement end
         #HARASSING_HORSEMAN achievement
         (try_begin),
           (ge, ":my_horse_agent", 0),
           (this_or_next|eq, ":my_item_class", multi_item_class_type_bow),
           (this_or_next|eq, ":my_item_class", multi_item_class_type_crossbow),
           (this_or_next|eq, ":my_item_class", multi_item_class_type_throwing),
           (eq, ":my_item_class", multi_item_class_type_throwing_axe),
           (get_achievement_stat, ":achievement_stat", ACHIEVEMENT_HARASSING_HORSEMAN, 0),
           (lt, ":achievement_stat", 100),
           (val_add, ":achievement_stat", 1),
           (set_achievement_stat, ACHIEVEMENT_HARASSING_HORSEMAN, 0, ":achievement_stat"),
           (ge, ":achievement_stat", 100),
           (unlock_achievement, ACHIEVEMENT_HARASSING_HORSEMAN),
         (try_end),
         #HARASSING_HORSEMAN achievement end
         #THROWING_STAR achievement
         (try_begin),
           (this_or_next|eq, ":my_item_class", multi_item_class_type_throwing),
           (eq, ":my_item_class", multi_item_class_type_throwing_axe),
           (get_achievement_stat, ":achievement_stat", ACHIEVEMENT_THROWING_STAR, 0),
           (lt, ":achievement_stat", 25),
           (val_add, ":achievement_stat", 1),
           (set_achievement_stat, ACHIEVEMENT_THROWING_STAR, 0, ":achievement_stat"),
           (ge, ":achievement_stat", 25),
           (unlock_achievement, ACHIEVEMENT_THROWING_STAR),
         (try_end),
         #THROWING_STAR achievement end
         #SHISH_KEBAB achievement
         (try_begin),
           (ge, ":my_horse_agent", 0),
           (eq, ":my_item_class", multi_item_class_type_lance),
           (get_achievement_stat, ":achievement_stat", ACHIEVEMENT_SHISH_KEBAB, 0),
           (lt, ":achievement_stat", 25),
           (val_add, ":achievement_stat", 1),
           (set_achievement_stat, ACHIEVEMENT_SHISH_KEBAB, 0, ":achievement_stat"),
           (ge, ":achievement_stat", 25),
           (unlock_achievement, ACHIEVEMENT_SHISH_KEBAB),
         (try_end),
         #SHISH_KEBAB achievement end
         #CHOPPY_CHOP_CHOP achievement
         (try_begin),
           (this_or_next|eq, ":my_item_class", multi_item_class_type_sword),
           (this_or_next|eq, ":my_item_class", multi_item_class_type_axe),
           (this_or_next|eq, ":my_item_class", multi_item_class_type_cleavers),
           (this_or_next|eq, ":my_item_class", multi_item_class_type_two_handed_sword),
           (this_or_next|eq, ":my_item_class", multi_item_class_type_two_handed_axe),
           (this_or_next|eq, ":my_wielded_item", "itm_sarranid_axe_a"), #sarranid item exception
           (eq, ":my_wielded_item", "itm_sarranid_axe_b"), #sarranid item exception
           (neq, ":my_wielded_item", "itm_sarranid_two_handed_mace_1"), #sarranid item exception
           (get_achievement_stat, ":achievement_stat", ACHIEVEMENT_CHOPPY_CHOP_CHOP, 0),
           (lt, ":achievement_stat", 50),
           (val_add, ":achievement_stat", 1),
           (set_achievement_stat, ACHIEVEMENT_CHOPPY_CHOP_CHOP, 0, ":achievement_stat"),
           (ge, ":achievement_stat", 50),
           (unlock_achievement, ACHIEVEMENT_CHOPPY_CHOP_CHOP),
         (try_end),
         #CHOPPY_CHOP_CHOP achievement end
         #MACE_IN_YER_FACE achievement
         (try_begin),
           (this_or_next|eq, ":my_item_class", multi_item_class_type_blunt),
           (eq, ":my_wielded_item", "itm_sarranid_two_handed_mace_1"), #sarranid item exception
           (neq, ":my_wielded_item", "itm_sarranid_axe_b"), #sarranid item exception
           (neq, ":my_wielded_item", "itm_sarranid_axe_a"), #sarranid item exception
           (get_achievement_stat, ":achievement_stat", ACHIEVEMENT_MACE_IN_YER_FACE, 0),
           (lt, ":achievement_stat", 25),
           (val_add, ":achievement_stat", 1),
           (set_achievement_stat, ACHIEVEMENT_MACE_IN_YER_FACE, 0, ":achievement_stat"),
           (ge, ":achievement_stat", 25),
           (unlock_achievement, ACHIEVEMENT_MACE_IN_YER_FACE),
         (try_end),
         #MACE_IN_YER_FACE achievement end
         #THE_HUSCARL achievement
         (try_begin),
           (eq, ":my_item_class", multi_item_class_type_throwing_axe),
           (get_achievement_stat, ":achievement_stat", ACHIEVEMENT_THE_HUSCARL, 0),
           (lt, ":achievement_stat", 50),
           (val_add, ":achievement_stat", 1),
           (set_achievement_stat, ACHIEVEMENT_THE_HUSCARL, 0, ":achievement_stat"),
           (ge, ":achievement_stat", 50),
           (unlock_achievement, ACHIEVEMENT_THE_HUSCARL),
         (try_end),
         #THE_HUSCARL achievement end
       (try_end),
     (try_end),

     (try_begin),
       (is_between, ":my_player_no", 0, multiplayer_max_possible_player_id),
       (player_get_agent_id, ":player_agent", ":my_player_no"),
       (eq, ":dead_agent_no", ":player_agent"),
     
       (assign, ":show_respawn_counter", 0),
       (try_begin),
         #TODO: add other game types with no respawns here
         (neq, "$g_multiplayer_game_type", multiplayer_game_type_battle),
         (neq, "$g_multiplayer_game_type", multiplayer_game_type_destroy),
         (assign, ":show_respawn_counter", 1),
       (else_try),         
         (eq, "$g_multiplayer_player_respawn_as_bot", 1),
         (player_get_team_no, ":my_player_team", ":my_player_no"),
         (assign, ":is_found", 0),
         (try_for_agents, ":cur_agent"),
           (eq, ":is_found", 0),
           (agent_is_alive, ":cur_agent"),
           (agent_is_human, ":cur_agent"),
           (agent_is_non_player, ":cur_agent"),
           (agent_get_team ,":cur_team", ":cur_agent"),
           (eq, ":cur_team", ":my_player_team"),
           (assign, ":is_found", 1),
         (try_end),
         (eq, ":is_found", 1),
         (assign, ":show_respawn_counter", 1),
       (try_end),
       
       (try_begin),
         #(player_get_slot, ":spawn_count", ":player_no", slot_player_spawn_count),
         (eq, "$g_multiplayer_game_type", multiplayer_game_type_siege),
         (gt, "$g_multiplayer_number_of_respawn_count", 0),         
     
         (ge, "$g_my_spawn_count", "$g_multiplayer_number_of_respawn_count"),
     
         (multiplayer_get_my_player, ":my_player_no"),
         (player_get_team_no, ":my_player_team", ":my_player_no"),

         (this_or_next|eq, ":my_player_team", 0),
         (ge, "$g_my_spawn_count", 999),
    
         (assign, "$g_show_no_more_respawns_remained", 1),
       (else_try),
         (assign, "$g_show_no_more_respawns_remained", 0),
       (try_end),

       (eq, ":show_respawn_counter", 1),             

       (start_presentation, "prsnt_multiplayer_respawn_time_counter"),
     (try_end),
     ]),
     
  #script_multiplayer_get_item_value_for_troop
  # Input: arg1 = item_no, arg2 = troop_no
  # Output: reg0: item_value
  ("multiplayer_get_item_value_for_troop",
   [
     (store_script_param, ":item_no", 1),
     (store_script_param, ":troop_no", 2),
     (try_begin),
       (call_script, "script_cf_multiplayer_is_item_default_for_troop", ":item_no", ":troop_no"),
       (assign, ":item_value", 0),
     (else_try),
       (store_item_value, ":item_value", ":item_no"),
       (store_troop_faction, ":faction_no", ":troop_no"),
       (store_sub, ":faction_slot", ":faction_no", npc_kingdoms_begin),
       (val_add, ":faction_slot", slot_item_multiplayer_faction_price_multipliers_begin),
       (item_get_slot, ":price_multiplier", ":item_no", ":faction_slot"),
       (val_mul, ":item_value", ":price_multiplier"),
       (val_div, ":item_value", 100),
     (try_end),
     (assign, reg0, ":item_value"),
     ]),

  #script_multiplayer_get_previous_item_for_item_and_troop
  # Input: arg1 = item_no, arg2 = troop_no
  # Output: reg0: previous_item_no (-1 if it is the root item, 0 if the item is invalid) 
  ("multiplayer_get_previous_item_for_item_and_troop",
   [
     (store_script_param, ":item_no", 1),
     (store_script_param, ":troop_no", 2),
     (item_get_slot, ":item_class", ":item_no", slot_item_multiplayer_item_class),
     (call_script, "script_multiplayer_get_item_value_for_troop", ":item_no", ":troop_no"),
     (assign, ":item_value", reg0),
     (store_sub, ":troop_index", ":troop_no", multiplayer_troops_begin),
     (val_add, ":troop_index", slot_item_multiplayer_availability_linked_list_begin),
     (assign, ":max_item_no", -1),
     (assign, ":max_item_value", -1),
     (try_for_range, ":i_item", all_items_begin, all_items_end),
       (item_slot_eq, ":i_item", slot_item_multiplayer_item_class, ":item_class"),
       (item_slot_ge, ":i_item", ":troop_index", 1),
       (call_script, "script_multiplayer_get_item_value_for_troop", ":i_item", ":troop_no"),
       (assign, ":i_item_value", reg0),
       (try_begin),
         (eq, ":i_item_value", 0),
         (eq, ":max_item_value", 0),
         #choose between 2 default items
         (store_item_value, ":i_item_real_value", ":i_item"),
         (store_item_value, ":max_item_real_value", ":max_item_no"),
         (try_begin),
           (gt, ":i_item_real_value", ":max_item_real_value"),
           (assign, ":max_item_value", ":i_item_value"),
           (assign, ":max_item_no", ":i_item"),
         (try_end),
       (else_try),
         (gt, ":i_item_value", ":max_item_value"),
         (lt, ":i_item_value", ":item_value"),
         (assign, ":max_item_value", ":i_item_value"),
         (assign, ":max_item_no", ":i_item"),
       (try_end),
     (try_end),
     (try_begin),
       (eq, ":max_item_no", -1),
       (assign, ":item_upper_class", -1),
       (try_begin),
         (is_between, ":item_class", multi_item_class_type_melee_weapons_begin, multi_item_class_type_melee_weapons_end),
         (assign, ":item_upper_class", 0),
       (else_try),
         (is_between, ":item_class", multi_item_class_type_shields_begin, multi_item_class_type_shields_end),
         (assign, ":item_upper_class", 1),
       (else_try),
         (eq, ":item_class", multi_item_class_type_bow),
         (assign, ":item_upper_class", 2),
       (else_try),
         (eq, ":item_class", multi_item_class_type_crossbow),
         (assign, ":item_upper_class", 3),
       (else_try),
         (eq, ":item_class", multi_item_class_type_arrow),
         (assign, ":item_upper_class", 4),
       (else_try),
         (eq, ":item_class", multi_item_class_type_bolt),
         (assign, ":item_upper_class", 5),
       (else_try),
         (eq, ":item_class", multi_item_class_type_throwing),
         (assign, ":item_upper_class", 6),
       (else_try),
         (is_between, ":item_class", multi_item_class_type_heads_begin, multi_item_class_type_heads_end),
         (assign, ":item_upper_class", 7),
       (else_try),
         (is_between, ":item_class", multi_item_class_type_bodies_begin, multi_item_class_type_bodies_end),
         (assign, ":item_upper_class", 8),
       (else_try),
         (is_between, ":item_class", multi_item_class_type_feet_begin, multi_item_class_type_feet_end),
         (assign, ":item_upper_class", 9),
       (else_try),
         (is_between, ":item_class", multi_item_class_type_gloves_begin, multi_item_class_type_gloves_end),
         (assign, ":item_upper_class", 10),
       (else_try),
         (is_between, ":item_class", multi_item_class_type_horses_begin, multi_item_class_type_horses_end),
         (assign, ":item_upper_class", 11),
       (try_end),
       (neq, ":item_upper_class", 0),
       #search for the default item for non-weapon classes (only 1 slot is easy to fill)
       (assign, ":end_cond", all_items_end),
       (try_for_range, ":i_item", all_items_begin, ":end_cond"),
         (item_slot_ge, ":i_item", ":troop_index", 1),
         (item_get_slot, ":i_item_class", ":i_item", slot_item_multiplayer_item_class),
         (try_begin),
           (is_between, ":i_item_class", multi_item_class_type_melee_weapons_begin, multi_item_class_type_melee_weapons_end),
           (assign, ":i_item_upper_class", 0),
         (else_try),
           (is_between, ":i_item_class", multi_item_class_type_shields_begin, multi_item_class_type_shields_end),
           (assign, ":i_item_upper_class", 1),
         (else_try),
           (eq, ":i_item_class", multi_item_class_type_bow),
           (assign, ":i_item_upper_class", 2),
         (else_try),
           (eq, ":i_item_class", multi_item_class_type_crossbow),
           (assign, ":i_item_upper_class", 3),
         (else_try),
           (eq, ":i_item_class", multi_item_class_type_arrow),
           (assign, ":i_item_upper_class", 4),
         (else_try),
           (eq, ":i_item_class", multi_item_class_type_bolt),
           (assign, ":i_item_upper_class", 5),
         (else_try),
           (eq, ":i_item_class", multi_item_class_type_throwing),
           (assign, ":i_item_upper_class", 6),
         (else_try),
           (is_between, ":i_item_class", multi_item_class_type_heads_begin, multi_item_class_type_heads_end),
           (assign, ":i_item_upper_class", 7),
         (else_try),
           (is_between, ":i_item_class", multi_item_class_type_bodies_begin, multi_item_class_type_bodies_end),
           (assign, ":i_item_upper_class", 8),
         (else_try),
           (is_between, ":i_item_class", multi_item_class_type_feet_begin, multi_item_class_type_feet_end),
           (assign, ":i_item_upper_class", 9),
         (else_try),
           (is_between, ":i_item_class", multi_item_class_type_gloves_begin, multi_item_class_type_gloves_end),
           (assign, ":i_item_upper_class", 10),
         (else_try),
           (is_between, ":i_item_class", multi_item_class_type_horses_begin, multi_item_class_type_horses_end),
           (assign, ":i_item_upper_class", 11),
         (try_end),
         (eq, ":i_item_upper_class", ":item_upper_class"),
         (call_script, "script_cf_multiplayer_is_item_default_for_troop", ":i_item", ":troop_no"),
         (assign, ":max_item_no", ":i_item"),
         (assign, ":end_cond", 0), #break
       (try_end),
     (try_end),
     (assign, reg0, ":max_item_no"),
     ]),

  #script_cf_multiplayer_is_item_default_for_troop
  # Input: arg1 = item_no, arg2 = troop_no
  # Output: reg0: total_cost
  ("cf_multiplayer_is_item_default_for_troop",
   [
     (store_script_param, ":item_no", 1),
     (store_script_param, ":troop_no", 2),
     (assign, ":default_item", 0),
     (try_begin),
       (neg|is_between, ":item_no", horses_begin, horses_end),
       (neq, ":item_no", "itm_warhorse_sarranid"),
       (neq, ":item_no", "itm_warhorse_steppe"),

       (troop_get_inventory_capacity, ":end_cond", ":troop_no"), #troop no can come -1 here error occured at friday
       (try_for_range, ":i_slot", 0, ":end_cond"),
         (troop_get_inventory_slot, ":default_item_id", ":troop_no", ":i_slot"),
         (eq, ":item_no", ":default_item_id"),
         (assign, ":default_item", 1),
         (assign, ":end_cond", 0), #break
       (try_end),
     (try_end),
     (eq, ":default_item", 1),
     ]),
  
  #script_multiplayer_calculate_cur_selected_items_cost
  # Input: arg1 = player_no
  # Output: reg0: total_cost
  ("multiplayer_calculate_cur_selected_items_cost",
   [
     (store_script_param, ":player_no", 1),
     (store_script_param, ":calculation_type", 2), #0 for normal calculation
     (assign, ":total_cost", 0),
     (player_get_troop_id, ":troop_no", ":player_no"),

     (try_begin),
       (eq, ":calculation_type", 0),
       (assign, ":begin_cond", slot_player_cur_selected_item_indices_begin),
       (assign, ":end_cond", slot_player_cur_selected_item_indices_end),
     (else_try),
       (assign, ":begin_cond", slot_player_selected_item_indices_begin),
       (assign, ":end_cond", slot_player_selected_item_indices_end),
     (try_end),
     
     (try_for_range, ":i_item", ":begin_cond", ":end_cond"),
       (player_get_slot, ":item_id", ":player_no", ":i_item"),
       (ge, ":item_id", 0), #might be -1 for horses etc.
       (call_script, "script_multiplayer_get_item_value_for_troop", ":item_id", ":troop_no"),
       (val_add, ":total_cost", reg0),
     (try_end),
     (assign, reg0, ":total_cost"),
     ]),

  #script_multiplayer_set_item_available_for_troop
  # Input: arg1 = item_no, arg2 = troop_no
  # Output: none
  ("multiplayer_set_item_available_for_troop",
   [
     (store_script_param, ":item_no", 1),
     (store_script_param, ":troop_no", 2),
     (store_sub, ":item_troop_slot", ":troop_no", multiplayer_troops_begin),
     (val_add, ":item_troop_slot", slot_item_multiplayer_availability_linked_list_begin),
     (item_set_slot, ":item_no", ":item_troop_slot", 1),
     ]),

  #script_multiplayer_send_item_selections
  # Input: none
  # Output: none
  ("multiplayer_send_item_selections",
   [
     (multiplayer_get_my_player, ":my_player_no"),
     (try_for_range, ":i_item", slot_player_selected_item_indices_begin, slot_player_selected_item_indices_end),
       (player_get_slot, ":item_id", ":my_player_no", ":i_item"),
       (multiplayer_send_2_int_to_server, multiplayer_event_set_item_selection, ":i_item", ":item_id"),
     (try_end),
     ]),

  #script_multiplayer_set_default_item_selections_for_troop
  # Input: arg1 = troop_no
  # Output: none
  ("multiplayer_set_default_item_selections_for_troop",
   [
     (store_script_param, ":troop_no", 1),
     (multiplayer_get_my_player, ":my_player_no"),
     (call_script, "script_multiplayer_clear_player_selected_items", ":my_player_no"),
     (assign, ":cur_weapon_slot", 0),
     (troop_get_inventory_capacity, ":inv_cap", ":troop_no"),
     (try_for_range, ":i_slot", 0, ":inv_cap"),
       (troop_get_inventory_slot, ":item_id", ":troop_no", ":i_slot"),
       (ge, ":item_id", 0),
       (item_get_slot, ":item_class", ":item_id", slot_item_multiplayer_item_class),
       (try_begin),
         (is_between, ":item_class", multi_item_class_type_weapons_begin, multi_item_class_type_weapons_end),
         (this_or_next|eq, "$g_multiplayer_disallow_ranged_weapons", 0),
         (neg|is_between, ":item_class", multi_item_class_type_ranged_weapons_begin, multi_item_class_type_ranged_weapons_end),
         (store_add, ":selected_item_slot", slot_player_selected_item_indices_begin, ":cur_weapon_slot"),
         (player_set_slot, ":my_player_no", ":selected_item_slot", ":item_id"),
         (val_add, ":cur_weapon_slot", 1),
       (else_try),
         (is_between, ":item_class", multi_item_class_type_heads_begin, multi_item_class_type_heads_end),
         (store_add, ":selected_item_slot", slot_player_selected_item_indices_begin, 4),
         (player_set_slot, ":my_player_no", ":selected_item_slot", ":item_id"),
       (else_try),
         (is_between, ":item_class", multi_item_class_type_bodies_begin, multi_item_class_type_bodies_end),
         (store_add, ":selected_item_slot", slot_player_selected_item_indices_begin, 5),
         (player_set_slot, ":my_player_no", ":selected_item_slot", ":item_id"),
       (else_try),
         (is_between, ":item_class", multi_item_class_type_feet_begin, multi_item_class_type_feet_end),
         (store_add, ":selected_item_slot", slot_player_selected_item_indices_begin, 6),
         (player_set_slot, ":my_player_no", ":selected_item_slot", ":item_id"),
       (else_try),
         (is_between, ":item_class", multi_item_class_type_gloves_begin, multi_item_class_type_gloves_end),
         (store_add, ":selected_item_slot", slot_player_selected_item_indices_begin, 7),
         (player_set_slot, ":my_player_no", ":selected_item_slot", ":item_id"),
       (else_try),
         (is_between, ":item_class", multi_item_class_type_horses_begin, multi_item_class_type_horses_end),
         (eq, "$g_horses_are_avaliable", 1),
         (store_add, ":selected_item_slot", slot_player_selected_item_indices_begin, 8),
         (player_set_slot, ":my_player_no", ":selected_item_slot", ":item_id"),
       (try_end),
     (try_end),
     ]),

  #script_multiplayer_display_available_items_for_troop_and_item_classes
  # Input: arg1 = troop_no, arg2 = item_classes_begin, arg3 = item_classes_end, arg4 = pos_x_begin, arg5 = pos_y_begin
  # Output: none
  ("multiplayer_display_available_items_for_troop_and_item_classes",
   [
     (store_script_param, ":troop_no", 1),
     (store_script_param, ":item_classes_begin", 2),
     (store_script_param, ":item_classes_end", 3),
     (store_script_param, ":pos_x_begin", 4),
     (store_script_param, ":pos_y_begin", 5),

     (assign, ":x_adder", 100),
     (try_begin),
       (gt, ":pos_x_begin", 500),
       (assign, ":x_adder", -100),
     (try_end),

     (store_sub, ":item_troop_slot", ":troop_no", multiplayer_troops_begin),
     (val_add, ":item_troop_slot", slot_item_multiplayer_availability_linked_list_begin),

     (try_for_range, ":cur_slot", multi_data_item_button_indices_begin, multi_data_item_button_indices_end),
       (troop_set_slot, "trp_multiplayer_data", ":cur_slot", -1),
     (try_end),

     (assign, ":num_available_items", 0),
     
     (try_for_range, ":item_no", all_items_begin, all_items_end),
       (item_get_slot, ":item_class", ":item_no", slot_item_multiplayer_item_class),
       (is_between, ":item_class", ":item_classes_begin", ":item_classes_end"),
       (this_or_next|eq, "$g_multiplayer_disallow_ranged_weapons", 0),
       (neg|is_between, ":item_class", multi_item_class_type_ranged_weapons_begin, multi_item_class_type_ranged_weapons_end),
       (item_slot_ge, ":item_no", ":item_troop_slot", 1),
       (store_add, ":cur_slot_index", ":num_available_items", multi_data_item_button_indices_begin),
       #using the result array for item_ids
       (troop_set_slot, "trp_multiplayer_data", ":cur_slot_index", ":item_no"),
       (val_add, ":num_available_items", 1),
     (try_end),

     #sorting
     (store_add, ":item_slots_end", ":num_available_items", multi_data_item_button_indices_begin),
     (store_sub, ":item_slots_end_minus_one", ":item_slots_end", 1),
     (try_for_range, ":cur_slot", multi_data_item_button_indices_begin, ":item_slots_end_minus_one"),
       (store_add, ":cur_slot_2_begin", ":cur_slot", 1),
       (try_for_range, ":cur_slot_2", ":cur_slot_2_begin", ":item_slots_end"),
         (troop_get_slot, ":item_1", "trp_multiplayer_data", ":cur_slot"),
         (troop_get_slot, ":item_2", "trp_multiplayer_data", ":cur_slot_2"),
         (call_script, "script_multiplayer_get_item_value_for_troop", ":item_1", ":troop_no"),
         (assign, ":item_1_point", reg0),
         (call_script, "script_multiplayer_get_item_value_for_troop", ":item_2", ":troop_no"),
         (assign, ":item_2_point", reg0),
         (item_get_slot, ":item_1_class", ":item_1", slot_item_multiplayer_item_class),
         (item_get_slot, ":item_2_class", ":item_2", slot_item_multiplayer_item_class),
         (val_mul, ":item_1_class", 1000000), #assuming maximum item price is 1000000
         (val_mul, ":item_2_class", 1000000), #assuming maximum item price is 1000000
         (val_add, ":item_1_point", ":item_1_class"),
         (val_add, ":item_2_point", ":item_2_class"),
         (lt, ":item_2_point", ":item_1_point"),
         (troop_set_slot, "trp_multiplayer_data", ":cur_slot", ":item_2"),
         (troop_set_slot, "trp_multiplayer_data", ":cur_slot_2", ":item_1"),
       (try_end),
     (try_end),

     (troop_get_slot, ":last_item_no", "trp_multiplayer_data", multi_data_item_button_indices_begin),
     (assign, ":num_item_classes", 0),
     (try_begin),
       (ge, ":last_item_no", 0),
       (item_get_slot, ":last_item_class", ":last_item_no", slot_item_multiplayer_item_class),

       (try_for_range, ":cur_slot", multi_data_item_button_indices_begin, ":item_slots_end"),
         (troop_get_slot, ":item_no", "trp_multiplayer_data", ":cur_slot"),
         (item_get_slot, ":item_class", ":item_no", slot_item_multiplayer_item_class),
         (neq, ":item_class", ":last_item_class"),
         (val_add, ":num_item_classes", 1),
         (assign, ":last_item_class", ":item_class"),
       (try_end),

       (try_begin),
         (store_mul, ":required_y", ":num_item_classes", 100),
         (gt, ":required_y", ":pos_y_begin"),
         (store_sub, ":dif", ":required_y", ":pos_y_begin"),
         (val_div, ":dif", 100),
         (val_add, ":dif", 1),
         (val_mul, ":dif", 100),
         (val_add, ":pos_y_begin", ":dif"),
       (try_end),

       (item_get_slot, ":last_item_class", ":last_item_no", slot_item_multiplayer_item_class),
     (try_end),
     (assign, ":cur_x", ":pos_x_begin"),
     (assign, ":cur_y", ":pos_y_begin"),
     (try_for_range, ":cur_slot", multi_data_item_button_indices_begin, ":item_slots_end"),
       (troop_get_slot, ":item_no", "trp_multiplayer_data", ":cur_slot"),
       (item_get_slot, ":item_class", ":item_no", slot_item_multiplayer_item_class),
       (try_begin),
         (neq, ":item_class", ":last_item_class"),
         (val_sub, ":cur_y", 100),
         (assign, ":cur_x", ":pos_x_begin"),
         (assign, ":last_item_class", ":item_class"),
       (try_end),
       (create_image_button_overlay, ":cur_obj", "mesh_mp_inventory_choose", "mesh_mp_inventory_choose"),
       (position_set_x, pos1, 800),
       (position_set_y, pos1, 800),
       (overlay_set_size, ":cur_obj", pos1),
       (position_set_x, pos1, ":cur_x"),
       (position_set_y, pos1, ":cur_y"),
       (overlay_set_position, ":cur_obj", pos1),
       (create_mesh_overlay_with_item_id, reg0, ":item_no"),
       (store_add, ":item_x", ":cur_x", 50),
       (store_add, ":item_y", ":cur_y", 50),
       (position_set_x, pos1, ":item_x"),
       (position_set_y, pos1, ":item_y"),
       (overlay_set_position, reg0, pos1),
       (val_add, ":cur_x", ":x_adder"),
     (try_end),
     ]),

  # script_multiplayer_fill_map_game_types
  # Input: game_type
  # Output: num_maps
  ("multiplayer_fill_map_game_types",
    [
      (store_script_param, ":game_type", 1),
      (try_for_range, ":i_multi", multi_data_maps_for_game_type_begin, multi_data_maps_for_game_type_end),
        (troop_set_slot, "trp_multiplayer_data", ":i_multi", -1),
      (try_end),
      (assign, ":num_maps", 0),
      (try_begin),
        (this_or_next|eq, ":game_type", multiplayer_game_type_deathmatch),
        (this_or_next|eq, ":game_type", multiplayer_game_type_duel),
        (eq, ":game_type", multiplayer_game_type_team_deathmatch),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin, "scn_multi_scene_1"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 1, "scn_multi_scene_2"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 2, "scn_multi_scene_4"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 3, "scn_multi_scene_7"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 4, "scn_multi_scene_9"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 5, "scn_multi_scene_11"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 6, "scn_multi_scene_12"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 7, "scn_multi_scene_14"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 8, "scn_multi_scene_17"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 9, "scn_multi_scene_18"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 10, "scn_multi_scene_19"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 11, "scn_multi_scene_20"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 12, "scn_random_multi_plain_medium"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 13, "scn_random_multi_plain_large"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 14, "scn_random_multi_steppe_medium"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 15, "scn_random_multi_steppe_large"),
        (assign, ":num_maps", 16),
     (else_try),
        (eq, ":game_type", multiplayer_game_type_battle),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin, "scn_multi_scene_1"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 1, "scn_multi_scene_2"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 2, "scn_multi_scene_4"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 3, "scn_multi_scene_7"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 4, "scn_multi_scene_9"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 5, "scn_multi_scene_11"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 6, "scn_multi_scene_12"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 7, "scn_multi_scene_14"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 8, "scn_multi_scene_17"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 9, "scn_multi_scene_18"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 10, "scn_multi_scene_19"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 11, "scn_multi_scene_20"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 12, "scn_random_multi_plain_medium"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 13, "scn_random_multi_plain_large"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 14, "scn_random_multi_steppe_medium"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 15, "scn_random_multi_steppe_large"),
        (assign, ":num_maps", 16),
     (else_try),
        (eq, ":game_type", multiplayer_game_type_destroy),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin, "scn_multi_scene_1"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 1, "scn_multi_scene_2"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 2, "scn_multi_scene_4"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 3, "scn_multi_scene_7"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 4, "scn_multi_scene_9"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 5, "scn_multi_scene_12"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 6, "scn_multi_scene_14"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 7, "scn_multi_scene_19"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 8, "scn_multi_scene_20"),
        (assign, ":num_maps", 9),
      (else_try),
        (eq, ":game_type", multiplayer_game_type_capture_the_flag),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin, "scn_multi_scene_1"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 1, "scn_multi_scene_2"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 2, "scn_multi_scene_4"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 3, "scn_multi_scene_7"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 4, "scn_multi_scene_9"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 5, "scn_multi_scene_11"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 6, "scn_multi_scene_12"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 7, "scn_multi_scene_14"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 8, "scn_multi_scene_17"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 9, "scn_multi_scene_18"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 10, "scn_multi_scene_19"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 11, "scn_multi_scene_20"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 12, "scn_random_multi_plain_medium"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 13, "scn_random_multi_plain_large"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 14, "scn_random_multi_steppe_medium"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 15, "scn_random_multi_steppe_large"),
        (assign, ":num_maps", 16),
     (else_try),
        (eq, ":game_type", multiplayer_game_type_headquarters),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin, "scn_multi_scene_1"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 1, "scn_multi_scene_2"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 2, "scn_multi_scene_4"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 3, "scn_multi_scene_7"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 4, "scn_multi_scene_9"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 5, "scn_multi_scene_11"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 6, "scn_multi_scene_12"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 7, "scn_multi_scene_14"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 8, "scn_multi_scene_17"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 9, "scn_multi_scene_18"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 10, "scn_multi_scene_19"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 11, "scn_multi_scene_20"),
        (assign, ":num_maps", 12),
      (else_try),
        (eq, ":game_type", multiplayer_game_type_siege),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin, "scn_multi_scene_3"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 1, "scn_multi_scene_8"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 2, "scn_multi_scene_10"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 3, "scn_multi_scene_13"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 4, "scn_multi_scene_15"),
        (troop_set_slot, "trp_multiplayer_data", multi_data_maps_for_game_type_begin + 5, "scn_multi_scene_16"),
        (assign, ":num_maps", 6),
      (try_end),
      (assign, reg0, ":num_maps"),
      ]),

  
  # script_multiplayer_count_players_bots
  # Input: none
  # Output: none
  ("multiplayer_count_players_bots",
    [
      (get_max_players, ":num_players"),
      (try_for_range, ":cur_player", 0, ":num_players"),
        (player_is_active, ":cur_player"),
        (player_set_slot, ":cur_player", slot_player_last_bot_count, 0),
      (try_end),

      (try_for_agents, ":cur_agent"),
        (agent_is_human, ":cur_agent"),
        (agent_is_alive, ":cur_agent"),
        (agent_get_player_id, ":agent_player", ":cur_agent"),
        (lt, ":agent_player", 0), #not a player
        (agent_get_group, ":agent_group", ":cur_agent"),
        (player_is_active, ":agent_group"),
        (player_get_slot, ":bot_count", ":agent_group", slot_player_last_bot_count),
        (val_add, ":bot_count", 1),
        (player_set_slot, ":agent_group", slot_player_last_bot_count, ":bot_count"),
      (try_end),
      ]),

  # script_multiplayer_find_player_leader_for_bot
  # Input: arg1 = team_no
  # Output: reg0 = player_no
  ("multiplayer_find_player_leader_for_bot",
    [
      (store_script_param, ":team_no", 1),
      (store_script_param, ":look_only_actives", 2),

      (team_get_faction, ":team_faction", ":team_no"),
      (assign, ":num_ai_troops", 0),
      (try_for_range, ":cur_ai_troop", multiplayer_ai_troops_begin, multiplayer_ai_troops_end),
        (store_troop_faction, ":ai_troop_faction", ":cur_ai_troop"),
        (eq, ":ai_troop_faction", ":team_faction"),
        (val_add, ":num_ai_troops", 1),
      (try_end),

      (call_script, "script_multiplayer_count_players_bots"),

      (assign, ":team_player_count", 0),

      (get_max_players, ":num_players"),
      (try_for_range, ":cur_player", 0, ":num_players"),
        (assign, ":continue", 0),
        (player_is_active, ":cur_player"),          
        (try_begin),
          (eq, ":look_only_actives", 0),
          (assign, ":continue", 1),
        (else_try),
          (neq, ":look_only_actives", 0),
          (player_get_agent_id, ":cur_agent", ":cur_player"),
          (ge, ":cur_agent", 0),
          (agent_is_alive, ":cur_agent"),
          (assign, ":continue", 1),
        (try_end),

        (eq, ":continue", 1),
      
        (player_get_team_no, ":player_team", ":cur_player"),
        (eq, ":team_no", ":player_team"),
        (val_add, ":team_player_count", 1),
      (try_end),
      (assign, ":result_leader", -1),
      (try_begin),      
        (gt, ":team_player_count", 0),
        (assign, ":total_bot_count", "$g_multiplayer_num_bots_team_1"),
        (try_begin),
          (eq, ":team_no", 1),
          (assign, ":total_bot_count", "$g_multiplayer_num_bots_team_2"),
        (try_end),
        (store_div, ":num_bots_for_each_player", ":total_bot_count", ":team_player_count"),
        (store_mul, ":check_remainder", ":num_bots_for_each_player", ":team_player_count"),
        (try_begin),
          (lt, ":check_remainder", ":total_bot_count"),
          (val_add, ":num_bots_for_each_player", 1),
        (try_end),
      
        (assign, ":total_bot_req", 0),
        (try_for_range, ":cur_player", 0, ":num_players"),
          (player_is_active, ":cur_player"),

          (player_get_agent_id, ":cur_agent", ":cur_player"),
          (ge, ":cur_agent", 0),
          (agent_is_alive, ":cur_agent"),
      
          (player_get_team_no, ":player_team", ":cur_player"),
          (eq, ":team_no", ":player_team"),
          (assign, ":ai_wanted", 0),
          (store_add, ":end_cond", slot_player_bot_type_1_wanted, ":num_ai_troops"),
          (try_for_range, ":bot_type_wanted_slot", slot_player_bot_type_1_wanted, ":end_cond"),
            (player_slot_ge, ":cur_player", ":bot_type_wanted_slot", 1),
            (assign, ":ai_wanted", 1),
            (assign, ":end_cond", 0), #break
          (try_end),
          (eq, ":ai_wanted", 1),
          (player_get_slot, ":player_bot_count", ":cur_player", slot_player_last_bot_count),
          (lt, ":player_bot_count", ":num_bots_for_each_player"),
          (val_add, ":total_bot_req", ":num_bots_for_each_player"),
          (val_sub, ":total_bot_req", ":player_bot_count"),
        (try_end),
        (gt, ":total_bot_req", 0),
      
        (store_random_in_range, ":random_bot", 0, ":total_bot_req"),
        (try_for_range, ":cur_player", 0, ":num_players"),
          (player_is_active, ":cur_player"),

          (player_get_agent_id, ":cur_agent", ":cur_player"),
          (ge, ":cur_agent", 0),
          (agent_is_alive, ":cur_agent"),

          (player_get_team_no, ":player_team", ":cur_player"),
          (eq, ":team_no", ":player_team"),
          (assign, ":ai_wanted", 0),
          (store_add, ":end_cond", slot_player_bot_type_1_wanted, ":num_ai_troops"),
          (try_for_range, ":bot_type_wanted_slot", slot_player_bot_type_1_wanted, ":end_cond"),
            (player_slot_ge, ":cur_player", ":bot_type_wanted_slot", 1),
            (assign, ":ai_wanted", 1),
            (assign, ":end_cond", 0), #break
          (try_end),
          (eq, ":ai_wanted", 1),
          (player_get_slot, ":player_bot_count", ":cur_player", slot_player_last_bot_count),
          (lt, ":player_bot_count", ":num_bots_for_each_player"),
          (val_sub, ":random_bot", ":num_bots_for_each_player"),
          (val_add, ":random_bot", ":player_bot_count"),
          (lt, ":random_bot", 0),
          (assign, ":result_leader", ":cur_player"),
          (assign, ":num_players", 0), #break
        (try_end),
      (try_end),
      (assign, reg0, ":result_leader"),
      ]),

  # script_multiplayer_find_bot_troop_and_group_for_spawn
  # Input: arg1 = team_no
  # Output: reg0 = troop_id, reg1 = group_id
  ("multiplayer_find_bot_troop_and_group_for_spawn",
    [
      (store_script_param, ":team_no", 1),
      (store_script_param, ":look_only_actives", 2),

      (call_script, "script_multiplayer_find_player_leader_for_bot", ":team_no", ":look_only_actives"),
      (assign, ":leader_player", reg0),

      (assign, ":available_troops_in_faction", 0),
      (assign, ":available_troops_to_spawn", 0),
      (team_get_faction, ":team_faction_no", ":team_no"),

      (try_for_range, ":troop_no", multiplayer_ai_troops_begin, multiplayer_ai_troops_end),
        (store_troop_faction, ":troop_faction", ":troop_no"),
        (eq, ":troop_faction", ":team_faction_no"),
        (store_add, ":wanted_slot", slot_player_bot_type_1_wanted, ":available_troops_in_faction"),
        (val_add, ":available_troops_in_faction", 1),
        (try_begin),
          (this_or_next|lt, ":leader_player", 0),
          (player_slot_ge, ":leader_player", ":wanted_slot", 1),
          (val_add, ":available_troops_to_spawn", 1),
        (try_end),
      (try_end),

      (assign, ":available_troops_in_faction", 0),

      (store_random_in_range, ":random_troop_index", 0, ":available_troops_to_spawn"),
      (assign, ":end_cond", multiplayer_ai_troops_end),
      (try_for_range, ":troop_no", multiplayer_ai_troops_begin, ":end_cond"),
        (store_troop_faction, ":troop_faction", ":troop_no"),
        (eq, ":troop_faction", ":team_faction_no"),
        (store_add, ":wanted_slot", slot_player_bot_type_1_wanted, ":available_troops_in_faction"),
        (val_add, ":available_troops_in_faction", 1),
        (this_or_next|lt, ":leader_player", 0),
        (player_slot_ge, ":leader_player", ":wanted_slot", 1),
        (val_sub, ":random_troop_index", 1),
        (lt, ":random_troop_index", 0),
        (assign, ":end_cond", 0),
        (assign, ":selected_troop", ":troop_no"),
      (try_end),
      (assign, reg0, ":selected_troop"),
      (assign, reg1, ":leader_player"),
      ]),	

  # script_multiplayer_change_leader_of_bot
  # Input: arg1 = agent_no
  # Output: none
  ("multiplayer_change_leader_of_bot",
    [
      (store_script_param, ":agent_no", 1),
      (agent_get_team, ":team_no", ":agent_no"),
      (call_script, "script_multiplayer_find_player_leader_for_bot", ":team_no", 1),
      (assign, ":leader_player", reg0),
      (agent_set_group, ":agent_no", ":leader_player"),
      ]),
      
  ("multiplayer_find_spawn_point",
  [
     (store_script_param, ":team_no", 1),
     (store_script_param, ":examine_all_spawn_points", 2), #0-dm, 1-tdm, 2-cf, 3-hq, 4-sg
     (store_script_param, ":is_horseman", 3), #0:no, 1:yes, -1:do not care
     
     (set_fixed_point_multiplier, 100),
                   
     (assign, ":flags", 0),
     
     (try_begin),
       (eq, ":examine_all_spawn_points", 1),
       (val_or, ":flags", spf_examine_all_spawn_points),
     (try_end),
     
     (try_begin),
       (eq, ":is_horseman", 1),
       (val_or, ":flags", spf_is_horseman),
     (try_end),

     (try_begin),
       (eq, "$g_multiplayer_game_type", multiplayer_game_type_deathmatch),
       (eq, "$g_multiplayer_game_type", multiplayer_game_type_duel),
       (val_or, ":flags", spf_all_teams_are_enemy),
       (val_or, ":flags", spf_try_to_spawn_close_to_at_least_one_enemy),
     (else_try),
       (eq, "$g_multiplayer_game_type", multiplayer_game_type_team_deathmatch),
       (val_or, ":flags", spf_try_to_spawn_close_to_at_least_one_enemy),       
     (else_try),
       (eq, "$g_multiplayer_game_type", multiplayer_game_type_siege),
       (val_or, ":flags", spf_team_1_spawn_far_from_entry_66), #team 1 agents will not spawn 70 meters around of entry 0
       (val_or, ":flags", spf_team_0_walkers_spawn_at_high_points),
       (val_or, ":flags", spf_team_0_spawn_near_entry_66),       
       (val_or, ":flags", spf_care_agent_to_agent_distances_less),
     (else_try),
       (eq, "$g_multiplayer_game_type", multiplayer_game_type_capture_the_flag),
       (val_or, ":flags", spf_team_1_spawn_far_from_entry_0), #team 1 agents will not spawn 70 meters around of entry 0
       (val_or, ":flags", spf_team_0_spawn_far_from_entry_32), #team 0 agents will not spawn 70 meters around of entry 32
       (val_or, ":flags", spf_try_to_spawn_close_to_at_least_one_enemy),       
     (else_try),       
       (eq, "$g_multiplayer_game_type", multiplayer_game_type_headquarters),                     
       (assign, ":assigned_flag_count", 0),
       
       (store_sub, ":maximum_moved_flag_distance", multi_headquarters_pole_height, 50), #900 - 50 = 850
       (store_mul, ":maximum_moved_flag_distance_sq", ":maximum_moved_flag_distance", ":maximum_moved_flag_distance"),
       (val_div, ":maximum_moved_flag_distance_sq", 100), #dividing 100, because fixed point multiplier is 100 and it is included twice, look above line.
       
       (try_for_range, ":flag_no", 0, "$g_number_of_flags"),
         (store_add, ":cur_flag_owner_slot", multi_data_flag_owner_begin, ":flag_no"),
         (troop_get_slot, ":cur_flag_owner", "trp_multiplayer_data", ":cur_flag_owner_slot"),         
         
         (scene_prop_get_instance, ":pole_id", "spr_headquarters_pole_code_only", ":flag_no"),
         (prop_instance_get_position, pos0, ":pole_id"),
         
         (try_begin),
           (eq, ":cur_flag_owner", 1),
           (scene_prop_get_instance, ":flag_of_team_1", "$team_1_flag_scene_prop", ":flag_no"),                      
                      
           (prop_instance_get_position, pos1, ":flag_of_team_1"),
           (get_sq_distance_between_positions, ":flag_height_sq", pos0, pos1),           
           (ge, ":flag_height_sq", ":maximum_moved_flag_distance_sq"),
           
           (set_spawn_effector_scene_prop_id, ":assigned_flag_count", ":flag_of_team_1"),
           (val_add, ":assigned_flag_count", 1),
         (else_try),
           (eq, ":cur_flag_owner", 2),
           (scene_prop_get_instance, ":flag_of_team_2", "$team_2_flag_scene_prop", ":flag_no"),
           
           (prop_instance_get_position, pos1, ":flag_of_team_2"),
           (get_sq_distance_between_positions, ":flag_height_sq", pos0, pos1),           
           (ge, ":flag_height_sq", ":maximum_moved_flag_distance_sq"),

           (set_spawn_effector_scene_prop_id, ":assigned_flag_count", ":flag_of_team_2"),
           (val_add, ":assigned_flag_count", 1),
         (try_end),
       (try_end),
       (set_spawn_effector_scene_prop_id, ":assigned_flag_count", -1),
     (try_end),     

     (multiplayer_find_spawn_point, reg0, ":team_no", ":flags"),
  ]),
    
  # script_multiplayer_find_spawn_point_2
  # Input: arg1 = team_no, arg2 = examine_all_spawn_points, arg3 = is_horseman
  # Output: reg0 = entry_point_no
  ("multiplayer_find_spawn_point_2",
   [
     (store_script_param, ":team_no", 1),
     (store_script_param, ":examine_all_spawn_points", 2), #0-dm, 1-tdm, 2-cf, 3-hq, 4-sg
     (store_script_param, ":is_horseman", 3), #0:no, 1:yes, -1:do not care

     (assign, ":best_entry_point_score", -10000000),
     (assign, ":best_entry_point", 0),

     (assign, ":num_operations", 0),

     (assign, ":num_human_agents_div_3_plus_one", 0),
     (try_begin), #counting number of agents
       (this_or_next|eq, "$g_multiplayer_game_type", multiplayer_game_type_capture_the_flag),
       (this_or_next|eq, "$g_multiplayer_game_type", multiplayer_game_type_headquarters),
       (eq, "$g_multiplayer_game_type", multiplayer_game_type_siege),
       (try_for_agents, ":i_agent"),
         (agent_is_alive, ":i_agent"),
         (agent_is_human, ":i_agent"),
         (val_add, ":num_human_agents_div_3_plus_one", 1),
       (try_end),
     (try_end),

     (assign, ":num_human_agents_plus_one", ":num_human_agents_div_3_plus_one"),

     (try_begin), 
       (le, ":num_human_agents_plus_one", 4),
       (assign, ":random_number_upper_limit", 2), #this is not typo-mistake this should be 2 too, not 1.
     (else_try), 
       (le, ":num_human_agents_plus_one", 8),
       (assign, ":random_number_upper_limit", 2),
     (else_try), 
       (le, ":num_human_agents_plus_one", 16),
       (assign, ":random_number_upper_limit", 3),
     (else_try),
       (le, ":num_human_agents_plus_one", 24),
       (assign, ":random_number_upper_limit", 4),
     (else_try),
       (le, ":num_human_agents_plus_one", 32),
       (assign, ":random_number_upper_limit", 5),
     (else_try),
       (le, ":num_human_agents_plus_one", 40),
       (assign, ":random_number_upper_limit", 6),
     (else_try),
       (assign, ":random_number_upper_limit", 7),
     (try_end),

     (val_div, ":num_human_agents_div_3_plus_one", 3),
     (val_add, ":num_human_agents_div_3_plus_one", 1),
     (store_mul, ":negative_num_human_agents_div_3_plus_one", ":num_human_agents_div_3_plus_one", -1),

     (try_begin),
       (eq, ":examine_all_spawn_points", 1),
       (assign, ":random_number_upper_limit", 1),
     (try_end),
     
     (try_begin), #counting number of our flags and enemy flags
       (eq, "$g_multiplayer_game_type", multiplayer_game_type_headquarters),
       (assign, ":our_flag_count", 0),
       (assign, ":enemy_flag_count", 0),     
       (try_for_range, ":flag_no", 0, "$g_number_of_flags"),
         (store_add, ":cur_flag_owner_slot", multi_data_flag_owner_begin, ":flag_no"),
         (troop_get_slot, ":cur_flag_owner", "trp_multiplayer_data", ":cur_flag_owner_slot"),
         (neq, ":cur_flag_owner", 0),
         (val_sub, ":cur_flag_owner", 1),
         (try_begin),
           (eq, ":cur_flag_owner", ":team_no"),
           (val_add, ":our_flag_count", 1),
         (else_try),
           (val_add, ":enemy_flag_count", 1),
         (try_end),
       (try_end),
     (try_end),

     (assign, ":first_agent", 0),
     (try_begin), #first spawned agents will be spawned at their base points in tdm, cf and hq mods.
       (this_or_next|eq, "$g_multiplayer_game_type", multiplayer_game_type_team_deathmatch),
       (this_or_next|eq, "$g_multiplayer_game_type", multiplayer_game_type_capture_the_flag),
       (eq, "$g_multiplayer_game_type", multiplayer_game_type_headquarters),
       (try_begin),
         (eq, ":team_no", 0),
         (eq, "$g_multiplayer_team_1_first_spawn", 1),
         (assign, ":first_agent", 1),
         (assign, "$g_multiplayer_team_1_first_spawn", 0),
       (else_try),
         (eq, ":team_no", 1),
         (eq, "$g_multiplayer_team_2_first_spawn", 1),
         (assign, ":first_agent", 1),
         (assign, "$g_multiplayer_team_2_first_spawn", 0),
       (try_end),
     (try_end),
     
     (try_begin),
       (eq, ":first_agent", 1),
       (store_mul, ":best_entry_point", ":team_no", multi_num_valid_entry_points_div_2),
     (else_try),
       (try_for_range, ":i_entry_point", 0, multi_num_valid_entry_points),
         (assign, ":minimum_enemy_distance", 3000), 
         (assign, ":second_minimum_enemy_distance", 3000), 
              
         (assign, ":entry_point_score", 0),
         (store_random_in_range, ":random_value", 0, ":random_number_upper_limit"), #in average it is 5
         (eq, ":random_value", 0),
         (entry_point_get_position, pos0, ":i_entry_point"), #pos0 holds current entry point position
         (try_for_agents, ":i_agent"),
           (agent_is_alive, ":i_agent"),
           (agent_is_human, ":i_agent"),
           (agent_get_team, ":agent_team", ":i_agent"),     
           (try_begin),
             (this_or_next|eq, "$g_multiplayer_game_type", multiplayer_game_type_team_deathmatch),
             (this_or_next|eq, "$g_multiplayer_game_type", multiplayer_game_type_capture_the_flag),
             (this_or_next|eq, "$g_multiplayer_game_type", multiplayer_game_type_headquarters),
             (eq, "$g_multiplayer_game_type", multiplayer_game_type_siege),
             (try_begin),
               (teams_are_enemies, ":team_no", ":agent_team"),
               (assign, ":multiplier", -2),
             (else_try),
               (assign, ":multiplier", 1),
             (try_end),
           (else_try),
             (this_or_next|eq, "$g_multiplayer_game_type", multiplayer_game_type_deathmatch),
             (eq, "$g_multiplayer_game_type", multiplayer_game_type_duel),
             (assign, ":multiplier", -1), 
           (try_end),     
           (agent_get_position, pos1, ":i_agent"),
           (get_distance_between_positions_in_meters, ":distance", pos0, pos1),
           (val_add, ":num_operations", 1),
           (try_begin),
             (try_begin), #find closest enemy soldiers
               (lt, ":multiplier", 0),
               (try_begin),
                 (lt, ":distance", ":minimum_enemy_distance"),
                 (assign, ":second_minimum_enemy_distance", ":minimum_enemy_distance"),
                 (assign, ":minimum_enemy_distance", ":distance"),
               (else_try),
                 (lt, ":distance", ":second_minimum_enemy_distance"),
                 (assign, ":second_minimum_enemy_distance", ":distance"),
               (try_end),
             (try_end),
     
             (lt, ":distance", 100),
             (try_begin), #do not spawn over or too near to another agent (limit is 2 meters, squared 4 meters)
               (lt, ":distance", 3),
               (try_begin),
                 (this_or_next|eq, ":examine_all_spawn_points", 0),
                 (this_or_next|lt, ":multiplier", 0), #new added 20.08.08
                 (neq, "$g_multiplayer_game_type", multiplayer_game_type_siege),
                 (try_begin),
                   (lt, ":distance", 1),                 
                   (assign, ":dist_point", -1000000), #never place 
                 (else_try),
                   (lt, ":distance", 2),
                   (try_begin),
                     (lt, ":multiplier", 0), 
                     (assign, ":dist_point", -20000),
                   (else_try),
                     (assign, ":dist_point", -2000), #can place, friend and distance is between 1-2 meters
                   (try_end), 
                 (else_try),
                   (try_begin),
                     (lt, ":multiplier", 0), 
                     (assign, ":dist_point", -10000), 
                   (else_try),
                     (assign, ":dist_point", -1000), #can place, friend and distance is between 2-3 meters
                   (try_end),
                 (try_end),
               (else_try),
                 #if examinining all spawn points and mod is siege only. This happens in new round start placings.
                 (try_begin),
                   (lt, ":distance", 1),                 
                   (assign, ":dist_point", -20000), #very hard to place distance is < 1 meter
                 (else_try),
                   (lt, ":distance", 2),
                   (assign, ":dist_point", -2000),
                 (else_try),       
                   (assign, ":dist_point", -1000), #can place, distance is between 2-3 meters
                 (try_end),                 
               (try_end),
     
               (val_mul, ":dist_point", ":num_human_agents_div_3_plus_one"),                 
             (else_try),
               (assign, ":dist_point", 0),
               (this_or_next|neq, "$g_multiplayer_game_type", multiplayer_game_type_siege),
               (this_or_next|lt, ":multiplier", 0),
               (eq, ":team_no", 1), #only attackers are effected by positive enemy & friend distance at siege mod, defenders only get negative score effect a bit     

               (try_begin), #in siege give no positive or negative score to > 40m distance. (6400 = 10000 - 3600(60 * 60))
                 (this_or_next|eq, "$g_multiplayer_game_type", multiplayer_game_type_siege),

                 (this_or_next|eq, "$g_multiplayer_game_type", multiplayer_game_type_deathmatch), #new added after moving below part to above
                 (this_or_next|eq, "$g_multiplayer_game_type", multiplayer_game_type_duel), #new added after moving below part to above
                 (eq, "$g_multiplayer_game_type", multiplayer_game_type_team_deathmatch), #new added after moving below part to above

                 (store_sub, ":dist_point", multiplayer_spawn_min_enemy_dist_limit, ":distance"), #up to 40 meters give (positive(if friend) or negative(if enemy)) points
                 (val_max, ":dist_point", 0),
                 (val_mul, ":dist_point", ":dist_point"),
               (else_try),
                 (store_mul, ":one_and_half_limit", multiplayer_spawn_min_enemy_dist_limit, 3),
                 (val_div, ":one_and_half_limit", 2),
                 (store_sub, ":dist_point", ":one_and_half_limit", ":distance"), #up to 60 meters give (positive(if friend) or negative(if enemy)) points
                 (val_mul, ":dist_point", ":dist_point"),
               (try_end),
            
               (val_mul, ":dist_point", ":multiplier"),
             (try_end),
             (val_add, ":entry_point_score", ":dist_point"),
           (try_end),
         (try_end),

         (try_begin),
           (eq, "$g_multiplayer_game_type", multiplayer_game_type_siege),
           (store_mul, ":max_enabled_agent_distance_score", 1000, ":num_human_agents_div_3_plus_one"),
           (ge, ":entry_point_score", ":max_enabled_agent_distance_score"),
           (assign, ":entry_point_score", ":max_enabled_agent_distance_score"),
         (try_end),

         (try_begin),      
           (neq, "$g_multiplayer_game_type", multiplayer_game_type_siege),

           #(assign, ":minimum_enemy_dist_score", 0), #close also these with displays
           #(assign, ":second_minimum_enemy_dist_score", 0), #close also these with displays
           #(assign, reg2, ":minimum_enemy_distance"), #close also these with displays
           #(assign, reg3, ":second_minimum_enemy_distance"), #close also these with displays
          
           (try_begin), #if minimum enemy dist score is greater than 40(multiplayer_spawn_above_opt_enemy_dist_point) meters then give negative score
             (lt, ":minimum_enemy_distance", 3000), 
             (try_begin),
               (gt, ":minimum_enemy_distance", multiplayer_spawn_above_opt_enemy_dist_point),
               (val_sub, ":minimum_enemy_distance", multiplayer_spawn_above_opt_enemy_dist_point),
               (store_mul, ":minimum_enemy_dist_score", ":minimum_enemy_distance", -50),
               (val_mul, ":minimum_enemy_dist_score", ":num_human_agents_div_3_plus_one"),
               (val_add, ":entry_point_score", ":minimum_enemy_dist_score"),
             (try_end),
           (try_end),

           (try_begin), #if second minimum enemy dist score is greater than 40(multiplayer_spawn_above_opt_enemy_dist_point) meters then give negative score
             (lt, ":second_minimum_enemy_distance", 3000), #3000 x 3000
             (try_begin),
               (gt, ":second_minimum_enemy_distance", multiplayer_spawn_above_opt_enemy_dist_point),
               (val_sub, ":second_minimum_enemy_distance", multiplayer_spawn_above_opt_enemy_dist_point),
               (store_mul, ":second_minimum_enemy_dist_score", ":second_minimum_enemy_distance", -50),
               (val_mul, ":second_minimum_enemy_dist_score", ":num_human_agents_div_3_plus_one"),
               (val_add, ":entry_point_score", ":second_minimum_enemy_dist_score"),
             (try_end),
           (try_end),
           
           #(assign, reg0, ":minimum_enemy_dist_score"), #close also above assignment lines with these displays
           #(assign, reg1, ":second_minimum_enemy_dist_score"), #close also above assignment lines with these displays
           #(display_message, "@{!}minimum enemy distance : {reg2}, score : {reg0}"), #close also above assignment lines with these displays
           #(display_message, "@{!}second minimum enemy distance : {reg3}, score : {reg1}"), #close also above assignment lines with these displays
         (try_end),
 
         (try_begin), #giving positive points for "distance of entry point position to ground" while searching for entry point for defender team
           (neq, ":is_horseman", -1), #if being horseman or rider is not (not important)

           #additional score to entry points which has distance to ground value of > 0 meters
           (position_get_distance_to_terrain, ":height_to_terrain", pos0),     
           (val_max, ":height_to_terrain", 0),
           (val_min, ":height_to_terrain", 300),
           (ge, ":height_to_terrain", 40),                      
           
           (store_mul, ":height_to_terrain_score", ":height_to_terrain", ":num_human_agents_div_3_plus_one"), #it was 8
           
           (try_begin),
             (eq, "$g_multiplayer_game_type", multiplayer_game_type_team_deathmatch),
             (val_mul, ":height_to_terrain_score", 16),
           (else_try),  
             (val_mul, ":height_to_terrain_score", 4),
           (try_end),
           
           (try_begin),
             (eq, ":is_horseman", 0),
             (try_begin),
               (eq, "$g_multiplayer_game_type", multiplayer_game_type_siege), #but only in siege mod, defender infantries will get positive points for spawning in high places.
               (eq, ":team_no", 0), 
               (val_add, ":entry_point_score", ":height_to_terrain_score"),
             (try_end),
           (else_try),
             (val_mul, ":height_to_terrain_score", 5),
             (val_sub, ":entry_point_score", ":height_to_terrain_score"),
           (try_end),
         (try_end),
    
         (try_begin), #additional random entry point score at deathmatch, teamdethmatch, capture the flag and siege
           (this_or_next|eq, "$g_multiplayer_game_type", multiplayer_game_type_siege),
           (this_or_next|eq, "$g_multiplayer_game_type", multiplayer_game_type_deathmatch),
           (this_or_next|eq, "$g_multiplayer_game_type", multiplayer_game_type_duel),
           (this_or_next|eq, "$g_multiplayer_game_type", multiplayer_game_type_capture_the_flag),
           (eq, "$g_multiplayer_game_type", multiplayer_game_type_team_deathmatch),
           (try_begin),
             (neq, "$g_multiplayer_game_type", multiplayer_game_type_siege),
             (store_random_in_range, ":random_value", 0, 400),

             (try_begin),
               (eq, "$g_multiplayer_game_type", multiplayer_game_type_capture_the_flag),
               (val_mul, ":random_value", 5),
             (try_end),
           (else_try),
             (eq, ":team_no", 1),
             (store_random_in_range, ":random_value", 0, 600), #siege-attacker
           (else_try),
             (store_random_in_range, ":random_value", 0, 200), #siege-defender
           (try_end),
           (val_mul, ":random_value", ":num_human_agents_div_3_plus_one"),
           (val_add, ":entry_point_score", ":random_value"),
         (try_end),

         (try_begin),
           (this_or_next|eq, "$g_multiplayer_game_type", multiplayer_game_type_capture_the_flag),
           (eq, "$g_multiplayer_game_type", multiplayer_game_type_siege),

           (try_begin),         
             (eq, "$g_multiplayer_game_type", multiplayer_game_type_capture_the_flag),
             (try_begin),
               (eq, ":team_no", 0),
               (entry_point_get_position, pos1, multi_base_point_team_1), #our base is at pos1
               (entry_point_get_position, pos2, multi_base_point_team_2), #enemy base is at pos2
             (else_try),
               (entry_point_get_position, pos1, multi_base_point_team_2), #our base is at pos2
               (entry_point_get_position, pos2, multi_base_point_team_1), #enemy base is at pos1
             (try_end),
           (else_try),
             (try_begin), #siege
               (eq, ":team_no", 0),
               (entry_point_get_position, pos1, multi_siege_flag_point), #our base is at pos1 (it was multi_initial_spawn_point_team_1 changed at v622)
               (entry_point_get_position, pos2, multi_initial_spawn_point_team_2), #enemy base is at pos2
             (else_try),
               (entry_point_get_position, pos1, multi_initial_spawn_point_team_2), #our base is at pos2
               (entry_point_get_position, pos2, multi_siege_flag_point), #enemy base is at pos1 (it was multi_initial_spawn_point_team_1 changed at v622)
             (try_end),
           (try_end),

           (try_begin),         
             (eq, "$g_multiplayer_game_type", multiplayer_game_type_siege),
             (position_get_z, ":pos0_z", pos0),
             (position_set_z, pos1, ":pos0_z"), #make z of our base same with entry point position z
             (position_set_z, pos2, ":pos0_z"), #make z of enemy base same with entry point position z
           (try_end),
           
           (get_sq_distance_between_positions_in_meters, ":sq_dist_to_our_base", pos0, pos1),
           (get_sq_distance_between_positions_in_meters, ":sq_dist_to_enemy_base", pos0, pos2),                 
           (get_distance_between_positions_in_meters, ":dist_to_enemy_base", pos0, pos2),

           #give positive points if this entry point is near to our base.
           (assign, ":dist_to_our_base_point", 0),     
           (try_begin), #capture the flag (points for being near to base)
             (eq, "$g_multiplayer_game_type", multiplayer_game_type_capture_the_flag),

             (get_distance_between_positions_in_meters, ":dist_to_our_base", pos0, pos1),
             (lt, ":dist_to_our_base", 100),
             (store_sub, ":dist_to_our_base_point", 100, ":dist_to_our_base"),

             (try_begin), #assign all 75-100's to 75
               (gt, ":dist_to_our_base_point", 75),
               (assign, ":dist_to_our_base_point", 75),
             (try_end),
     
             (val_mul, ":dist_to_our_base_point", 50), #0..5000 (increase is linear)
     
             (val_mul, ":dist_to_our_base_point", ":num_human_agents_div_3_plus_one"),
           (else_try), #siege (points for being near to base)
             (lt, ":sq_dist_to_our_base", 10000), #in siege give entry points score until 100m distance is reached
             (try_begin),
               (eq, ":team_no", 0),
               (try_begin),
                 (lt, ":sq_dist_to_our_base", 2500), #if distance is < 50m in siege give all highest point possible
                 (assign, ":sq_dist_to_our_base", 0),
               (else_try),
                 (val_sub, ":sq_dist_to_our_base", 2500),
                 (val_mul, ":sq_dist_to_our_base", 2),
               (try_end),
             (try_end),

             (store_sub, ":dist_to_our_base_point", 10000, ":sq_dist_to_our_base"),

             #can be (10000 - (10000 - 2500) * 2) = -5000 (for only defenders) so we are adding this loss.
             (val_add, ":dist_to_our_base_point", 5000), #so score getting from being near to base changes between 0 to 15000

             (try_begin),
               (eq, ":team_no", 0), 
             (else_try), #in siege mod for attackers being near to base entry point has 45 times less importance
               (val_div, ":dist_to_our_base_point", 45),
             (try_end),
             (val_mul, ":dist_to_our_base_point", ":num_human_agents_div_3_plus_one"),
           (try_end),

           (val_add, ":entry_point_score", ":dist_to_our_base_point"),


           #give negative points if this entry point is near to enemy base.
           (assign, ":dist_to_enemy_base_point", 0),
           (try_begin), #capture the flag
             (eq, "$g_multiplayer_game_type", multiplayer_game_type_capture_the_flag),

             (lt, ":dist_to_enemy_base", 150),
             (store_sub, ":dist_to_enemy_base_point", 150, ":dist_to_enemy_base"),

             (try_begin), #assign 150 to 150 + (150 - 50) * 2 = 350, assign 100 to 100 + (100 - 50) * 2 = 200
               (gt, ":dist_to_enemy_base_point", 50),
               (store_sub, ":dist_to_enemy_base_point_minus_50", ":dist_to_enemy_base_point", 50),
               (val_mul, ":dist_to_enemy_base_point_minus_50", 2),
               (val_add, ":dist_to_enemy_base_point", ":dist_to_enemy_base_point_minus_50"),
             (try_end),
     
             (val_mul, ":dist_to_enemy_base_point", -50), #-7500(with extras 350 * 50 = -17500)..0 (increase is linear)
     
             (val_mul, ":dist_to_enemy_base_point", ":num_human_agents_div_3_plus_one"),
           (else_try), 
             (this_or_next|neq, "$g_multiplayer_game_type", multiplayer_game_type_siege),
             (eq, ":team_no", 1),

             (assign, ":dist_to_enemy_base_point", 0),
     
             (try_begin),
               (neq, "$g_multiplayer_game_type", multiplayer_game_type_siege),

               (try_begin),
                 (lt, ":sq_dist_to_enemy_base", 10000),
                 (store_sub, ":dist_to_enemy_base_point", 10000, ":sq_dist_to_enemy_base"),
                 (val_div, ":dist_to_enemy_base_point", 4),
                 (val_mul, ":dist_to_enemy_base_point", ":negative_num_human_agents_div_3_plus_one"),
               (try_end),
             (else_try),     
               (val_max, ":dist_to_enemy_base", 60), #<60 meters has all most negative score

               (try_begin),
                 (eq, ":is_horseman", 1),
                 (assign, ":optimal_distance", 120),
               (else_try),
                 (assign, ":optimal_distance", 80),
               (try_end),
     
               (try_begin),     
                 (le, ":dist_to_enemy_base", ":optimal_distance"),
                 (store_sub, ":dist_to_enemy_base_point", ":optimal_distance", ":dist_to_enemy_base"),
                 (val_mul, ":dist_to_enemy_base_point", 180), #-3600 max
               (else_try),
                 (store_sub, ":dist_to_enemy_base_point", ":dist_to_enemy_base", ":optimal_distance"),
                 (val_mul, ":dist_to_enemy_base_point", 30), #-unlimited max but lower slope
               (try_end),

               (val_sub, ":dist_to_enemy_base_point", 600),
               (val_max, ":dist_to_enemy_base_point", 0),
     
               (val_mul, ":dist_to_enemy_base_point", ":negative_num_human_agents_div_3_plus_one"),
             (try_end),             
           (try_end),

           (val_add, ":entry_point_score", ":dist_to_enemy_base_point"),
         (else_try),
           (eq, "$g_multiplayer_game_type", multiplayer_game_type_headquarters),
     
           (try_for_range, ":flag_no", 0, "$g_number_of_flags"),
             (store_add, ":cur_flag_owner_slot", multi_data_flag_owner_begin, ":flag_no"),
             (troop_get_slot, ":cur_flag_owner", "trp_multiplayer_data", ":cur_flag_owner_slot"),
             (neq, ":cur_flag_owner", 0),
             (val_sub, ":cur_flag_owner", 1),

             (scene_prop_get_instance, ":pole_id", "spr_headquarters_pole_code_only", ":flag_no"), 
             (prop_instance_get_position, pos1, ":pole_id"), #pos1 holds pole position.

             (get_sq_distance_between_positions_in_meters, ":sq_dist_to_cur_pole", pos0, pos1),
             (lt, ":sq_dist_to_cur_pole", 6400),

             (try_begin),
               (eq, ":cur_flag_owner", ":team_no"),
               (store_sub, ":dist_to_flag_point", 6400, ":sq_dist_to_cur_pole"), #up to 80 meters give positive points if entry point is near our base
               (val_mul, ":dist_to_flag_point", 2),
               (val_div, ":dist_to_flag_point", ":our_flag_count"),     
               (val_mul, ":dist_to_flag_point", ":num_human_agents_div_3_plus_one"),
             (else_try),
               (store_sub, ":dist_to_flag_point", 6400, ":sq_dist_to_cur_pole"), #up to 80 meters give negative points if entry point is near enemy base
               (val_mul, ":dist_to_flag_point", 2),
               (val_div, ":dist_to_flag_point", ":enemy_flag_count"),     
               (val_mul, ":dist_to_flag_point", ":negative_num_human_agents_div_3_plus_one"),
             (try_end),
             (val_add, ":entry_point_score", ":dist_to_flag_point"),
           (try_end),           
         (try_end),

         #(assign, reg1, ":i_entry_point"),
         #(assign, reg2, ":entry_point_score"),
         #(display_message, "@{!}entry_no : {reg1} , entry_score : {reg2}"),

         (gt, ":entry_point_score", ":best_entry_point_score"),
         (assign, ":best_entry_point_score", ":entry_point_score"),
         (assign, ":best_entry_point", ":i_entry_point"),         
       (try_end),

       #(assign, reg0, ":best_entry_point"), 
       #(assign, reg1, ":best_entry_point_score"),
       #(assign, reg2, ":num_operations"),       
       #(assign, reg7, ":is_horseman"),
       #(display_message, "@{!},is horse:{reg7}, best entry:{reg0}, best entry score:{reg1}, num_operations:{reg2}"),
     (try_end),
     (assign, reg0, ":best_entry_point"), 
     ]),
  
  #script_multiplayer_buy_agent_equipment
  # Input: arg1 = player_no
  # Output: none
  ("multiplayer_buy_agent_equipment",
   [
     (store_script_param, ":player_no", 1),
     (player_get_troop_id, ":player_troop", ":player_no"),
     (player_get_gold, ":player_gold", ":player_no"),
     (player_get_slot, ":added_gold", ":player_no", slot_player_last_rounds_used_item_earnings),
     (player_set_slot, ":player_no", slot_player_last_rounds_used_item_earnings, 0),
     (val_add, ":player_gold", ":added_gold"),
     (assign, ":armor_bought", 0),
     
     #moving original values to temp slots
     (try_for_range, ":i_item", slot_player_selected_item_indices_begin, slot_player_selected_item_indices_end),
       (player_get_slot, ":selected_item_index", ":player_no", ":i_item"),
       (store_sub, ":i_cur_selected_item", ":i_item", slot_player_selected_item_indices_begin),
       (try_begin),
         (player_item_slot_is_picked_up, ":player_no", ":i_cur_selected_item"),
         (assign, ":selected_item_index", -1),
       (try_end),
       (val_add, ":i_cur_selected_item", slot_player_cur_selected_item_indices_begin),
       (player_set_slot, ":player_no", ":i_cur_selected_item", ":selected_item_index"),
     (try_end),
     (assign, ":end_cond", 1000),
     (try_for_range, ":unused", 0, ":end_cond"),
       (call_script, "script_multiplayer_calculate_cur_selected_items_cost", ":player_no", 0),
       (assign, ":total_cost", reg0),
       (try_begin),
         (gt, ":total_cost", ":player_gold"),
         #downgrade one of the selected items
         #first normalize the prices
         #then prioritize some of the weapon classes for specific troop classes
         (call_script, "script_multiplayer_get_troop_class", ":player_troop"),
         (assign, ":player_troop_class", reg0),

         (assign, ":max_cost_value", 0),
         (assign, ":max_cost_value_index", -1),
         (try_for_range, ":i_item", slot_player_cur_selected_item_indices_begin, slot_player_cur_selected_item_indices_end),
           (player_get_slot, ":item_id", ":player_no", ":i_item"),
           (ge, ":item_id", 0), #might be -1 for horses etc.
           (call_script, "script_multiplayer_get_item_value_for_troop", ":item_id", ":player_troop"),
           (assign, ":item_value", reg0),
           (store_sub, ":item_type", ":i_item", slot_player_cur_selected_item_indices_begin),
           (try_begin), #items
             (this_or_next|eq, ":item_type", 0),
             (this_or_next|eq, ":item_type", 1),
             (this_or_next|eq, ":item_type", 2),
             (eq, ":item_type", 3),
             (val_mul, ":item_value", 5),
           (else_try), #head
             (eq, ":item_type", 4),
             (val_mul, ":item_value", 4),
           (else_try), #body
             (eq, ":item_type", 5),
             (val_mul, ":item_value", 2),
           (else_try), #foot
             (eq, ":item_type", 6),
             (val_mul, ":item_value", 8),
           (else_try), #gloves
             (eq, ":item_type", 7),
             (val_mul, ":item_value", 8),
           (else_try), #horse
             #base value (most expensive)
           (try_end),
           (item_get_slot, ":item_class", ":item_id", slot_item_multiplayer_item_class),
           (try_begin),
             (eq, ":player_troop_class", multi_troop_class_infantry),
             (this_or_next|eq, ":item_class", multi_item_class_type_sword),
             (this_or_next|eq, ":item_class", multi_item_class_type_axe),
             (this_or_next|eq, ":item_class", multi_item_class_type_blunt),
             (this_or_next|eq, ":item_class", multi_item_class_type_war_picks),
             (this_or_next|eq, ":item_class", multi_item_class_type_two_handed_sword),
             (this_or_next|eq, ":item_class", multi_item_class_type_small_shield),
             (eq, ":item_class", multi_item_class_type_two_handed_axe),
             (val_div, ":item_value", 2),
           (else_try),
             (eq, ":player_troop_class", multi_troop_class_spearman),
             (this_or_next|eq, ":item_class", multi_item_class_type_spear),
             (eq, ":item_class", multi_item_class_type_large_shield),
             (val_div, ":item_value", 2),
           (else_try),
             (eq, ":player_troop_class", multi_troop_class_cavalry),
             (this_or_next|eq, ":item_class", multi_item_class_type_lance),
             (this_or_next|eq, ":item_class", multi_item_class_type_sword),
             (eq, ":item_class", multi_item_class_type_horse),
             (val_div, ":item_value", 2),
           (else_try),
             (eq, ":player_troop_class", multi_troop_class_archer),
             (this_or_next|eq, ":item_class", multi_item_class_type_bow),
             (eq, ":item_class", multi_item_class_type_arrow),
             (val_div, ":item_value", 2),
           (else_try),
             (eq, ":player_troop_class", multi_troop_class_crossbowman),
             (this_or_next|eq, ":item_class", multi_item_class_type_crossbow),
             (eq, ":item_class", multi_item_class_type_bolt),
             (val_div, ":item_value", 2),
           (else_try),
             (eq, ":player_troop_class", multi_troop_class_mounted_archer),
             (this_or_next|eq, ":item_class", multi_item_class_type_bow),
             (this_or_next|eq, ":item_class", multi_item_class_type_arrow),
             (eq, ":item_class", multi_item_class_type_horse),
             (val_div, ":item_value", 2),
           (else_try),
             (eq, ":player_troop_class", multi_troop_class_mounted_crossbowman),
             (this_or_next|eq, ":item_class", multi_item_class_type_crossbow),
             (this_or_next|eq, ":item_class", multi_item_class_type_bolt),
             (eq, ":item_class", multi_item_class_type_horse),
             (val_div, ":item_value", 2),
           (try_end),
   
           (try_begin),
             (gt, ":item_value", ":max_cost_value"),
             (assign, ":max_cost_value", ":item_value"),
             (assign, ":max_cost_value_index", ":i_item"),
           (try_end),
         (try_end),

         #max_cost_value and max_cost_value_index will definitely be valid
         #unless no items are left (therefore some items must cost 0 gold)
         (player_get_slot, ":item_id", ":player_no", ":max_cost_value_index"),
         (call_script, "script_multiplayer_get_previous_item_for_item_and_troop", ":item_id", ":player_troop"),
         (assign, ":item_id", reg0),
         (player_set_slot, ":player_no", ":max_cost_value_index", ":item_id"),
       (else_try),
         (assign, ":end_cond", 0),
         (val_sub, ":player_gold", ":total_cost"),
         (player_set_gold, ":player_no", ":player_gold", multi_max_gold_that_can_be_stored),
         (try_for_range, ":i_item", slot_player_cur_selected_item_indices_begin, slot_player_cur_selected_item_indices_end),
           (player_get_slot, ":item_id", ":player_no", ":i_item"),
           #checking if different class default item replace is needed for weapons
           (try_begin),
             (ge, ":item_id", 0),
             #then do nothing
           (else_try),
             (store_sub, ":base_index_slot", ":i_item", slot_player_cur_selected_item_indices_begin),
             (store_add, ":selected_item_index_slot", ":base_index_slot", slot_player_selected_item_indices_begin),
             (player_get_slot, ":selected_item_index", ":player_no", ":selected_item_index_slot"),
             (this_or_next|eq, ":selected_item_index", -1),
             (player_item_slot_is_picked_up, ":player_no", ":base_index_slot"),
             #then do nothing
           (else_try),
             #an item class without a default value is -1, then find a default weapon
             (item_get_slot, ":item_class", ":selected_item_index", slot_item_multiplayer_item_class),
             (is_between, ":item_class", multi_item_class_type_weapons_begin, multi_item_class_type_weapons_end),
             (assign, ":dc_replaced_item", -1),
             (try_for_range, ":i_dc_item_class", multi_item_class_type_melee_weapons_begin, multi_item_class_type_melee_weapons_end),
               (lt, ":dc_replaced_item", 0),
               (assign, ":dc_item_class_used", 0),
               (try_for_range, ":i_dc_item", slot_player_cur_selected_item_indices_begin, slot_player_cur_selected_item_indices_end),
                 (player_get_slot, ":dc_cur_item", ":player_no", ":i_dc_item"),
                 (ge, ":dc_cur_item", 0),
                 (item_get_slot, ":dc_item_class", ":dc_cur_item", slot_item_multiplayer_item_class),
                 (eq, ":dc_item_class", ":i_dc_item_class"),
                 (assign, ":dc_item_class_used", 1),
               (try_end),
               (eq, ":dc_item_class_used", 0),
               (assign, ":dc_end_cond", all_items_end),
               (try_for_range, ":i_dc_new_item", all_items_begin, ":dc_end_cond"),
                 (item_slot_eq, ":i_dc_new_item", slot_item_multiplayer_item_class, ":i_dc_item_class"),
                 (call_script, "script_cf_multiplayer_is_item_default_for_troop", ":i_dc_new_item", ":player_troop"),
                 (assign, ":dc_end_cond", 0), #break
                 (assign, ":dc_replaced_item", ":i_dc_new_item"),
               (try_end),
             (try_end),
             (ge, ":dc_replaced_item", 0),
             (player_set_slot, ":player_no", ":i_item", ":dc_replaced_item"),
             (assign, ":item_id", ":dc_replaced_item"),
           (try_end),

           #finally, add the item to agent
           (try_begin),
             (ge, ":item_id", 0), #might be -1 for horses etc.
             (store_sub, ":item_slot", ":i_item", slot_player_cur_selected_item_indices_begin),
             (player_add_spawn_item, ":player_no", ":item_slot", ":item_id"),
             (try_begin),
               (eq, ":item_slot", ek_body), #ek_body is the slot for armor
               (assign, ":armor_bought", 1),
             (try_end),
           (try_end),
         (try_end),

         (player_set_slot, ":player_no", slot_player_total_equipment_value, ":total_cost"),     
       (try_end),
     (try_end),
     (try_begin),
       (eq, ":armor_bought", 0),
       (eq, "$g_multiplayer_force_default_armor", 1),
       (assign, ":end_cond", all_items_end),
       (try_for_range, ":i_new_item", all_items_begin, ":end_cond"),
         (this_or_next|item_slot_eq, ":i_new_item", slot_item_multiplayer_item_class, multi_item_class_type_light_armor),
         (this_or_next|item_slot_eq, ":i_new_item", slot_item_multiplayer_item_class, multi_item_class_type_medium_armor),
         (item_slot_eq, ":i_new_item", slot_item_multiplayer_item_class, multi_item_class_type_heavy_armor),
         (call_script, "script_cf_multiplayer_is_item_default_for_troop", ":i_new_item", ":player_troop"),
         (assign, ":end_cond", 0), #break
         (player_add_spawn_item, ":player_no", ek_body, ":i_new_item"), #ek_body is the slot for armor
       (try_end),
     (try_end),
     ]),
  
  
# NE skill changed values in party_get_ideal_size

  # 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"),

      #default limit is 30 for any party
      # (assign, ":limit", 30),
	  (assign, ":limit", 70),
      (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"),

        #default limit is 10 for kingdom lords
        # (assign, ":limit", 10),
        (assign, ":limit", 30),

        #each (leadership level) gives 5 to limit
        (store_skill_level, ":skill", "skl_leadership", ":party_leader"),
        (store_attribute_level, ":charisma", ":party_leader", ca_charisma),
		# NE skill
        #(val_mul, ":skill", 5),
		(val_mul, ":skill", 10),
		# NE end skill
        (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", 100),
		  (val_add, ":limit", 200),
        (try_end),
		
		# NE dk
		(try_begin),
          (eq, ":faction_id", "fac_dark_knights"),
          (val_add, ":limit", 100),
        (try_end),
		# NE End dk

        (try_begin),
          (faction_slot_eq, ":faction_id", slot_faction_marshall, ":party_leader"),
          (val_add, ":limit", 20),
        (try_end),        

        (try_for_range, ":cur_center", castles_begin, castles_end),
          (party_slot_eq, ":cur_center", slot_town_lord, ":party_leader"),
          (val_add, ":limit", 20),
        (try_end),        
      (try_end),

      #if player has level of 0 then ideal limit will be exactly same, if player has level of 80 then ideal limit will be multiplied by 2 ((80 + 80) / 80)
      #below code will increase limits a little as the game progresses and player gains level
      (store_character_level, ":level", "trp_player"),
      (val_min, ":level", 80),
       (store_add, ":level_factor", 80, ":level"),
       (val_mul, ":limit", ":level_factor"),
      (val_div, ":limit", 80), 
       (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"),
	  # NE skill
      #(store_mul, ":limit", ":skill", 5),
	  (store_mul, ":limit", ":skill", 10),
	  # NE end skill
      (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)), arg3 = item_modifier
  # 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),
      (store_script_param, ":item_modifier", 3),
      (try_begin),
        (is_presentation_active, "prsnt_equipment_overview"),
        (call_script, "script_get_item_prerequisites", ":item_no", ":item_modifier"),
        (gt, reg0, 0), # Item has some prerequisite
        (try_begin),
          (eq, reg0, 1), # Strength prerequisite
          (try_begin),
            (eq, ":extra_text_id", 0),
            (set_result_string, "@Requires strength: {reg2}"),
            (store_attribute_level, reg3, "trp_player", ca_strength),
            (try_begin),
              (ge, reg3, reg2),
              (set_trigger_result, 0x00FF00),
            (else_try),
              (set_trigger_result, 0xFF0000),
            (try_end),
          (else_try),
            (eq, ":extra_text_id", 1),
            (gt, "$g_lco_heroes", 0),
            (store_add, ":offset", "$g_lco_heroes", "$g_lco_active_hero"), # Slot ID where hero reference is stored
            (troop_get_slot, ":troop_id", lco_storage, ":offset"), # We got hero troop ID, now checking equipment
            (store_attribute_level, reg3, ":troop_id", ca_strength),
            (str_store_troop_name, s62, ":troop_id"),
            (set_result_string, "@{s62}'s strength: {reg3}"),
            (try_begin),
              (ge, reg3, reg2),
              (set_trigger_result, 0x00FF00),
            (else_try),
              (set_trigger_result, 0xFF0000),
            (try_end),
          (try_end),
        (else_try),
          (try_begin),
            (eq, reg1, "skl_riding"),
            (str_store_string, s61, "@Riding"),
          (else_try),
            (eq, reg1, "skl_shield"),
            (str_store_string, s61, "@Shield"),
          (else_try),
            (eq, reg1, "skl_power_throw"),
            (str_store_string, s61, "@Power Throw"),
          (else_try),
            (eq, reg1, "skl_power_draw"),
            (str_store_string, s61, "@Power Draw"),
          (else_try),
            (str_store_string, s61, "@Skill #{reg1}"),
          (try_end),
          (try_begin),
            (eq, ":extra_text_id", 0),
            (set_result_string, "@Requires {s61}: {reg2}"),
            (store_skill_level, reg3, reg1, "trp_player"),
            (try_begin),
              (ge, reg3, reg2),
              (set_trigger_result, 0x00FF00),
            (else_try),
              (set_trigger_result, 0xFF0000),
            (try_end),
          (else_try),
            (eq, ":extra_text_id", 1),
            (gt, "$g_lco_heroes", 0),
            (store_add, ":offset", "$g_lco_heroes", "$g_lco_active_hero"), # Slot ID where hero reference is stored
            (troop_get_slot, ":troop_id", lco_storage, ":offset"), # We got hero troop ID, now checking equipment
            (store_skill_level, reg3, reg1, ":troop_id"),
            (str_store_troop_name, s62, ":troop_id"),
            (set_result_string, "@{s62}'s {s61}: {reg3}"),
            (try_begin),
              (ge, reg3, reg2),
              (set_trigger_result, 0x00FF00),
            (else_try),
              (set_trigger_result, 0xFF0000),
            (try_end),
          (try_end),
        (try_end),
      (else_try),
        (is_between, ":item_no", food_begin, food_end),
        (try_begin),
          (eq, ":extra_text_id", 0),
          (assign, ":continue", 1),
          (try_begin),
            (this_or_next|eq, ":item_no", "itm_cattle_meat"),
            (this_or_next|eq, ":item_no", "itm_pork"),
				(eq, ":item_no", "itm_chicken"),
				
            (eq, ":item_modifier", imod_rotten),
            (assign, ":continue", 0),
          (try_end),
          (eq, ":continue", 1),
          (item_get_slot, ":food_bonus", ":item_no", slot_item_food_bonus),
########################################################################################################################
# LAV MODIFICATIONS START (TRADE GOODS MOD)
########################################################################################################################
          (try_begin),
            (eq, ":item_modifier", imod_fine),
            (val_add, ":food_bonus", 1),
          (else_try),
            (eq, ":item_modifier", imod_well_made),
            (val_add, ":food_bonus", 2),
          (else_try),
            (eq, ":item_modifier", imod_lordly),
            (val_add, ":food_bonus", 5),
          (else_try),
            (eq, ":item_modifier", imod_exquisite),
            (val_add, ":food_bonus", 6),
          (try_end),
########################################################################################################################
# LAV MODIFICATIONS END (TRADE GOODS MOD)
########################################################################################################################

          (assign, reg1, ":food_bonus"),
          (set_result_string, "@+{reg1} to party morale"),
          (set_trigger_result, 0x4444FF),
        (try_end),
      (else_try),
        (is_between, ":item_no", readable_books_begin, readable_books_end),
        (try_begin),
          (eq, ":extra_text_id", 0),
          (item_get_slot, reg1, ":item_no", slot_item_intelligence_requirement),
          (set_result_string, "@Requires {reg1} intelligence to read"),
          (set_trigger_result, 0xFFEEDD),
        (else_try),
          (eq, ":extra_text_id", 1),
          (item_get_slot, ":progress", ":item_no", slot_item_book_reading_progress),
          (val_div, ":progress", 10),
          (assign, reg1, ":progress"),
          (set_result_string, "@Reading Progress: {reg1}%"),
          (set_trigger_result, 0xFFEEDD),
        (try_end),
      (else_try),
        (is_between, ":item_no", reference_books_begin, reference_books_end),
        (try_begin),
          (eq, ":extra_text_id", 0),
          (try_begin),
            (eq, ":item_no", "itm_book_wound_treatment_reference"),
            (str_store_string, s1, "@wound treament"),
          (else_try),
            (eq, ":item_no", "itm_book_training_reference"),
            (str_store_string, s1, "@trainer"),
          (else_try),
            (eq, ":item_no", "itm_book_surgery_reference"),
            (str_store_string, s1, "@surgery"),
          (try_end),
          (set_result_string, "@+1 to {s1} while in inventory"),
          (set_trigger_result, 0xFFEEDD),
        (try_end),
		
		# NE food
# v585 Josef whiskey modifiers		
	   (else_try),
          (eq, ":item_no", "itm_whiskey"),
		  (eq, ":extra_text_id", 0),
          (str_store_string, s1, "@path finding & spotting"),
          (set_result_string, "@-3 to {s1}, +30 to morale"),
          (set_trigger_result, 0x4444FF),		
		
		
		
		
		
      (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", active_npcs_begin, active_npcs_end),
       (context_menu_add_item, "@View notes", 2),
     (try_end),
    
     (try_begin),
       (neq, ":party_no", "p_main_party"),       
       (store_faction_of_party, ":party_faction", ":party_no"),
                     
       (this_or_next|eq, ":party_faction", "$players_kingdom"),
       (this_or_next|eq, ":party_faction", "fac_player_supporters_faction"),
       (party_slot_eq, ":party_no", slot_party_type, spt_kingdom_caravan),
       
       (neg|is_between, ":party_no", centers_begin, centers_end),
       
       (context_menu_add_item, "@Accompany", cmenu_follow), 
     (try_end),
         
     #(context_menu_add_item, "@Debug party", 3),
  ]),

  #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"),
    (else_try),
      (eq, ":button_value", 3),
      (assign, reg1, ":party_no"),
      (str_store_party_name, s1, reg1),
      (get_party_ai_behavior, reg2, reg1),
      (get_party_ai_object, reg3, reg1),
      (get_party_ai_current_behavior, reg4, reg1),
      (get_party_ai_current_object, reg5, reg1),
      (try_begin),
        (party_is_active, reg3),
        (str_store_party_name, s3, reg3),
      (else_try),
        (str_store_string, s3, "@no_party"),
      (try_end),
      (try_begin),
        (party_is_active, reg5),
        (str_store_party_name, s5, reg5),
      (else_try),
        (str_store_string, s5, "@no_party"),
      (try_end),
      (display_message, "@Party {s1} (reg1): behavior {reg2} @ {s3} {reg3}, current behavior {reg4} @ {s5} {reg5}.", 0xFF0000),
    (try_end),
  ]),

  #script_game_get_skill_modifier_for_troop
  # This script is called from the game engine when a skill's modifiers are needed
  # INPUT: arg1 = troop_no, arg2 = skill_no
  # OUTPUT: trigger_result = modifier_value
  ("game_get_skill_modifier_for_troop",
   [(store_script_param, ":troop_no", 1),
    (store_script_param, ":skill_no", 2),
    (assign, ":modifier_value", 0),
    (try_begin),
      (eq, ":skill_no", "skl_wound_treatment"),
      #(call_script, "script_get_troop_item_amount", ":troop_no", "itm_book_wound_treatment_reference"),
      #(gt, reg0, 0),
      (store_item_kind_count, ":item_count", "itm_book_wound_treatment_reference", ":troop_no"),
      (gt, ":item_count", 0),
      (val_add, ":modifier_value", 1),
    (else_try),
      (eq, ":skill_no", "skl_trainer"),
      # NE 600 Series: Apply -4 skill check penalty to the trainer skill when in brutality mode
      (try_begin),
        (eq,"$setting_brutality_mode", 1),
        (val_sub, ":modifier_value", 4),
      (try_end),
      #(call_script, "script_get_troop_item_amount", ":troop_no", "itm_book_training_reference"),
      #(gt, reg0, 0),
      (store_item_kind_count, ":item_count", "itm_book_training_reference", ":troop_no"),
      (gt, ":item_count", 0),
      (val_add, ":modifier_value", 1),
    (else_try),   
      (eq, ":skill_no", "skl_surgery"),
       # NE 600 Series: Disable the surgery skill with a -20 modifier when in brutality mode
      (try_begin),
        (eq,"$setting_brutality_mode", 1),
        (assign, ":modifier_value", -20),
      (else_try),
        #(call_script, "script_get_troop_item_amount", ":troop_no", "itm_book_surgery_reference"),
        #(gt, reg0, 0),
        (store_item_kind_count, ":item_count", "itm_book_surgery_reference", ":troop_no"),
        (gt, ":item_count", 0),
        (val_add, ":modifier_value", 1),
      (try_end),
    # NE food
	# v585 Josef whiskey	  
	(else_try),
      (this_or_next|eq, ":skill_no", "skl_pathfinding"),
      (eq, ":skill_no", "skl_spotting"),
      #(call_script, "script_get_troop_item_amount", ":troop_no", "itm_whiskey"),
      #(gt, reg0, 0),
      (store_item_kind_count, ":item_count", "itm_whiskey", ":troop_no"),
      (gt, ":item_count", 0),
      (val_add, ":modifier_value", -3),	  
    (try_end),
    # ne end food
    (set_trigger_result, ":modifier_value"),
    (try_begin),
      (eq, "$cheat_mode", 1),
      (assign, reg65, ":modifier_value"),
    (try_end),
    ]),

# Note to modders: Uncomment these if you'd like to use the following.
  
##  #script_game_check_party_sees_party
##  # This script is called from the game engine when a party is inside the range of another party
##  # INPUT: arg1 = party_no_seer, arg2 = party_no_seen
##  # OUTPUT: trigger_result = true or false (1 = true, 0 = false)
##  ("game_check_party_sees_party",
##   [
##     (store_script_param, ":party_no_seer", 1),
##     (store_script_param, ":party_no_seen", 2),
##     (set_trigger_result, 1),
##    ]),
##
##  #script_game_get_party_speed_multiplier
##  # This script is called from the game engine when a skill's modifiers are needed
##  # INPUT: arg1 = party_no
##  # OUTPUT: trigger_result = multiplier (scaled by 100, meaning that giving 100 as the trigger result does not change the party speed)
##  ("game_get_party_speed_multiplier",
##   [
##     (store_script_param, ":party_no", 1),
##     (set_trigger_result, 100),
##    ]),
  

  # script_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"),
      (assign,":wage", 0),
      (try_begin),
        (troop_is_hero, ":troop_id"),
      (else_try),
        (store_character_level, ":wage", ":troop_id"),
        (val_mul, ":wage", ":wage"),
        (val_add, ":wage", 50),
        (val_div, ":wage", 30),
        (troop_is_mounted, ":troop_id"),
        (val_mul, ":wage", 5),
        (val_div, ":wage", 4),
      (try_end),
      (assign, reg0, ":wage"),
  ]),

  #script_setup_talk_info
  # INPUT: $g_talk_troop, $g_talk_troop_relation
  ("setup_talk_info",
    [
      (talk_info_set_relation_bar, "$g_talk_troop_relation"),
      (str_store_troop_name, s61, "$g_talk_troop"),
      (str_store_string, s61, "@{!} {s61}"),
      (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),
  ]),

#NPC companion changes begin
  #script_setup_talk_info_companions
  ("setup_talk_info_companions",
    [
      (call_script, "script_npc_morale", "$g_talk_troop"),
      (assign, ":troop_morale", reg0),

      (talk_info_set_relation_bar, ":troop_morale"),

      (str_store_troop_name, s61, "$g_talk_troop"),
      (str_store_string, s61, "@{!} {s61}"),
      (assign, reg1, ":troop_morale"),
      (str_store_string, s62, "str_morale_reg1"),
      (talk_info_set_line, 0, s61),
      (talk_info_set_line, 1, s62),
      (talk_info_set_line, 3, s63),
  ]),
#NPC companion changes end

  #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", 3),
      (val_add, ":upper_limit", 25),
      (val_min, ":upper_limit", 100),
      (set_party_creation_random_limits, 0, ":upper_limit"),
      (assign, reg0, ":upper_limit"),
  ]),

  #script_set_trade_route_between_centers
  # INPUT:
  # param1: center_no_1
  # param1: center_no_2
  ("set_trade_route_between_centers",
    [(store_script_param, ":center_no_1", 1),
     (store_script_param, ":center_no_2", 2),
     (assign, ":center_1_added", 0),
     (assign, ":center_2_added", 0),
     (try_for_range, ":cur_slot", slot_town_trade_routes_begin, slot_town_trade_routes_end),
       (try_begin),
         (eq, ":center_1_added", 0),
         (party_slot_eq, ":center_no_1", ":cur_slot", 0),
         (party_set_slot, ":center_no_1", ":cur_slot", ":center_no_2"),
         (assign, ":center_1_added", 1),
       (try_end),
       (try_begin),
         (eq, ":center_2_added", 0),
         (party_slot_eq, ":center_no_2", ":cur_slot", 0),
         (party_set_slot, ":center_no_2", ":cur_slot", ":center_no_1"),
         (assign, ":center_2_added", 1),
       (try_end),
     (try_end),
     (try_begin),
       (eq, ":center_1_added", 0),
       (str_store_party_name, s1, ":center_no_1"),
       (display_message, "@{!}DEBUG -- ERROR: More than 15 trade routes are given for {s1}."),
     (try_end),
     (try_begin),
       (eq, ":center_2_added", 0),
       (str_store_party_name, s1, ":center_no_2"),
       (display_message, "@{!}DEBUG -- ERROR: More than 15 trade routes are given for {s1}."),
     (try_end),
     ]),

  #script_center_change_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)
  # param4: randomness (between 0-100)
  ("center_change_trade_good_production",
    [
      (store_script_param, ":center_no", 1),
      (store_script_param, ":item_no", 2),
      (store_script_param, ":production_rate", 3),
#      (val_mul, ":production_rate", 5),
      (store_script_param, ":randomness", 4),
      (store_random_in_range, ":random_num", 0, ":randomness"),
      (store_random_in_range, ":random_sign", 0, 2),
      (try_begin),
        (eq, ":random_sign", 0),
        (val_add, ":production_rate", ":random_num"),
      (else_try),
        (val_sub, ":production_rate", ":random_num"),
      (try_end),
      (val_sub, ":item_no", trade_goods_begin),
      (val_add, ":item_no", slot_town_trade_good_productions_begin),

      (party_get_slot, ":old_production_rate", ":center_no", ":item_no"),
      (val_add, ":production_rate", ":old_production_rate"),
      (party_set_slot, ":center_no", ":item_no", ":production_rate"),
  ]),

  ("average_trade_good_prices", #Called from start
    [
	
	#This should be done by route rather than distance
      (store_sub, ":item_to_slot", slot_town_trade_good_prices_begin, trade_goods_begin),

      (try_for_range, ":center_no", towns_begin, towns_end),
        
		
        (try_for_range, ":other_center", centers_begin, centers_end),
          (this_or_next|is_between, ":other_center", towns_begin, towns_end),
			(is_between, ":other_center", villages_begin, villages_end),

		  (this_or_next|party_slot_eq, ":other_center", slot_village_market_town, ":center_no"),
		  (this_or_next|party_slot_eq, ":center_no", slot_town_trade_route_1, ":other_center"),
		  (this_or_next|party_slot_eq, ":center_no", slot_town_trade_route_2, ":other_center"),
		  (this_or_next|party_slot_eq, ":center_no", slot_town_trade_route_3, ":other_center"),
		  (this_or_next|party_slot_eq, ":center_no", slot_town_trade_route_4, ":other_center"),
		  (this_or_next|party_slot_eq, ":center_no", slot_town_trade_route_5, ":other_center"),
		  (this_or_next|party_slot_eq, ":center_no", slot_town_trade_route_6, ":other_center"),
		  (this_or_next|party_slot_eq, ":center_no", slot_town_trade_route_7, ":other_center"),
		  (this_or_next|party_slot_eq, ":center_no", slot_town_trade_route_8, ":other_center"),
		  (this_or_next|party_slot_eq, ":center_no", slot_town_trade_route_9, ":other_center"),
		  (this_or_next|party_slot_eq, ":center_no", slot_town_trade_route_10, ":other_center"),
		  (this_or_next|party_slot_eq, ":center_no", slot_town_trade_route_11, ":other_center"),
		  (this_or_next|party_slot_eq, ":center_no", slot_town_trade_route_12, ":other_center"),
		  (this_or_next|party_slot_eq, ":center_no", slot_town_trade_route_13, ":other_center"),
		  (this_or_next|party_slot_eq, ":center_no", slot_town_trade_route_14, ":other_center"),
			(party_slot_eq, ":center_no", slot_town_trade_route_15, ":other_center"),

#          (neq, ":other_center", ":center_no"),
#          (store_distance_to_party_from_party, ":cur_distance", ":center_no", ":other_center"),
#          (lt, ":cur_distance", 50), #Reduced from 110
#          (store_sub, ":dist_factor", 50, ":cur_distance"),
		  
          (try_for_range, ":cur_good", trade_goods_begin, trade_goods_end),
            (store_add, ":cur_good_slot", ":cur_good", ":item_to_slot"),
            (party_get_slot, ":center_price", ":center_no", ":cur_good_slot"),
            (party_get_slot, ":other_center_price", ":other_center", ":cur_good_slot"),
            (store_sub, ":price_dif", ":center_price", ":other_center_price"),
			
			(store_div, ":price_dif_change", ":price_dif", 5), #this is done twice, reduced from 4
#            (assign, ":price_dif_change", ":price_dif"),

#            (val_mul ,":price_dif_change", ":dist_factor"),
#            (val_div ,":price_dif_change", 500), #Maximum of 1/10 per center
            (val_add, ":other_center_price", ":price_dif_change"),
            (party_set_slot, ":other_center", ":cur_good_slot", ":other_center_price"),
			
            (val_sub, ":center_price", ":price_dif_change"),
            (party_set_slot, ":center_no", ":cur_good_slot", ":center_price"),
			
          (try_end),
        (try_end),
      (try_end),
  ]),


  
  #script_average_trade_good_productions
  # INPUT: none (called only from game start?)
  #This is currently deprecated, as I was going to try to fine-tune production
  ("average_trade_good_productions",
    [
      (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", towns_begin, towns_end),
        (this_or_next|is_between, ":center_no", towns_begin, towns_end),
        (is_between, ":center_no", villages_begin, villages_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", 110),
          (store_sub, ":dist_factor", 110, ":cur_distance"),
          (try_for_range, ":cur_good", trade_goods_begin, trade_goods_end),
            (store_add, ":cur_good_slot", ":cur_good", ":item_to_slot"),
            (party_get_slot, ":center_production", ":center_no", ":cur_good_slot"),
            (party_get_slot, ":other_center_production", ":other_center", ":cur_good_slot"),
            (store_sub, ":prod_dif", ":center_production", ":other_center_production"),
            (gt, ":prod_dif", 0),
            (store_mul, ":prod_dif_change", ":prod_dif", 1),
##            (try_begin),
##              (is_between, ":center_no", towns_begin, towns_end),
##              (is_between, ":other_center", towns_begin, towns_end),
##              (val_mul, ":cur_distance", 2),
##            (try_end),
            (val_mul ,":prod_dif_change", ":dist_factor"),
            (val_div ,":prod_dif_change", 110),
            (val_add, ":other_center_production", ":prod_dif_change"),
            (party_set_slot, ":other_center", ":cur_good_slot", ":other_center_production"),
          (try_end),
        (try_end),
      (try_end),
  ]),
  
  #script_normalize_trade_good_productions 
  #Adjusts productions according to the amount of the item produced
  # INPUT: none
  # This currently deprecated, as I was going to try to fine-tune productions
  ("normalize_trade_good_productions",
    [
      (store_sub, ":item_to_slot", slot_town_trade_good_productions_begin, trade_goods_begin),
      (try_for_range, ":cur_good", trade_goods_begin, trade_goods_end),
        (assign, ":total_production", 0),
        (assign, ":num_centers", 0),
        (store_add, ":cur_good_slot", ":cur_good", ":item_to_slot"),
        (try_for_range, ":center_no", centers_begin, centers_end),
          (val_add, ":num_centers", 1),
          (try_begin),
            (is_between, ":center_no", towns_begin, towns_end), #each town is weighted as 5 villages...
            (val_add, ":num_centers", 4), 
          (try_end),
          (party_get_slot, ":center_production", ":center_no", ":cur_good_slot"),
          (val_add, ":total_production", ":center_production"),
        (try_end),
        (store_div, ":new_production_difference", ":total_production", ":num_centers"),
        (neq, ":new_production_difference", 0),
        (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),
          (party_get_slot, ":center_production", ":center_no", ":cur_good_slot"),
          (val_sub, ":center_production", ":new_production_difference"),
          (party_set_slot, ":center_no", ":cur_good_slot", ":center_production"),
        (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
  #Called once every 72 hours
  ("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_price_slot", ":cur_good", trade_goods_begin),
        (val_add, ":cur_good_price_slot", slot_town_trade_good_prices_begin),
		(party_get_slot, ":cur_price", ":center_no", ":cur_good_price_slot"),
		
        (call_script, "script_center_get_production", ":center_no", ":cur_good"),
		(assign, ":production", reg0),
		
        (call_script, "script_center_get_consumption", ":center_no", ":cur_good"),
		(assign, ":consumption", reg0),
		(val_sub, ":production", ":consumption"),
		
		#Change averages production x 4 for excess demand
        (try_begin),
		  #supply is greater than demand
          (gt, ":production", 0), 
		  (store_mul, ":change_factor", ":production", 8), #price will be decreased by his factor
		  (store_random_in_range, ":random_change", 0, ":change_factor"),
		  (try_begin), #Excess of supply decelerates over time, as low price reduces output
			(lt, ":cur_price", 900),
			(val_mul, ":random_change", ":cur_price"),
			(val_div, ":random_change", 900),
		  (try_end),
          (val_sub, ":cur_price", ":random_change"),
        (else_try),
          (lt, ":production", 0), 
		  (store_sub, ":change_factor", 0, ":production"), #price will be increased by his factor
		  (val_mul, ":change_factor", 8),
		  (store_random_in_range, ":random_change", 0, ":change_factor"),
          (val_add, ":cur_price", ":random_change"),
        (try_end),
	
		
        #Move price towards average by 3%...
		#Equilibrium is 33 cycles, or 100 days
		#Change per cycle is Production x 4
		#Thus, max differential = -5 x 4 x 33 = -660 for -5
        (store_sub, ":price_difference", ":cur_price", average_price_factor),
        (val_mul, ":price_difference", 97),
        (val_div, ":price_difference", 100),
        (store_add, ":new_price", average_price_factor, ":price_difference"),
		
		#Price of manufactured goods drift towards primary raw material 
		(try_begin),
			(item_get_slot, ":raw_material", ":cur_good", slot_item_primary_raw_material),
            (neq, ":raw_material", 0),
	        (store_sub, ":raw_material_price_slot", ":raw_material", trade_goods_begin),
	        (val_add, ":raw_material_price_slot", slot_town_trade_good_prices_begin),
			(party_get_slot, ":raw_material_price", ":center_no", ":raw_material_price_slot"),
			(gt, ":raw_material_price", ":new_price"),
			(store_sub, ":raw_material_boost", ":raw_material_price", ":new_price"),
			(val_div, ":raw_material_boost", 10),
			(val_add, ":new_price", ":raw_material_boost"),
		(try_end),
		
        (val_clamp, ":new_price", minimum_price_factor, maximum_price_factor),
        (party_set_slot, ":center_no", ":cur_good_price_slot", ":new_price"),
      (try_end),
  ]),
  
  ("center_get_production",
    [
	#Actually, this could be reset somewhat to yield supply and demand as raw numbers
	#Demand could be set values for rural and urban
	#Supply could be based on capital goods -- head of cattle, head of sheep, fish ponds, fishing fleets, acres of grain fields, olive orchards, olive presses, wine presses, mills, smithies, salt pans, potters' kilns, etc
	#Prosperity would increase both demand and supply
		(store_script_param_1, ":center_no"),
		(store_script_param_2, ":cur_good"),
  
		(assign, ":base_production", 0),
		
		#Grain products
		(try_begin),
			(eq, ":cur_good", "itm_bread"), #Demand = 3000 across Calradia
			(party_get_slot, ":base_production", ":center_no", slot_center_mills),
			(val_mul, ":base_production", 20), #one mills per village, five mills per town = 160 mills 
		(else_try),
			(eq, ":cur_good", "itm_grain"), #Demand =  3200+, 1600 to mills, 1500 on its own, extra to breweries
			(party_get_slot, ":base_production", ":center_no", slot_center_acres_grain),
			(val_div, ":base_production", 125), #10000 acres is the average across Calradia, extra in Swadia, less in snows and steppes, a bit from towns 
		(else_try),
			(eq, ":cur_good", "itm_ale"), #
			(party_get_slot, ":base_production", ":center_no", slot_center_breweries),
			(val_mul, ":base_production", 35), 
# NE Food
# I know this makes no bloody sense but I want hard tack to be scarce as meat
		(else_try),
			(eq, ":cur_good", "itm_hardtack"),
			(party_get_slot, ":base_production", ":center_no", slot_center_mills),
			(val_mul, ":base_production", 5),
# Ne end food
		(else_try),
			(eq, ":cur_good", "itm_smoked_fish"), #Demand = 20
			(party_get_slot, ":base_production", ":center_no", slot_center_fishing_fleet),
			(val_mul, ":base_production", 4), #was originally 5
		(else_try),
			(eq, ":cur_good", "itm_salt"), 
			(party_get_slot, ":base_production", ":center_no", slot_center_salt_pans),
			(val_mul, ":base_production", 35),

		#Cattle products	
		(else_try),
			(eq, ":cur_good", "itm_cattle_meat"), #Demand = 5
			(party_get_slot, ":base_production", ":center_no", slot_center_head_cattle),
			(val_div, ":base_production", 9),
		(else_try),
			(eq, ":cur_good", "itm_dried_meat"), #Demand = 15
			(party_get_slot, ":base_production", ":center_no", slot_center_head_cattle),
                        (party_get_slot, ":sheep_addition", ":center_no", slot_center_head_sheep),
                        (val_div, ":sheep_addition", 2),
                        (val_add, ":base_production", ":sheep_addition"),
                        (party_get_slot, ":gardens", ":center_no", slot_center_household_gardens),
                        (val_mul, ":base_production", ":gardens"),
                        (val_div, ":base_production", 10), 
		(else_try),
			(eq, ":cur_good", "itm_cheese"), 	 #Demand = 10
			(party_get_slot, ":base_production", ":center_no", slot_center_head_cattle),
			(val_div, ":base_production", 4),
		(else_try),
			(eq, ":cur_good", "itm_butter"), 	 #Demand = 2
			(party_get_slot, ":base_production", ":center_no", slot_center_head_cattle),
                        (party_get_slot, ":gardens", ":center_no", slot_center_household_gardens),
                        (val_mul, ":base_production", ":gardens"),
                        (val_div, ":base_production", 15),
		(else_try),
			(eq, ":cur_good", "itm_raw_leather"), 	 #Demand = ??
			(party_get_slot, ":base_production", ":center_no", slot_center_head_cattle),
			(val_div, ":base_production", 6),
			(party_get_slot, ":sheep_addition", ":center_no", slot_center_head_sheep),
			(val_div, ":sheep_addition", 12),
			(val_add, ":base_production", ":sheep_addition"),
			
		(else_try),
			(eq, ":cur_good", "itm_leatherwork"), 	 #Demand = ??
			(party_get_slot, ":base_production", ":center_no", slot_center_tanneries),
			(val_mul, ":base_production", 20),
			

		(else_try),
			(eq, ":cur_good", "itm_honey"), 	 #Demand = 5
			(party_get_slot, ":base_production", ":center_no", slot_center_apiaries),
			(val_mul, ":base_production", 6),
		(else_try),
			(eq, ":cur_good", "itm_cabbages"), 	 #Demand = 7
			(is_between, ":center_no", villages_begin, villages_end),
			(assign, ":base_production", 8),
		(else_try),
			(eq, ":cur_good", "itm_apples"), 	 #Demand = 7
			(is_between, ":center_no", villages_begin, villages_end),
			(assign, ":base_production", 5),


# Ne end food			
		#Sheep products	
		(else_try),
			(eq, ":cur_good", "itm_sausages"), 	 #Demand = 5
			(party_get_slot, ":base_production", ":center_no", slot_center_head_sheep), #average of 90 sheep
			(val_div, ":base_production", 15),
		(else_try),
			(eq, ":cur_good", "itm_wool"), 	 #(Demand = 0, but 15 averaged out perhaps)
			(party_get_slot, ":base_production", ":center_no", slot_center_head_sheep), #average of 90 sheep
			(val_div, ":base_production", 5),
		(else_try),
			(eq, ":cur_good", "itm_wool_cloth"), 	 #(Demand = 1500 across Calradia)
			(party_get_slot, ":base_production", ":center_no", slot_center_wool_looms),
			(val_mul, ":base_production", 5), #300 across Calradia
		
		(else_try),
			(eq, ":cur_good", "itm_iron"), 	 #Demand = 5, one supplies three smithies
			(party_get_slot, ":base_production", ":center_no", slot_center_iron_deposits),
			(val_mul, ":base_production", 10),
		(else_try),
			(eq, ":cur_good", "itm_tools"), 	 #Demand = 560 across Calradia
			(party_get_slot, ":base_production", ":center_no", slot_center_smithies),
			(val_mul, ":base_production", 3),

		#Other artisanal goods	
		(else_try),
			(eq, ":cur_good", "itm_pottery"), #560 is total demand	 
			(party_get_slot, ":base_production", ":center_no", slot_center_pottery_kilns),
			(val_mul, ":base_production", 2),

		(else_try),
			(eq, ":cur_good", "itm_raw_grapes"), 	 
			(party_get_slot, ":base_production", ":center_no", slot_center_acres_vineyard),
			(val_div, ":base_production", 100),
		(else_try),
			(eq, ":cur_good", "itm_wine"), 	 
			(party_get_slot, ":base_production", ":center_no", slot_center_wine_presses),
			(val_mul, ":base_production", 30),
			
			
		(else_try),
			(eq, ":cur_good", "itm_raw_olives"), 	 
			(party_get_slot, ":base_production", ":center_no", slot_center_acres_olives),
			(val_div, ":base_production", 150),
		(else_try),
			(eq, ":cur_good", "itm_oil"), 	 
			(party_get_slot, ":base_production", ":center_no", slot_center_olive_presses),
			(val_mul, ":base_production", 12),
			
		#Flax and linen	
		(else_try),
			(eq, ":cur_good", "itm_linen"), 	 
			(party_get_slot, ":base_production", ":center_no", slot_center_linen_looms),
			(val_mul, ":base_production", 5),
		(else_try),
			(eq, ":cur_good", "itm_raw_flax"), 	 
			(party_get_slot, ":base_production", ":center_no", slot_center_acres_flax),
			(val_div, ":base_production", 65),
# Ne food
		(else_try),
			(eq, ":cur_good", "itm_lumber"), 	 #Demand = 7
			(is_between, ":center_no", villages_begin, villages_end),
			(assign, ":base_production", 15),			

		(else_try),
			(eq, ":cur_good", "itm_velvet"), 	 
			(party_get_slot, ":base_production", ":center_no", slot_center_silk_looms),
			(val_mul, ":base_production", 5),
		(else_try),
			(eq, ":cur_good", "itm_raw_silk"), 	 
			(party_get_slot, ":base_production", ":center_no", slot_center_silk_farms),
			(val_div, ":base_production", 20),
		(else_try),
			(eq, ":cur_good", "itm_raw_dyes"), 	 
			(this_or_next|eq, ":center_no", "p_town_5"),
				(eq, ":center_no", "p_town_22"),
			(assign, ":base_production", 50),
                (else_try),
                        (this_or_next|eq, ":center_no", "p_village_11"), #Dusturil (village of Tulga)
                        (eq, ":center_no", "p_village_25"), #Dashbigha (village of Tulga)
                          (assign, ":base_production", 50),
                (else_try),
                        (this_or_next|eq, ":center_no", "p_village_37"), #Ada Kulun (village of Ichlamur)
                        (this_or_next|eq, ":center_no", "p_village_42"), #Dirigh Aban (village of Ichlamur)
                        (this_or_next|eq, ":center_no", "p_village_99"), #Fishara (village of Bariyye)
                        (eq, ":center_no", "p_village_100"), #Iqbayl (village of Bariyye)
                          (assign, ":base_production", 25),
		(else_try),
			(eq, ":cur_good", "itm_raw_date_fruit"), 	 
			(party_get_slot, ":base_production", ":center_no", slot_center_acres_dates),
			(val_div, ":base_production", 120),
		(else_try),
			(eq, ":cur_good", "itm_furs"), 	 #Demand = 90 across Calradia
			(party_get_slot, ":base_production", ":center_no", slot_center_fur_traps),
			(val_mul, ":base_production", 3),
		(else_try),
			(eq, ":cur_good", "itm_spice"),
			(try_begin),
				(eq, ":center_no", "p_town_10"), #Tulga
				(assign, ":base_production", 100),
			(else_try),
				(eq, ":center_no", "p_town_17"), #Ichamur
				(assign, ":base_production", 40),
			(else_try),
				(eq, ":center_no", "p_town_19"), #Shariz
				(assign, ":base_production", 30),
			(else_try),
				(eq, ":center_no", "p_town_22"), #Bariyye
				(assign, ":base_production", 30),
			(try_end),	
		(try_end),
		
		
		
		
		
		#Modify production by other goods
		(assign, ":modified_production", ":base_production"),
		(try_begin),
			(eq, ":cur_good", "itm_bread"),
			(call_script, "script_good_price_affects_good_production", ":center_no", "itm_grain", ":base_production", 1),
			(assign, ":modified_production", reg0),
		(else_try),
			(eq, ":cur_good", "itm_ale"),
			(call_script, "script_good_price_affects_good_production", ":center_no", "itm_grain", ":base_production", 2),
			(assign, ":modified_production", reg0),
		(else_try),
			(eq, ":cur_good", "itm_dried_meat"),
			(call_script, "script_good_price_affects_good_production", ":center_no", "itm_salt", ":base_production", 2),
			(assign, ":modified_production", reg0),
		(else_try),
			(eq, ":cur_good", "itm_smoked_fish"),
			(call_script, "script_good_price_affects_good_production", ":center_no", "itm_salt", ":base_production", 2),
			(assign, ":modified_production", reg0),
		(else_try),	
			(eq, ":cur_good", "itm_tools"),
			(call_script, "script_good_price_affects_good_production", ":center_no", "itm_iron", ":base_production", 1),
			(assign, ":modified_production", reg0),
		(else_try),	
			(eq, ":cur_good", "itm_wool_cloth"),
			(call_script, "script_good_price_affects_good_production", ":center_no", "itm_wool", ":base_production", 1),
			(assign, ":modified_production", reg0),
		(else_try),	
			(eq, ":cur_good", "itm_wine"),
			(call_script, "script_good_price_affects_good_production", ":center_no", "itm_raw_grapes", ":base_production", 1),
			(assign, ":modified_production", reg0),
		(else_try),	
			(eq, ":cur_good", "itm_oil"),
			(call_script, "script_good_price_affects_good_production", ":center_no", "itm_raw_olives", ":base_production", 1),
			(assign, ":modified_production", reg0),
		(else_try),	
			(eq, ":cur_good", "itm_velvet"),
			(call_script, "script_good_price_affects_good_production", ":center_no", "itm_raw_silk", ":base_production", 1),
			(assign, ":initially_modified_production", reg0),
			
			(call_script, "script_good_price_affects_good_production", ":center_no", "itm_raw_dyes", ":initially_modified_production", 2),
			(assign, ":modified_production", reg0),
		(else_try),	
			(eq, ":cur_good", "itm_leatherwork"),
			(call_script, "script_good_price_affects_good_production", ":center_no", "itm_raw_leather", ":base_production", 1),
			(assign, ":modified_production", reg0),
		(else_try),	
			(eq, ":cur_good", "itm_linen"),
			(call_script, "script_good_price_affects_good_production", ":center_no", "itm_raw_flax", ":base_production", 1),
			(assign, ":modified_production", reg0),
		(try_end),
		

		(assign, ":base_production_modded_by_raw_materials", ":modified_production"), #this is just logged for the report screen

	    #Increase both positive and negative production by the center's prosperity
		#Richer towns have more people and consume more, but also produce more 
		(try_begin),
			(party_get_slot, ":prosperity_plus_75", ":center_no", slot_town_prosperity),
			(val_add, ":prosperity_plus_75", 75),
			(val_mul, ":modified_production", ":prosperity_plus_75"),
			(val_div, ":modified_production", 125),
		(try_end),
  
		(try_begin),
		    (this_or_next|party_slot_eq, ":center_no", slot_village_state, svs_being_raided),
		        (party_slot_eq, ":center_no", slot_village_state, svs_looted),
		    (assign, ":modified_production", 0),	
		(try_end),
 
	    (assign, reg0, ":modified_production"), #modded by prosperity
	    (assign, reg1, ":base_production_modded_by_raw_materials"),
	    (assign, reg2, ":base_production"),
	  
	]),

  ("center_get_consumption",
    [
		(store_script_param_1, ":center_no"),
		(store_script_param_2, ":cur_good"),

		(assign, ":consumer_consumption", 0),
		(try_begin),
			(this_or_next|is_between, ":center_no", "p_town_19", "p_castle_1"),		
				(ge, ":center_no", "p_village_91"),
			(item_slot_ge, ":cur_good", slot_item_desert_demand, 0), #Otherwise use rural or urban
			(item_get_slot, ":consumer_consumption", ":cur_good", slot_item_desert_demand),
		(else_try),
			(is_between, ":center_no", villages_begin, villages_end),
			(item_get_slot, ":consumer_consumption", ":cur_good", slot_item_rural_demand),
		(else_try),
			(is_between, ":center_no", towns_begin, towns_end),
			(item_get_slot, ":consumer_consumption", ":cur_good", slot_item_urban_demand),
		(try_end),
		
		
		(assign, ":raw_material_consumption", 0),
		(try_begin),
			(eq, ":cur_good", "itm_grain"),
			(party_get_slot, ":grain_for_bread", ":center_no", slot_center_mills),
			(val_mul, ":grain_for_bread", 20),
			
			(party_get_slot, ":grain_for_ale", ":center_no", slot_center_breweries),
			(val_mul, ":grain_for_ale", 5),
			
			(store_add, ":raw_material_consumption", ":grain_for_bread", ":grain_for_ale"),
			
		(else_try),	
			(eq, ":cur_good", "itm_iron"),
			(party_get_slot, ":raw_material_consumption", ":center_no", slot_center_smithies),
			(val_mul, ":raw_material_consumption", 3),
			
		(else_try),	
			(eq, ":cur_good", "itm_wool"),
			(party_get_slot, ":raw_material_consumption", ":center_no", slot_center_wool_looms),
			(val_mul, ":raw_material_consumption", 5),

		(else_try),	
			(eq, ":cur_good", "itm_raw_flax"),
			(party_get_slot, ":raw_material_consumption", ":center_no", slot_center_linen_looms),
			(val_mul, ":raw_material_consumption", 5),

		(else_try),	
			(eq, ":cur_good", "itm_raw_leather"),
			(party_get_slot, ":raw_material_consumption", ":center_no", slot_center_tanneries),
			(val_mul, ":raw_material_consumption", 20),

		(else_try),	
			(eq, ":cur_good", "itm_raw_grapes"),
			(party_get_slot, ":raw_material_consumption", ":center_no", slot_center_wine_presses),
			(val_mul, ":raw_material_consumption", 30),

		(else_try),	
			(eq, ":cur_good", "itm_raw_olives"),
			(party_get_slot, ":raw_material_consumption", ":center_no", slot_center_olive_presses),
			(val_mul, ":raw_material_consumption", 12),

			
		(else_try),	
			(eq, ":cur_good", "itm_raw_dyes"),
			(party_get_slot, ":raw_material_consumption", ":center_no", slot_center_silk_looms),
			(val_mul, ":raw_material_consumption", 1),
		(else_try),	
			(eq, ":cur_good", "itm_raw_silk"),
			(party_get_slot, ":raw_material_consumption", ":center_no", slot_center_silk_looms),
			(val_mul, ":raw_material_consumption", 5),
			

		(else_try),	
			(eq, ":cur_good", "itm_salt"),
			(party_get_slot, ":salt_for_beef", ":center_no", slot_center_head_cattle),
			(val_div, ":salt_for_beef", 10),
			
			(party_get_slot, ":salt_for_fish", ":center_no", slot_center_fishing_fleet),
			(val_div, ":salt_for_fish", 5),
			
			(store_add, ":raw_material_consumption", ":salt_for_beef", ":salt_for_fish"),
		(try_end),
		
		(try_begin), #Reduce consumption of raw materials if their cost is high
			(gt, ":raw_material_consumption", 0),
			(store_sub, ":item_to_price_slot", slot_town_trade_good_prices_begin, trade_goods_begin),
	        (store_add, ":cur_good_price_slot", ":cur_good", ":item_to_price_slot"),
	        (party_get_slot, ":cur_center_price", ":center_no", ":cur_good_price_slot"),
			(gt, ":cur_center_price", 1000),
			(val_mul, ":raw_material_consumption", 1000),
			(val_div, ":raw_material_consumption", ":cur_center_price"),
		(try_end),
		
	
		
		(store_add, ":modified_consumption", ":consumer_consumption", ":raw_material_consumption"),
		(try_begin),
			(party_get_slot, ":prosperity_plus_75", ":center_no", slot_town_prosperity),
			(val_add, ":prosperity_plus_75", 75),
			(val_mul, ":modified_consumption", ":prosperity_plus_75"),
			(val_div, ":modified_consumption", 125),
		(try_end),
		

	    (assign, reg0, ":modified_consumption"), #modded by prosperity
	    (assign, reg1, ":raw_material_consumption"),
	    (assign, reg2, ":consumer_consumption"),				
	]),
  
  #script_get_enterprise_name
  # INPUT: arg1 = item_no
  # Output: reg0: production string
  ("get_enterprise_name",
    [
		(store_script_param_1, ":item_produced"),
		(assign, ":enterprise_name", "str_bread_site"),
		(try_begin),
			(eq, ":item_produced", "itm_bread"),
			(assign, ":enterprise_name", "str_bread_site"),
		(else_try),
			(eq, ":item_produced", "itm_ale"),
			(assign, ":enterprise_name", "str_ale_site"),
		(else_try),
			(eq, ":item_produced", "itm_oil"),
			(assign, ":enterprise_name", "str_oil_site"),
		(else_try),
			(eq, ":item_produced", "itm_wine"),
			(assign, ":enterprise_name", "str_wine_site"),
		(else_try),
			(eq, ":item_produced", "itm_leatherwork"),
			(assign, ":enterprise_name", "str_leather_site"),
		(else_try),
			(eq, ":item_produced", "itm_wool_cloth"),
			(assign, ":enterprise_name", "str_wool_cloth_site"),
		(else_try),
			(eq, ":item_produced", "itm_linen"),
			(assign, ":enterprise_name", "str_linen_site"),
		(else_try),
			(eq, ":item_produced", "itm_velvet"),
			(assign, ":enterprise_name", "str_velvet_site"),
		(else_try),
			(eq, ":item_produced", "itm_tools"),
			(assign, ":enterprise_name", "str_tool_site"),
		(try_end),
		(assign, reg0, ":enterprise_name"),
	]),
  
  #script_do_merchant_town_trade
  # INPUT: arg1 = party_no (of the merchant), arg2 = center_no
  ("cf_do_merchant_town_trade",
    [
      (store_script_param_1, ":party_no"),
      (store_script_param_2, ":center_no"),

	  (party_get_slot, ":origin", ":party_no", slot_party_last_traded_center),
	  
	  (try_begin),
		(eq, "$cheat_mode", 2),
		(str_store_party_name, s4, ":center_no"),
		(str_store_party_name, s5, ":origin"),
		(display_message, "@{!}DEBUG -- Caravan trades in {s4}, originally from {s5}"),
	  (try_end),
	  
	  (call_script, "script_add_log_entry", logent_party_traded, ":party_no", ":origin", ":center_no", -1),

      (call_script, "script_do_party_center_trade", ":party_no", ":center_no", price_adjustment), #change prices by 20%, also, sets party_last_traded to new
      
      (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"),

      #Adding tariffs to the town
      (party_get_slot, ":accumulated_tariffs", ":center_no", slot_center_accumulated_tariffs),
      (party_get_slot, ":prosperity", ":center_no", slot_town_prosperity),
	  
	  (assign, ":tariffs_generated", ":total_change"),
      (val_mul, ":tariffs_generated", ":prosperity"),
	  (val_div, ":tariffs_generated", 100),
	  (val_div, ":tariffs_generated", 10), #10 for caravans, 20 for villages
	  (val_add, ":accumulated_tariffs", ":tariffs_generated"),
	  
	  (try_begin),
		(ge, "$cheat_mode", 3),
		(assign, reg4, ":tariffs_generated"),
		(str_store_party_name, s4, ":center_no"),
		(assign, reg5, ":accumulated_tariffs"),
		(display_message, "@{!}New tariffs at {s4} = {reg4}, total = {reg5}"),
	  (try_end),
	  
      (party_set_slot, ":center_no", slot_center_accumulated_tariffs, ":accumulated_tariffs"),
	  
      #Adding 1 to center prosperity in many circumstances
      (try_begin),
        (store_random_in_range, ":rand", 0, 80),
        (call_script, "script_center_get_goods_availability", ":center_no"),
        (assign, ":hardship_index", reg0),
        (gt, ":rand", ":hardship_index"),
        (call_script, "script_change_center_prosperity", ":center_no", 1),
        (val_add, "$newglob_total_prosperity_from_caravan_trade", 1),
        (store_random_in_range, ":rand", 0, 100),
        (gt, ":rand", 82),
        (call_script, "script_change_center_prosperity", ":center_no", 1),
        (val_add, "$newglob_total_prosperity_from_caravan_trade", 1),
      (try_end),
      #Repeat, but harder
      (try_begin),
        (store_random_in_range, ":rand", -20, 40),
        (call_script, "script_center_get_goods_availability", ":center_no"),
		(assign, ":hardship_index", reg0),
		(gt, ":rand", ":hardship_index"),
		
        (call_script, "script_change_center_prosperity", ":center_no", 1),
		(val_add, "$newglob_total_prosperity_from_caravan_trade", 1),
      (try_end),
      
  ]),
  
  #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, arg2 = exclude leader
  # OUTPUT: reg0 = strength
  
  ("party_calculate_strength",
    [
      (store_script_param_1, ":party"), #Party_id
      (store_script_param_2, ":exclude_leader"), #Party_id
      
      (assign, reg0,0),
      (party_get_num_companion_stacks, ":num_stacks", ":party"),
      (assign, ":first_stack", 0),
      (try_begin),
        (neq, ":exclude_leader", 0),
        (assign, ":first_stack", 1),
      (try_end),
      (try_for_range, ":i_stack", ":first_stack", ":num_stacks"),
        (party_stack_get_troop_id, ":stack_troop",":party", ":i_stack"),
        (store_character_level, ":stack_strength", ":stack_troop"),
        (val_add, ":stack_strength", 4), #new was 12 (patch 1.125)
        (val_mul, ":stack_strength", ":stack_strength"),
        (val_mul, ":stack_strength", 2), #new (patch 1.125)
        (val_div, ":stack_strength", 100),
        (val_max, ":stack_strength", 1), #new (patch 1.125)
        (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),
          (troop_is_wounded, ":stack_troop"), #hero & wounded
          (assign, ":stack_strength", 0),
        (try_end),
        (val_add, reg0, ":stack_strength"),
      (try_end),
      (party_set_slot, ":party", slot_party_cached_strength, reg0),
  ]),


  #script_loot_player_items:
  # INPUT: arg1 = enemy_party_no
  # Output: none
  ("loot_player_items",
    [
      (store_script_param, ":enemy_party_no", 1),
      
      (troop_get_inventory_capacity, ":inv_cap", "trp_player"),
      (try_for_range, ":i_slot", 0, ":inv_cap"),
        (troop_get_inventory_slot, ":item_id", "trp_player", ":i_slot"),
        (ge, ":item_id", 0),
        (troop_get_inventory_slot_modifier, ":item_modifier", "trp_player", ":i_slot"),
        (try_begin),
          (is_between, ":item_id", trade_goods_begin, trade_goods_end),
          (assign, ":randomness", 20),
        (else_try),
          (this_or_next|is_between, ":item_id", horses_begin, horses_end),
          (this_or_next|eq, ":item_id", "itm_warhorse_sarranid"),
          (eq, ":item_id", "itm_warhorse_steppe"),
          (assign, ":randomness", 15),
        (else_try),
          (this_or_next|is_between, ":item_id", weapons_begin, weapons_end),
          (is_between, ":item_id", ranged_weapons_begin, ranged_weapons_end),
          (assign, ":randomness", 5),
        (else_try),
          (this_or_next|is_between, ":item_id", armors_begin, armors_end),
		  (this_or_next|eq, ":item_id", "itm_plate_boots"), #added to the end because of not breaking the save games
          (is_between, ":item_id", shields_begin, shields_end),
          (assign, ":randomness", 5),
        (try_end),
        (store_random_in_range, ":random_no", 0, 100),
        (lt, ":random_no", ":randomness"),
        (troop_remove_item, "trp_player", ":item_id"),

        (try_begin),
          (gt, ":enemy_party_no", 0),
          (party_get_slot, ":cur_loot_slot", ":enemy_party_no", slot_party_next_looted_item_slot),
          (val_add, ":cur_loot_slot", slot_party_looted_item_1),
          (party_set_slot, ":enemy_party_no", ":cur_loot_slot", ":item_id"),
          (val_sub, ":cur_loot_slot", slot_party_looted_item_1),
          (val_add, ":cur_loot_slot", slot_party_looted_item_1_modifier),
          (party_set_slot, ":enemy_party_no", ":cur_loot_slot", ":item_modifier"),
          (val_sub, ":cur_loot_slot", slot_party_looted_item_1_modifier),
          (val_add, ":cur_loot_slot", 1),
          (val_mod, ":cur_loot_slot", num_party_loot_slots),
          (party_set_slot, ":enemy_party_no", slot_party_next_looted_item_slot, ":cur_loot_slot"),
        (try_end),
      (try_end),
      (store_troop_gold, ":cur_gold", "trp_player"),
      (store_div, ":max_lost", ":cur_gold", 5),
      (store_div, ":min_lost", ":cur_gold", 10),
      (store_random_in_range, ":lost_gold", ":min_lost", ":max_lost"),
      (troop_remove_gold, "trp_player", ":lost_gold"),
	  # NE finances
	  (val_mul,":lost_gold",-1),
      (call_script, "script_adjust_finances", slot_finance_lost_in_combat, ":lost_gold"),
	  # NE end finances
      ]),

  
  #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
            
      (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_probability", 100),
      #(val_mul, ":loot_probability", 10),
      #(val_div, ":loot_probability", ":num_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),
      
      (assign, ":num_looted_items",0),
      (try_begin),
        (this_or_next|party_slot_eq, "$g_enemy_party", slot_party_type, spt_kingdom_caravan),
        (this_or_next|party_slot_eq, "$g_enemy_party", slot_party_type, spt_bandit_lair),
        (party_slot_eq, "$g_enemy_party", slot_party_type, spt_village_farmer),
        (store_mul, ":plunder_amount", player_loot_share, 30),
        (val_mul, ":plunder_amount", "$g_strength_contribution_of_player"),
        (val_div, ":plunder_amount", 100),
        (val_div, ":plunder_amount", ":num_player_party_shares"),
        (try_begin),
          (party_slot_eq, "$g_enemy_party", slot_party_type, spt_kingdom_caravan),
          (reset_item_probabilities, 100),
          (assign, ":range_min", trade_goods_begin),
          (assign, ":range_max", trade_goods_end),
        (else_try),
          (party_slot_eq, "$g_enemy_party", slot_party_type, spt_bandit_lair),
          (val_div, ":plunder_amount", 2),
          (reset_item_probabilities, 1),
          (assign, ":range_min", food_begin),
          (assign, ":range_max", food_end),
        (else_try),
          (val_div, ":plunder_amount", 5),
          (reset_item_probabilities, 1),
          (assign, ":range_min", food_begin),
          (assign, ":range_max", food_end),
        (try_end),
        (store_sub, ":item_to_price_slot", slot_town_trade_good_prices_begin, trade_goods_begin),
        (try_for_range, ":cur_goods", ":range_min", ":range_max"),
          (try_begin),
            (neg|party_slot_eq, "$g_enemy_party", slot_party_type, spt_bandit_lair),
            (store_add, ":cur_price_slot", ":cur_goods", ":item_to_price_slot"),
            (party_get_slot, ":cur_price", "$g_enemy_party", ":cur_price_slot"),                    
          (else_try),
            (assign, ":cur_price", maximum_price_factor),
            (val_add, ":cur_price", average_price_factor),
            (val_div, ":cur_price", 3),
          (try_end),  
                    
          (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"),
          (assign, reg0, ":cur_probability"),
          (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),
 # NE loot
## Start game setting check
      (try_begin),
        (eq,"$setting_use_new_loot_system",0),  
 # Ne end 
      #Now loot the defeated party
      (store_mul, ":loot_probability", player_loot_share, 3),
      (val_mul, ":loot_probability", "$g_strength_contribution_of_player"),
      (party_get_skill_level, ":player_party_looting", "p_main_party", "skl_looting"),
      (val_add, ":player_party_looting", 10),
      (val_mul, ":loot_probability", ":player_party_looting"),
      (val_div, ":loot_probability", 10),
      (val_div, ":loot_probability", ":num_player_party_shares"),

	  ## NE
	  ## Loot Lords before troops begin - Jinnai
      (party_get_num_companion_stacks, ":num_stacks",":enemy_party"),
      (assign,":lord_probability",":loot_probability"),
      (val_mul, ":lord_probability", 2),

      (try_for_range, ":i_stack", 0, ":num_stacks"),
        (party_stack_get_troop_id,     ":stack_troop",":enemy_party",":i_stack"),
        (troop_is_hero, ":stack_troop"),
        (troop_loot_troop,"trp_temp_troop",":stack_troop",":lord_probability"),
      (try_end),

     ## Loot Lords before troops end
	 # NE End

      (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_probability"),
        (try_end),
      (try_end),
	 (else_try),
	 # NE
## Looting rewrite begin (old code deleted rather than commented out) - Jinnai

	  
      #Now loot the defeated party
      (assign, ":loot_probability", 25),
#      (party_get_skill_level, ":player_party_looting", "p_main_party", "skl_looting"),
      (store_skill_level, ":player_party_looting", "skl_looting", "trp_player"),
      (try_begin),
        (ge,":player_party_looting",6),
        (assign,":loottimes",3),
      (else_try),
        (assign,":loottimes",2),
      (try_end),
      (val_mul, ":player_party_looting", 5),
      (val_add, ":loot_probability", ":player_party_looting"),
      (val_mul, ":player_party_looting", 2),
      (val_div, ":player_party_looting", 5), # Set up for modifier bit
      (val_div, ":num_player_party_shares", 10),
      (val_sub, ":loot_probability", ":num_player_party_shares"),
      (val_mul, ":loot_probability", "$g_strength_contribution_of_player"),
      (val_div, ":loot_probability", 100),

      (party_get_num_companion_stacks, ":num_stacks",":enemy_party"),
      (troop_get_inventory_capacity, ":maxitems", "trp_temp_troop"),
      (val_sub,":maxitems",1),

      (try_for_range, ":i_stack", 0, ":num_stacks"),
        (party_stack_get_troop_id,     ":stack_troop",":enemy_party",":i_stack"),
        (troop_sort_inventory, ":stack_troop"),
        (troop_get_inventory_capacity, ":inv_cap", ":stack_troop"),
        (assign, ":numitems", 0),
        (try_for_range, ":i_slot", 0, ":inv_cap"),
          (troop_get_inventory_slot, ":item_id", ":stack_troop", ":i_slot"),
          (ge, ":item_id", 0),
          (val_add,":numitems",1),
        (try_end),
        (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_probability"),
          (try_for_range, ":looting", 0, ":loottimes"),
            (assign,":continue",1),
            (try_begin),
              (troop_is_hero,":stack_troop"), # Only loot heroes once
              (gt,":looting",0),
              (assign,":continue",0),
            (try_end),
            (eq,":continue",1),
            (store_random_in_range,":rand",1,101),
            (try_begin),
              (le,":rand",":loot_probability"),
              (store_random_in_range,":rand",0,":numitems"),
              (troop_get_inventory_slot,":item_id",":stack_troop",":rand"),
              (ge, ":item_id", 0), # This shouldn't matter, but just in case...
              (neq, ":item_id", "itm_larktin_black_armor"), #Add all items that should never be lootable by the player here
              (neq, ":item_id", "itm_larktin_charger"),
              (neq, ":item_id", "itm_larktin_gauntlets"),
              (neq, ":item_id", "itm_larktin_black_greaves"),
              (neq, ":item_id", "itm_larktin_shield"),
              (item_get_type, ":item_type", ":item_id"),
              (assign, ":item_modifier",0), # Default to no modifier
              (store_random_in_range,":rand",1,51),
              (val_add,":rand",":player_party_looting"),
              (try_begin),
                (eq,":item_type",itp_type_horse),
                (try_begin),
                  (lt,":rand",20),
                  (assign, ":item_modifier",imod_lame),
                (else_try),
                  (lt,":rand",35),
                  (assign, ":item_modifier",imod_swaybacked),
                (else_try),
                  (gt,":rand",67),
                  (assign, ":item_modifier",imod_heavy),
                (else_try),
                  (gt,":rand",64),
                  (assign, ":item_modifier",imod_spirited),
                (else_try),
                  (gt,":rand",56),
                  (assign, ":item_modifier",imod_stubborn),
                (try_end),
              (else_try),
                (this_or_next|eq,":item_type",itp_type_one_handed_wpn),
                (eq,":item_type",itp_type_two_handed_wpn),
                (store_item_value, ":value", ":item_id"),
                (val_mod,":value",10),
                (try_begin),
                  (eq,":value",5), # Non-swords and non-polearms have a value ending in 5
                  (try_begin),
                    (lt,":rand",20),
                    (assign, ":item_modifier",imod_rusty),
                  (else_try),
                    (lt,":rand",35),
                    (assign, ":item_modifier",imod_chipped),
                  (else_try),
                    (gt,":rand",67),
                    (assign, ":item_modifier",imod_masterwork),
                  (else_try),
                    (gt,":rand",64),
                    (assign, ":item_modifier",imod_balanced),
                  (else_try),
                    (gt,":rand",56),
                    (assign, ":item_modifier",imod_heavy),
                  (try_end),
                (else_try),
                  (try_begin),
                    (lt,":rand",20),
                    (assign, ":item_modifier",imod_rusty),
                  (else_try),
                    (lt,":rand",35),
                    (assign, ":item_modifier",imod_chipped),
                  (else_try),
                    (gt,":rand",67),
                    (assign, ":item_modifier",imod_masterwork),
                  (else_try),
                    (gt,":rand",64),
                    (assign, ":item_modifier",imod_balanced),
                  (else_try),
                    (gt,":rand",56),
                    (assign, ":item_modifier",imod_tempered),
                  (try_end),
                (try_end),
              (else_try),
                (eq,":item_type",itp_type_polearm),
                (try_begin),
                  (lt,":rand",20),
                  (assign, ":item_modifier",imod_cracked),
                (else_try),
                  (lt,":rand",35),
                  (assign, ":item_modifier",imod_bent),
                (else_try),
                  (gt,":rand",56),
                  (assign, ":item_modifier",imod_balanced),
                (try_end),
              (else_try),
                (this_or_next|eq,":item_type",itp_type_arrows),
                (eq,":item_type",itp_type_bolts),
                (try_begin),
                  (lt,":rand",35),
                  (assign, ":item_modifier",imod_bent),
                (else_try),
                  (gt,":rand",56),
                  (assign, ":item_modifier",imod_large_bag),
                (try_end),
              (else_try),
                (eq,":item_type",itp_type_shield),
                (try_begin),
                  (lt,":rand",20),
                  (assign, ":item_modifier",imod_cracked),
                (else_try),
                  (lt,":rand",35),
                  (assign, ":item_modifier",imod_battered),
                (else_try),
                  (gt,":rand",63),
                  (assign, ":item_modifier",imod_reinforced),
                (else_try),
                  (gt,":rand",56),
                  (assign, ":item_modifier",imod_thick),
                (try_end),
              (else_try),
                (eq,":item_type",itp_type_bow),
                (try_begin),
                  (lt,":rand",20),
                  (assign, ":item_modifier",imod_cracked),
                (else_try),
                  (lt,":rand",35),
                  (assign, ":item_modifier",imod_bent),
                (else_try),
                  (gt,":rand",63),
                  (assign, ":item_modifier",imod_masterwork),
                (else_try),
                  (gt,":rand",56),
                  (assign, ":item_modifier",imod_strong),
                (try_end),
              (else_try),
                (eq,":item_type",itp_type_crossbow),
                (try_begin),
                  (lt,":rand",20),
                  (assign, ":item_modifier",imod_cracked),
                (else_try),
                  (lt,":rand",35),
                  (assign, ":item_modifier",imod_bent),
                (else_try),
                  (gt,":rand",63),
                  (assign, ":item_modifier",imod_masterwork),
                (else_try),
                  (gt,":rand",56),
                  (assign, ":item_modifier",0),
                (try_end),
              (else_try),
                (eq,":item_type",itp_type_thrown),
                (try_begin),
                  (lt,":rand",35),
                  (assign, ":item_modifier",imod_bent),
                (else_try),
                  (gt,":rand",67),
                  (assign, ":item_modifier",imod_balanced),
                (else_try),
                  (gt,":rand",64),
                  (assign, ":item_modifier",imod_heavy),
                (else_try),
                  (gt,":rand",56),
                  (assign, ":item_modifier",imod_large_bag),
                (try_end),
              (else_try),
                (this_or_next|eq,":item_type",itp_type_head_armor),
                (this_or_next|eq,":item_type",itp_type_body_armor),
                (this_or_next|eq,":item_type",itp_type_foot_armor),
                (eq,":item_type",itp_type_hand_armor),
                (store_item_value, ":value", ":item_id"),
                (val_mod,":value",10),
                (try_begin),
                  (eq,":value",5), # Non-cloth armor ends in a value of 5
                  (try_begin),
                    (lt,":rand",15),
                    (assign, ":item_modifier",imod_rusty),
                  (else_try),
                    (lt,":rand",25),
                    (assign, ":item_modifier",imod_battered),
                  (else_try),
                    (lt,":rand",35),
                    (assign, ":item_modifier",imod_crude),
                  (else_try),
                    (gt,":rand",63),
                    (assign, ":item_modifier",imod_reinforced),
                  (else_try),
                    (gt,":rand",56),
                    (assign, ":item_modifier",imod_thick),
                  (try_end),
                (else_try),
                  (try_begin),
                    (lt,":rand",20),
                    (assign, ":item_modifier",imod_tattered),
                  (else_try),
                    (lt,":rand",35),
                    (assign, ":item_modifier",imod_ragged),
                  (else_try),
                    (gt,":rand",67),
                    (assign, ":item_modifier",imod_hardened),
                  (else_try),
                    (gt,":rand",64),
                    (assign, ":item_modifier",imod_thick),
                  (else_try),
                    (gt,":rand",56),
                    (assign, ":item_modifier",imod_sturdy),
                  (try_end),
                (try_end),
              (try_end),
              (troop_sort_inventory, "trp_temp_troop"),
              (troop_add_item,"trp_temp_troop",":item_id",":item_modifier"),
            (try_end),
          (try_end),
        (try_end),
      (try_end),

## Looting rewrite end
# NE end loot

      #(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"),
      #  (is_between, ":item_id", horses_begin, horses_end),
      #  (troop_set_inventory_slot, "trp_temp_troop", ":i_slot", -1),
      #(try_end),

      (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),

      (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", player_loot_share),
      # 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", hero_loot_share),
        (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, ":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
                  
      (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", player_loot_share),
      (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"),
          (call_script, "script_troop_add_gold", ":stack_troop", ":player_gold_gain"),
		 # NE finances
		 (try_begin),
            (eq,":stack_troop","trp_player"),
            (call_script, "script_adjust_finances", slot_finance_from_battles, ":player_gold_gain"),
          (try_end),
		 # NE end finances
        (try_end),
      (try_end),
  ]),
  
  
  #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"),
      (call_script, "script_get_meeting_scene"), 
      (assign, ":meeting_scene", reg0),
      (modify_visitors_at_site,":meeting_scene"),
      (reset_visitors),
      (set_visitor,0,"trp_player"),
	  (try_begin),
		(gt, ":troop_dna", -1),
        (set_visitor,17,":meeting_troop",":troop_dna"),
	  (else_try),
        (set_visitor,17,":meeting_troop"),
	  (try_end),	
      (set_jump_mission,"mt_conversation_encounter"),
      (jump_to_scene,":meeting_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"),
      (try_begin),
        (lt, "$g_encountered_party_relation", 0), #hostile
#        (call_script, "script_music_set_situation_with_culture", mtf_sit_encounter_hostile),
      (try_end),
      (call_script, "script_get_meeting_scene"), (assign, ":meeting_scene", reg0),
      (modify_visitors_at_site,":meeting_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,":meeting_scene"),
      (change_screen_map_conversation, ":meeting_troop"),
  ]),
  
  #script_get_meeting_scene:
  # INPUT: none
  # OUTPUT: reg0 contain suitable scene_no
  
  ("get_meeting_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_meeting_scene_steppe"),
      (else_try),
        (eq, ":terrain_type", rt_plain),
        (assign, ":scene_to_use", "scn_meeting_scene_plain"),
      (else_try),
        (eq, ":terrain_type", rt_snow),
        (assign, ":scene_to_use", "scn_meeting_scene_snow"),
      (else_try),
        (eq, ":terrain_type", rt_desert),
        (assign, ":scene_to_use", "scn_meeting_scene_desert"),
      (else_try),
        (eq, ":terrain_type", rt_steppe_forest),
        (assign, ":scene_to_use", "scn_meeting_scene_steppe"),
      (else_try),
        (eq, ":terrain_type", rt_forest),
        (assign, ":scene_to_use", "scn_meeting_scene_plain"),
      (else_try),
        (eq, ":terrain_type", rt_snow_forest),
        (assign, ":scene_to_use", "scn_meeting_scene_snow"),
      (else_try),
        (eq, ":terrain_type", rt_desert_forest),
        (assign, ":scene_to_use", "scn_meeting_scene_desert"),
      (else_try),
        (assign, ":scene_to_use", "scn_meeting_scene_plain"),
      (try_end),
      (assign, reg0, ":scene_to_use"),
  ]),

  
  #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"),
       
        (party_stack_get_size, ":stack_size", ":party", ":stack_no"),
        
        (try_begin),
          (troop_is_hero, ":stack_troop"),
          (neg|is_between, ":stack_troop", pretenders_begin, pretenders_end),
          (neq, ":stack_troop", "trp_player"),
          (eq, "$g_prison_heroes", 1),
          (eq, ":party", "p_main_party"),
          (store_random_in_range, ":succeed_escaping", 0, 2),
          (neq, ":succeed_escaping", 0), #50% chance companion stays with us.
          (troop_set_health, ":stack_troop", 100), #heal before leaving
          (store_faction_of_party, ":enemy_faction", "$g_enemy_party"),
          (assign, ":minimum_distance", 99999),
          (assign, ":prison_center", -1),
          (try_for_range, ":center", walled_centers_begin, walled_centers_end),
            (store_faction_of_party, ":center_faction", ":center"),
            (eq, ":center_faction", ":enemy_faction"),
            (store_distance_to_party_from_party, ":dist", ":center", "p_main_party"),
            (lt, ":dist", ":minimum_distance"),
            (assign, ":minimum_distance", ":dist"),
            (assign, ":prison_center", ":center"),
          (try_end),          
          (assign, reg1, ":prison_center"),
          #(display_message, "@{!}DEBUG : prison center is {reg1}"),
          (try_begin),
            (ge, ":prison_center", 0),
            (store_random_in_range, ":succeed_escaping", 0, 4),
            (neq, ":succeed_escaping", 0), #25% chance companion escapes to a tavern.
            (party_add_prisoners, ":prison_center", ":stack_troop", ":stack_size"),          
            (troop_set_slot, ":stack_troop", slot_troop_prisoner_of_party, ":prison_center"),
            (troop_set_slot, ":stack_troop", slot_troop_playerparty_history, pp_history_scattered),          
            (troop_set_slot, ":stack_troop", slot_troop_turned_down_twice, 0),
            (troop_set_slot, ":stack_troop", slot_troop_occupation, 0),                                    
            (party_remove_members, ":party", ":stack_troop", ":stack_size"),
            (try_begin),
              (eq, "$cheat_mode", 1),
              (str_store_party_name, s1, ":prison_center"),
              (display_message, "str_your_hero_prisoned_at_s1"),
            (try_end),
          (else_try),
            #bandits or deserters won and captured companion. So place it randomly in a town's tavern.
            (assign, ":end_condition", 1000),
            (try_for_range, ":unused", 0, ":end_condition"),
              (store_random_in_range, ":town_no", towns_begin, towns_end),
              (neg|troop_slot_eq, ":stack_troop", slot_troop_home, ":town_no"),
              (neg|troop_slot_eq, ":stack_troop", slot_troop_first_encountered, ":town_no"),
              (assign, ":end_condition", -1),
            (try_end),  
            (troop_set_slot, ":stack_troop", slot_troop_cur_center, ":town_no"),
            (troop_set_slot, ":stack_troop", slot_troop_playerparty_history, pp_history_scattered),
            (troop_set_slot, ":stack_troop", slot_troop_turned_down_twice, 0),
            (troop_set_slot, ":stack_troop", slot_troop_occupation, 0),
            (party_remove_members, ":party", ":stack_troop", ":stack_size"),
            (try_begin),
              (eq, "$cheat_mode", 1),
              (str_store_troop_name, 4, ":stack_troop"),
              (str_store_party_name, 5, ":town_no"),
              (display_message, "@{!}{s4} is sent to {s5} after defeat"),
            (try_end),
          (try_end),
        (else_try),        
          (this_or_next|neg|troop_is_hero, ":stack_troop"),
          (eq, "$g_move_heroes", 1),
          (party_remove_members, ":party", ":stack_troop", ":stack_size"),
        (try_end),
      (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_party_add_wounded_members_as_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_wounded_members_as_prisoners",
    [
      (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_num_wounded, ":num_wounded", ":source_party", ":stack_no"),
        (ge, ":num_wounded", 1),
        (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_prisoner_stack_get_size, ":stack_size",":source_party",":stack_no"),
        (party_add_prisoners, ":target_party", ":stack_troop", ":num_wounded"),
      (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_companion_stacks, ":num_companion_stacks", ":party_no"),
      (try_begin),
        (gt, ":num_companion_stacks", 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_change_party_morale:
  # INPUT: party_no, morale_gained
  # OUTPUT: none

  ("change_party_morale",
   [
      (store_script_param_1, ":party_no"),
      (store_script_param_2, ":morale_dif"),

      (party_get_morale, ":cur_morale", ":party_no"),
      (store_add, ":new_morale", ":cur_morale", ":morale_dif"),
      (val_clamp, ":new_morale", 0, 100),
      (party_set_morale, ":party_no", ":new_morale"),
      (str_store_party_name, s1, ":party_no"),
      
      (try_begin),
        (lt, ":new_morale", ":cur_morale"),
        (store_sub, reg1, ":cur_morale", ":new_morale"),
      (else_try),
        (gt, ":new_morale", ":cur_morale"),
        (store_sub, reg1, ":new_morale", ":cur_morale"),        
      (try_end),
  ]),

  #script_count_casualties_and_adjust_morale:
  # INPUT: none
  # OUTPUT: none

  ("count_casualties_and_adjust_morale",
   [             
    (call_script, "script_calculate_main_party_shares"),
    (assign, ":num_player_party_shares", reg0),
    
    (assign, ":our_loss_score", 0),
    (party_get_num_companion_stacks, ":num_stacks","p_player_casualties"),
    (try_for_range, ":i_stack", 0, ":num_stacks"),
      (party_stack_get_troop_id, ":stack_troop", "p_player_casualties", ":i_stack"),
      (party_stack_get_size, ":stack_size", "p_player_casualties", ":i_stack"),
      
      (party_stack_get_num_wounded, ":num_wounded", "p_player_casualties", ":i_stack"),
      (store_mul, ":stack_size_mul_2", ":stack_size", 2),
      (store_sub, ":stack_size_mul_2_sub_wounded", ":num_wounded"),
      
      (store_character_level, ":level", ":stack_troop"),    
      (store_add, ":gain", ":level", 3),
      
      #if died/wounded troop is player troop then give its level +30 while calculating troop die effect on morale
      (try_begin),
        (eq, ":stack_troop", "trp_player"),
        (val_add, ":level", 75),
      (else_try),
        (troop_is_hero, ":stack_troop"),
        (val_add, ":level", 50),
      (try_end),
      
      (val_mul, ":gain", ":gain"),
      (val_div, ":gain", 10),
      (assign, reg0, ":gain"),
      (val_mul, ":gain", ":stack_size"),
      
      (try_begin),
        (neg|troop_is_hero, ":stack_troop"),
        (val_mul, ":gain", ":stack_size_mul_2_sub_wounded"),
        (val_div, ":gain", ":stack_size_mul_2"),
      (try_end),  
      
      (try_begin),
        (eq, "$cheat_mode", 1),
        (assign, reg1, ":stack_size"),
        (assign, reg2, ":gain"),
        (display_message, "str_our_per_person__reg0_num_people__reg1_total_gain__reg2"),
      (try_end),  
      (val_add, ":our_loss_score", ":gain"),
    (try_end),
    
    (assign, ":died_enemy_population", 0),
    (assign, ":enemy_loss_score", 0),
    (party_get_num_companion_stacks, ":num_stacks","p_enemy_casualties"),
    (try_for_range, ":i_stack", 0, ":num_stacks"),
      (party_stack_get_troop_id, ":stack_troop", "p_enemy_casualties", ":i_stack"),
      (party_stack_get_size, ":stack_size", "p_enemy_casualties", ":i_stack"),

      (party_stack_get_num_wounded, ":num_wounded", "p_enemy_casualties", ":i_stack"),
      (store_mul, ":stack_size_mul_2", ":stack_size", 2),
      (store_sub, ":stack_size_mul_2_sub_wounded", ":stack_size_mul_2", ":num_wounded"),

      (store_character_level, ":level", ":stack_troop"),      
      (store_add, ":gain", ":level", 3),

      #if troop is hero give extra +15 level while calculating troop die effect on morale 
      (try_begin),
        (troop_is_hero, ":stack_troop"),
        (val_add, ":level", 50),
      (try_end),

      (val_mul, ":gain", ":gain"),
      (val_div, ":gain", 10),      
      (assign, reg0, ":gain"),
      (val_mul, ":gain", ":stack_size"),
      
      (try_begin),
        (neg|troop_is_hero, ":stack_troop"),
        (val_mul, ":gain", ":stack_size_mul_2_sub_wounded"),
        (val_div, ":gain", ":stack_size_mul_2"),
      (try_end),  

      (try_begin),
        (eq, "$cheat_mode", 1),
        (assign, reg1, ":stack_size"),
        (assign, reg2, ":gain"),
        (display_message, "str_ene_per_person__reg0_num_people__reg1_total_gain__reg2"),
      (try_end),  
      (val_add, ":enemy_loss_score", ":gain"),
      (val_add, ":died_enemy_population", ":stack_size"),
    (try_end),

    (assign, ":ally_loss_score", 0),
    (try_begin),
      (eq, "$any_allies_at_the_last_battle", 1),
      (party_get_num_companion_stacks, ":num_stacks","p_ally_casualties"),
      (try_for_range, ":i_stack", 0, ":num_stacks"),
        (party_stack_get_troop_id, ":stack_troop", "p_ally_casualties", ":i_stack"),
        (party_stack_get_size, ":stack_size", "p_ally_casualties", ":i_stack"),
        
        (party_stack_get_num_wounded, ":num_wounded", "p_ally_casualties", ":i_stack"),
        (store_mul, ":stack_size_mul_2", ":stack_size", 2),
        (store_sub, ":stack_size_mul_2_sub_wounded", ":num_wounded"),

        (store_character_level, ":level", ":stack_troop"),    
        (store_add, ":gain", ":level", 3),

        #if troop is hero give extra +15 level while calculating troop die effect on morale 
        (try_begin),
          (troop_is_hero, ":stack_troop"),
          (val_add, ":level", 50),
        (try_end),

        (val_mul, ":gain", ":gain"),
        (val_div, ":gain", 10),      
        (assign, reg0, ":gain"),
        (val_mul, ":gain", ":stack_size"),

        (try_begin),
          (neg|troop_is_hero, ":stack_troop"),
          (val_mul, ":gain", ":stack_size_mul_2_sub_wounded"),
          (val_div, ":gain", ":stack_size_mul_2"),
        (try_end),  

        (try_begin),
          (eq, "$cheat_mode", 1),
          (assign, reg1, ":stack_size"),
          (assign, reg2, ":gain"),
          (display_message, "str_all_per_person__reg0_num_people__reg1_total_gain__reg2"),
        (try_end),  
        (val_add, ":ally_loss_score", ":gain"),
      (try_end),
    (try_end),
    
    (store_add, ":our_losses", ":our_loss_score", ":ally_loss_score"), 
    (assign, ":enemy_losses", ":enemy_loss_score"),
    (val_mul, ":our_losses", 100),
    
    (try_begin), 
      (eq, "$cheat_mode", 1),
      (assign, reg0, ":enemy_losses"),
      (display_message, "@{!}DEBUGS : enemy_loses : {reg0}"),
    (try_end),  
    
    (try_begin),
      (gt, ":enemy_losses", 0),
      (store_div, ":loss_ratio", ":our_losses", ":enemy_losses"),
    (else_try),
      (assign, ":loss_ratio", 1000),
    (try_end),

    (try_begin),
      (eq, "$cheat_mode", 1),
      (assign, reg1, ":loss_ratio"),
      (display_message, "str_loss_ratio_is_reg1"),
    (try_end),
     
    (try_begin),       
      (neg|is_between, "$g_enemy_party", centers_begin, centers_end),
      (store_sub, ":total_gain", 60, ":loss_ratio"),
    (else_try),
      (store_sub, ":total_gain", 100, ":loss_ratio"),
    (try_end),    

    (try_begin),
      (lt, ":total_gain", 0),
      (val_div, ":total_gain", 2),
    (try_end),

    (try_begin), 
      (eq, "$cheat_mode", 1),
      (assign, reg0, ":total_gain"),
      (display_message, "@{!}DEBUGS1 : total_gain : {reg0}"),
    (try_end),

    (val_max, ":total_gain", -60), #total gain changes between -60(1.8+ loss ratio) and 60(0 loss ratio). We assumed average loss ratio is 0.6
    (val_mul, ":total_gain", ":enemy_losses"),
    (val_div, ":total_gain", 100),

    (store_mul, ":total_enemy_morale_gain", ":total_gain", -1), #enemies get totally negative of the morale we get
    (val_mul, ":total_gain", "$g_strength_contribution_of_player"),
    (val_div, ":total_gain", 100),

    (try_begin), 
      (eq, "$cheat_mode", 1),
      (assign, reg0, ":total_gain"),
      (display_message, "@{!}DEBUGS2 : total_gain : {reg0}"),
    (try_end),  

    (try_begin),
      (party_is_active, "$g_enemy_party"), #change enemy morale if and only if there is a valid enemy party
      
      #main enemy party    
      (assign, ":total_enemy_population", 0),        
      (val_add, ":total_enemy_population", 10), #every part effect total population by number of agents they have plus 10
      (party_get_num_companion_stacks, ":num_stacks", "$g_enemy_party"),
      (try_for_range, ":i_stack", 0, ":num_stacks"),
        (party_stack_get_troop_id, ":stack_troop", "$g_enemy_party", ":i_stack"),
        (party_stack_get_size, ":stack_size", "$g_enemy_party", ":i_stack"),
        (val_add, ":total_enemy_population", ":stack_size"),
      (try_end),
      (assign, ":main_enemy_party_population", ":total_enemy_population"),

      #enemy attachers
      (party_get_num_attached_parties, ":num_attached_parties", "$g_enemy_party"),
      (try_for_range, ":attached_party_rank", 0, ":num_attached_parties"),
        (val_add, ":total_enemy_population", 10), #every part effect total population by number of agents they have plus 10
        (party_get_attached_party_with_rank, ":attached_party", "$g_enemy_party", ":attached_party_rank"),
        (party_get_num_companion_stacks, ":num_stacks", ":attached_party"),
        (try_for_range, ":i_stack", 0, ":num_stacks"),
          (party_stack_get_troop_id, ":stack_troop", ":attached_party", ":i_stack"),
          (party_stack_get_size, ":stack_size", ":attached_party", ":i_stack"),
          (val_add, ":total_enemy_population", ":stack_size"),        
        (try_end),
      (try_end),
    
      #(assign, reg3, ":total_enemy_population"),
      #(assign, reg4, ":died_enemy_population"),
      #(store_sub, ":remaining_enemy_population", ":total_enemy_population", ":died_enemy_population"),
      #(val_add, ":remaining_enemy_population", 10),
      #(assign, reg5, ":remaining_enemy_population"),
      #(display_message, "@total : {reg3}, died : {reg4}, remaining : {reg5}"),
    
      #remaining enemy population has 10+remaining soldiers in enemy party
      (assign, ":remaining_enemy_population", ":total_enemy_population"),

      (assign, reg5, ":remaining_enemy_population"),
      (assign, reg6, ":total_enemy_morale_gain"),
    
      (set_fixed_point_multiplier, 100),
      (val_mul, ":remaining_enemy_population", 100),
      (store_sqrt, ":sqrt_remaining_enemy_population", ":remaining_enemy_population"),
      (val_div, ":sqrt_remaining_enemy_population", 100),            
      (val_div, ":total_enemy_morale_gain", ":sqrt_remaining_enemy_population"),
      (val_div, ":total_enemy_morale_gain", 4),

      (try_begin),
        (eq, "$cheat_mode", 1),
        (assign, reg7, ":total_enemy_morale_gain"),
        (display_message, "str_total_enemy_morale_gain__reg6_last_total_enemy_morale_gain__reg7_remaining_enemy_population__reg5"),
      (try_end),

      (store_mul, ":party_morale_gain", ":total_enemy_morale_gain", ":main_enemy_party_population"),
      (val_div, ":party_morale_gain", ":total_enemy_population"),
      
      (try_begin),      
        (party_is_active, "$g_enemy_party"),
        
        (call_script, "script_change_party_morale", "$g_enemy_party", ":party_morale_gain"),

        (party_get_num_attached_parties, ":num_attached_parties", "$g_enemy_party"),
        (try_for_range, ":attached_party_rank", 0, ":num_attached_parties"),
          (party_get_attached_party_with_rank, ":attached_party", "$g_enemy_party", ":attached_party_rank"),
          (party_get_num_companion_stacks, ":num_stacks", ":attached_party"),
          (assign, ":party_population", 0),
          (try_for_range, ":i_stack", 0, ":num_stacks"),
            (party_stack_get_troop_id, ":stack_troop", ":attached_party", ":i_stack"),
            (party_stack_get_size, ":stack_size", ":attached_party", ":i_stack"),
            (val_add, ":party_population", ":stack_size"),        
          (try_end),
          #(store_div, ":party_ratio", ":total_enemy_population_multiplied_by_100", ":party_population"), #party ratio changes between 0..100, shows population ratio of that party among all enemy parties
          (store_mul, ":party_morale_gain", ":total_enemy_morale_gain", ":party_population"),
          (val_div, ":party_morale_gain", ":total_enemy_population"),
          (call_script, "script_change_party_morale", ":attached_party", ":party_morale_gain"),
        (try_end),
      (try_end),  
    (try_end),
    
    #Add morale
    (assign, ":morale_gain", ":total_gain"),
    (val_div, ":morale_gain", ":num_player_party_shares"),#if there are lots of soldiers in my party there will be less morale increase.
    
    (try_begin), 
      (eq, "$cheat_mode", 1),
      (assign, reg0, ":num_player_party_shares"),
      (assign, reg1, ":total_gain"),
      (display_message, "@{!}DEBUGS3 : num_player_party_shares:{reg0}, total_gain:{reg1}"),
    (try_end),  
    
    (call_script, "script_change_player_party_morale", ":morale_gain"),
    
    (store_mul, ":killed_enemies_by_our_soldiers", ":died_enemy_population", "$g_strength_contribution_of_player"),
    (store_div, ":faction_morale_change", ":killed_enemies_by_our_soldiers", 8), #each 8 killed agent with any faction decreases morale of troops belong to that faction in our party by 1.
    (try_begin),
      (gt, ":faction_morale_change", 2000),
      (assign, ":faction_morale_change", 2000),
    (try_end),    
    
    (try_begin), #here we give positive morale to our troops of with same faction of ally party with 2/3x multipication.
      (ge, "$g_ally_party", 0),

      (store_div, ":ally_faction_morale_change", ":faction_morale_change", 3), #2/3x multipication (less than normal)
      (val_mul, ":ally_faction_morale_change", 2),
      (store_faction_of_party, ":ally_faction", "$g_ally_party"),
      (faction_get_slot, ":faction_morale", ":ally_faction",  slot_faction_morale_of_player_troops),
      (val_add, ":faction_morale", ":ally_faction_morale_change"),
      (faction_set_slot, ":ally_faction",  slot_faction_morale_of_player_troops, ":faction_morale"),
    (try_end),
    
    (try_begin), #here we give positive morale to our troops of owner of rescued village's faction after saving village from bandits by x3 bonus.
      (neg|party_is_active, "$g_enemy_party"),
      (ge, "$current_town", 0),
      
      (val_mul, ":faction_morale_change", 2), #2x bonus (more than normal)
      (store_faction_of_party, ":ally_faction", "$current_town"),
      (faction_get_slot, ":faction_morale", ":ally_faction",  slot_faction_morale_of_player_troops),
      (val_add, ":faction_morale", ":faction_morale_change"),
      (faction_set_slot, ":ally_faction",  slot_faction_morale_of_player_troops, ":faction_morale"),
    (else_try),
      (party_is_active, "$g_enemy_party"),
      (assign, ":currently_in_rebellion", 0),    
      (try_begin),
        (eq, "$players_kingdom", "fac_player_supporters_faction"),
        (neg|faction_slot_eq, "fac_player_supporters_faction", slot_faction_leader, "trp_player"),
        (assign, ":currently_in_rebellion", 1),
      (try_end),     
      (eq, ":currently_in_rebellion", 0),

      (store_div, ":faction_morale_change", ":faction_morale_change", 3), #2/3x multipication (less than normal)
      (val_mul, ":faction_morale_change", 2),
      (store_faction_of_party, ":enemy_faction", "$g_enemy_party"),
      (faction_get_slot, ":faction_morale", ":enemy_faction",  slot_faction_morale_of_player_troops),
      (val_sub, ":faction_morale", ":faction_morale_change"),
      (faction_set_slot, ":enemy_faction",  slot_faction_morale_of_player_troops, ":faction_morale"),
    (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),
     (assign, ":total_routed", 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_id", ":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"),
       #get number of routed agent numbers
       (try_begin),
         (this_or_next|eq, ":party_no", "p_main_party"),
         (eq, ":party_no", "p_player_casualties"),     
         (troop_get_slot, ":num_routed", ":stack_troop_id", slot_troop_player_routed_agents),
         (troop_set_slot, ":stack_troop_id", slot_troop_player_routed_agents, 0),
       (else_try),
         (party_get_attached_to, ":attached_to", ":party_no"),
         (this_or_next|eq, ":party_no", "p_ally_casualties"),     
         (ge, ":attached_to", 0), 
         (this_or_next|eq, ":party_no", "p_ally_casualties"),     
         (eq, ":attached_to", "p_main_party"),
         (troop_get_slot, ":num_routed", ":stack_troop_id", slot_troop_ally_routed_agents),
         (troop_set_slot, ":stack_troop_id", slot_troop_ally_routed_agents, 0),
       (else_try),
         (troop_get_slot, ":num_routed", ":stack_troop_id", slot_troop_enemy_routed_agents),
         (troop_set_slot, ":stack_troop_id", slot_troop_enemy_routed_agents, 0),
       (try_end),                
       (store_sub, ":num_killed", ":stack_size", ":num_wounded"),
       (val_sub, ":num_killed", ":num_routed"),
       (val_add, ":total_killed", ":num_killed"),
       (val_add, ":total_wounded", ":num_wounded"),
       (val_add, ":total_routed", ":num_routed"),     
       (try_begin),
         (this_or_next|gt, ":num_killed", 0),
         (this_or_next|gt, ":num_wounded", 0),
         (gt, ":num_routed", 0),     
         (store_add, reg3, ":num_killed", ":num_wounded"),
         (store_add, reg3, reg3, ":num_routed"),
         (str_store_troop_name_by_count, s1, ":stack_troop_id", reg3),
         (try_begin),
           (troop_is_hero, ":stack_troop_id"),
           (assign, reg3, 0),
         (try_end),
         (try_begin), #there are people who killed, wounded and routed.
           (gt, ":num_killed", 0),
           (gt, ":num_wounded", 0),
           (gt, ":num_routed", 0),
           (assign, reg4, ":num_killed"),
           (assign, reg5, ":num_wounded"),
           (assign, reg6, ":num_routed"),
           (str_store_string, s2, "str_reg4_killed_reg5_wounded_reg6_routed"),
         (else_try), #there are people who killed and routed.
           (gt, ":num_killed", 0),
           (gt, ":num_routed", 0),
           (assign, reg4, ":num_killed"),
           (assign, reg5, ":num_routed"),
           (str_store_string, s2, "str_reg4_killed_reg5_routed"),     
         (else_try), #there are people who killed and wounded.
           (gt, ":num_killed", 0),
           (gt, ":num_wounded", 0),
           (assign, reg4, ":num_killed"),
           (assign, reg5, ":num_wounded"),
           (str_store_string, s2, "str_reg4_killed_reg5_wounded"),     
         (else_try), #there are people who wounded and routed.
           (gt, ":num_wounded", 0),
           (gt, ":num_routed", 0),
           (assign, reg4, ":num_wounded"),
           (assign, reg5, ":num_routed"),
           (str_store_string, s2, "str_reg4_wounded_reg5_routed"),
         (else_try), #there are people who only killed.
           (gt, ":num_killed", 0),
           (assign, reg1, ":num_killed"),
           (str_store_string, s3, "@killed"),
           (str_store_string, s2, "str_reg1_blank_s3"),
         (else_try), #there are people who only wounded.
           (gt, ":num_wounded", 0),
           (assign, reg1, ":num_wounded"),
           (str_store_string, s3, "@wounded"),
           (str_store_string, s2, "str_reg1_blank_s3"),
         (else_try), #there are people who only routed.
           (assign, reg1, ":num_routed"),
           (str_store_string, s3, "str_routed"),
           (str_store_string, s2, "str_reg1_blank_s3"),
         (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),
       (this_or_next|gt, ":total_wounded", 0),
       (gt, ":total_routed", 0),
       (store_add, ":total_agents", ":total_killed", ":total_wounded"),
       (val_add, ":total_agents", ":total_routed"),
       (assign, reg3, ":total_agents"),
       (try_begin),
         (gt, ":total_killed", 0),
         (gt, ":total_wounded", 0),
         (gt, ":total_routed", 0),
         (assign, reg4, ":total_killed"),
         (assign, reg5, ":total_wounded"),
         (assign, reg6, ":total_routed"),
         (str_store_string, s2, "str_reg4_killed_reg5_wounded_reg6_routed"),
       (else_try),
         (gt, ":total_killed", 0),
         (gt, ":total_routed", 0),
         (assign, reg4, ":total_killed"),
         (assign, reg5, ":total_routed"),
         (str_store_string, s2, "str_reg4_killed_reg5_routed"),
       (else_try),
         (gt, ":total_killed", 0),
         (gt, ":total_wounded", 0),
         (assign, reg4, ":total_killed"),
         (assign, reg5, ":total_wounded"),
         (str_store_string, s2, "str_reg4_killed_reg5_wounded"),
       (else_try),
         (gt, ":total_wounded", 0),
         (gt, ":total_routed", 0),
         (assign, reg4, ":total_wounded"),
         (assign, reg5, ":total_routed"),
         (str_store_string, s2, "str_reg4_wounded_reg5_routed"),
       (else_try),
         (gt, ":total_killed", 0),
         (str_store_string, s2, "@killed"),
       (else_try),
         (gt, ":total_wounded", 0),
         (str_store_string, s2, "@wounded"),
       (else_try),
         (str_store_string, s2, "str_routed"),
       (else_try),
       (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_write_fit_party_members_to_stack_selection
  # INPUT:
  # param1: party_no, exclude_leader
  #OUTPUT:
  # trp_stack_selection_amounts slots (slot 0 = number of stacks, 1 = number of men fit, 2..n = stack sizes (fit))
  # trp_stack_selection_ids slots (2..n = stack troops)
  ("write_fit_party_members_to_stack_selection",
   [
     (store_script_param, ":party_no", 1),
     (store_script_param, ":exclude_leader", 2),
     (party_get_num_companion_stacks, ":num_stacks", ":party_no"),
     (assign, ":slot_index", 2),
     (assign, ":total_fit", 0),
     (try_for_range, ":stack_index", 0, ":num_stacks"),
       (party_stack_get_troop_id, ":stack_troop", ":party_no", ":stack_index"),
       (assign, ":num_fit", 0),
       (try_begin),
         (troop_is_hero, ":stack_troop"),
         (try_begin),
           (neg|troop_is_wounded, ":stack_troop"),
           (this_or_next|eq, ":exclude_leader", 0),
           (neq, ":stack_index", 0),
           (assign, ":num_fit",1),
         (try_end),
       (else_try),
         (party_stack_get_size, ":num_fit", ":party_no", ":stack_index"),
         (party_stack_get_num_wounded, ":num_wounded", ":party_no", ":stack_index"),
         (val_sub, ":num_fit", ":num_wounded"),
       (try_end),
       (try_begin),
         (gt, ":num_fit", 0),
         (troop_set_slot, "trp_stack_selection_amounts", ":slot_index", ":num_fit"),
         (troop_set_slot, "trp_stack_selection_ids", ":slot_index", ":stack_troop"),
         (val_add, ":slot_index", 1),
       (try_end),
       (val_add, ":total_fit", ":num_fit"),
     (try_end),
     (val_sub, ":slot_index", 2),
     (troop_set_slot, "trp_stack_selection_amounts", 0, ":slot_index"),
     (troop_set_slot, "trp_stack_selection_amounts", 1, ":total_fit"),
    ]),

  #script_remove_fit_party_member_from_stack_selection
  # INPUT:
  # param1: slot_index
  #OUTPUT:
  # reg0 = troop_no
  # trp_stack_selection_amounts slots (slot 0 = number of stacks, 1 = number of men fit, 2..n = stack sizes (fit))
  # trp_stack_selection_ids slots (2..n = stack troops)
  ("remove_fit_party_member_from_stack_selection",
   [
     (store_script_param, ":slot_index", 1),
     (val_add, ":slot_index", 2),
     (troop_get_slot, ":amount", "trp_stack_selection_amounts", ":slot_index"),
     (troop_get_slot, ":troop_no", "trp_stack_selection_ids", ":slot_index"),
     (val_sub, ":amount", 1),
     (troop_set_slot, "trp_stack_selection_amounts", ":slot_index", ":amount"),
     (troop_get_slot, ":total_amount", "trp_stack_selection_amounts", 1),
     (val_sub, ":total_amount", 1),
     (troop_set_slot, "trp_stack_selection_amounts", 1, ":total_amount"),
     (try_begin),
       (le, ":amount", 0),
       (troop_get_slot, ":num_slots", "trp_stack_selection_amounts", 0),
       (store_add, ":end_cond", ":num_slots", 2),
       (store_add, ":begin_cond", ":slot_index", 1),
       (try_for_range, ":index", ":begin_cond", ":end_cond"),
         (store_sub, ":prev_index", ":index", 1),
         (troop_get_slot, ":value", "trp_stack_selection_amounts", ":index"),
         (troop_set_slot, "trp_stack_selection_amounts", ":prev_index", ":value"),
         (troop_get_slot, ":value", "trp_stack_selection_ids", ":index"),
         (troop_set_slot, "trp_stack_selection_ids", ":prev_index", ":value"),
       (try_end),
       (val_sub, ":num_slots", 1),
       (troop_set_slot, "trp_stack_selection_amounts", 0, ":num_slots"),
     (try_end),
     (assign, reg0, ":troop_no"),
    ]),

  #script_remove_random_fit_party_member_from_stack_selection
  # INPUT:
  # none
  #OUTPUT:
  # reg0 = troop_no
  # trp_stack_selection_amounts slots (slot 0 = number of stacks, 1 = number of men fit, 2..n = stack sizes (fit))
  # trp_stack_selection_ids slots (2..n = stack troops)
  ("remove_random_fit_party_member_from_stack_selection",
   [
     (troop_get_slot, ":total_amount", "trp_stack_selection_amounts", 1),
     (store_random_in_range, ":random_troop", 0, ":total_amount"),
     (troop_get_slot, ":num_slots", "trp_stack_selection_amounts", 0),
     (store_add, ":end_cond", ":num_slots", 2),
     (try_for_range, ":index", 2, ":end_cond"),
       (troop_get_slot, ":amount", "trp_stack_selection_amounts", ":index"),
       (val_sub, ":random_troop", ":amount"),
       (lt, ":random_troop", 0),
       (assign, ":end_cond", 0),
       (store_sub, ":slot_index", ":index", 2),
     (try_end),
     (call_script, "script_remove_fit_party_member_from_stack_selection", ":slot_index"),
    ]),

  
  #script_add_routed_party
  #INPUT: none
  #OUTPUT: none
  ("add_routed_party",
   [                
     (party_get_num_companion_stacks, ":num_stacks", "p_routed_enemies"), #question, I changed (total_enemy_casualties) with (p_routed_enemies) because this is not prisoner in p_routed_enemies party.        
     (assign, ":num_regulars", 0),
     (assign, ":deleted_stacks", 0),
     (try_for_range, ":stack_no", 0, ":num_stacks"),
       (store_sub, ":difference", ":num_stacks", ":stack_no"),
       (ge, ":difference", ":deleted_stacks"),
       (store_sub, ":stack_no_minus_deleted", ":stack_no", ":deleted_stacks"),
       (party_stack_get_troop_id, ":stack_troop", "p_routed_enemies", ":stack_no_minus_deleted"), 
       (try_begin),
         (troop_is_hero, ":stack_troop"),
         (party_stack_get_size, ":stack_size", "p_routed_enemies", ":stack_no_minus_deleted"),
         (party_remove_members, "p_routed_enemies", ":stack_troop", 1),              
         (try_begin), 
           (le, ":stack_size", 1),
           (val_add, ":deleted_stacks", 1), #if deleted hero is the only one in his troop, now we have one less stacks
         (try_end),
       (else_try),
         (val_add, ":num_regulars", 1),
       (try_end),
     (try_end),

     #add new party to map if there is at least one routed agent. (new party name : routed_party, template : routed_warriors)
     (try_begin),
       (ge, ":num_regulars", 1),
     
       (set_spawn_radius, 2),
       (spawn_around_party, "p_main_party", "pt_routed_warriors"),
       (assign, ":routed_party", reg0),
     
       (party_set_slot, ":routed_party", slot_party_commander_party, -1), #we need this because 0 is player's party!

       (assign, ":max_routed_agents", 0),
       (assign, ":routed_party_faction", "fac_neutral"),
       (try_for_range, ":cur_faction", fac_kingdom_1, fac_kingdoms_end),
         (faction_get_slot, ":num_routed_agents_in_this_faction", ":cur_faction", slot_faction_num_routed_agents),
         (gt, ":num_routed_agents_in_this_faction", ":max_routed_agents"),
         (assign, ":max_routed_agents", ":num_routed_agents_in_this_faction"),
         (assign, ":routed_party_faction", ":cur_faction"),
       (try_end),
       
       (party_set_faction, ":routed_party", ":routed_party_faction"),

       (party_set_ai_behavior, ":routed_party", ai_bhvr_travel_to_party),

       (assign, ":minimum_distance", 1000000),
       (try_for_parties, ":party_no"),
         (party_is_active, ":party_no"),
         (party_get_slot, ":cur_party_type", ":party_no", slot_party_type),
         (this_or_next|eq, ":cur_party_type", spt_town),
         (eq, ":cur_party_type", spt_castle),
         (store_faction_of_party, ":cur_faction", ":party_no"),
         (this_or_next|eq, ":routed_party_faction", "fac_neutral"),
         (eq, ":cur_faction", ":routed_party_faction"),
         (party_get_position, pos1, ":party_no"),
         (store_distance_to_party_from_party, ":dist", ":party_no", "p_main_party"),
         (try_begin),
           (lt, ":dist", ":minimum_distance"),
           (assign, ":minimum_distance", ":dist"),
           (assign, ":nearest_ally_city", ":party_no"),
         (try_end),
       (try_end),     

       (party_get_position, pos1, "p_main_party"), #store position information of main party in pos1
       (party_get_position, pos2, ":nearest_ally_city"), #store position information of target city in pos2

       (assign, ":minimum_distance", 1000000),
       (try_for_range, ":unused", 0, 10),
         (map_get_random_position_around_position, pos3, pos1, 2), #store position of found random position (possible placing position for new routed party) around battle position in pos3
         (get_distance_between_positions, ":dist", pos2, pos3), #store distance between found position and target city in ":dist".
         (try_begin),
           (lt, ":dist", ":minimum_distance"),
           (assign, ":minimum_distance", ":dist"),
           (copy_position, pos63, pos3), 
         (try_end),
       (end_try),
     
       (party_set_position, ":routed_party", pos63),

       (party_set_ai_object, ":routed_party", ":nearest_ally_city"),
       (party_set_flags, ":routed_party", pf_default_behavior, 1),

       #adding party members of p_routed_enemies to routed_party
       (party_clear, ":routed_party"),
       (party_get_num_companion_stacks, ":num_stacks", "p_routed_enemies"), #question, I changed (total_enemy_casualties) with (p_routed_enemies) because this is not prisoner in p_routed_enemies party.
       (try_for_range, ":stack_no", 0, ":num_stacks"),
         (party_stack_get_troop_id, ":stack_troop", "p_routed_enemies", ":stack_no"),          
         (try_begin),
           (neg|troop_is_hero, ":stack_troop"), #do not add routed heroes to (new created) routed party for now.

           (party_stack_get_size, ":stack_size", "p_routed_enemies", ":stack_no"),
           (party_add_members, ":routed_party", ":stack_troop", ":stack_size"),
         (try_end),
       (try_end),
     (try_end),
    ]), #ozan


  #script_cf_training_ground_sub_routine_1_for_melee_details
  # INPUT:
  # value
  #OUTPUT:
  # none
  ("cf_training_ground_sub_routine_1_for_melee_details",
   [
     (store_script_param, ":value", 1),
     (ge, "$temp_3", ":value"),
     (val_add, ":value", 1),
     (troop_get_slot, ":troop_id", "trp_stack_selection_ids", ":value"),
     (str_store_troop_name, s0, ":troop_id"),
     ]),

  #script_training_ground_sub_routine_2_for_melee_details
  # INPUT:
  # value
  #OUTPUT:
  # none
  ("training_ground_sub_routine_2_for_melee_details",
   [
     (store_script_param, ":value", 1),
     (val_sub, ":value", 1),
     (try_begin),
       (lt, ":value", 0),
       (call_script, "script_remove_random_fit_party_member_from_stack_selection"),
     (else_try),
       (call_script, "script_remove_fit_party_member_from_stack_selection", ":value"),
     (try_end),
     (assign, ":troop_id", reg0),
     (store_sub, ":slot_index", "$temp_2", 1),
     (troop_set_slot, "trp_temp_array_a", ":slot_index", ":troop_id"),
     (try_begin),
       (eq, "$temp", "$temp_2"),
       (call_script, "script_start_training_at_training_ground", -1, "$temp"),
     (else_try),
       (val_add, "$temp_2", 1),
       (jump_to_menu, "mnu_training_ground_selection_details_melee_2"),
     (try_end),
     ]),

  #script_cf_training_ground_sub_routine_for_training_result
  # INPUT:
  # arg1: troop_id, arg2: stack_no, arg3: troop_count, arg4: xp_ratio_to_add
  #OUTPUT:
  # none
  ("cf_training_ground_sub_routine_for_training_result",
   [
     (store_script_param, ":troop_id", 1),
     (store_script_param, ":stack_no", 2),
     (store_script_param, ":amount", 3),
     (store_script_param, ":xp_ratio_to_add", 4),

     (store_character_level, ":level", ":troop_id"),
     (store_add, ":level_added", ":level", 5),
     (store_mul, ":min_hardness", ":level_added", 3),
     (val_min, ":min_hardness", 100),
     (store_sub, ":hardness_dif", ":min_hardness", "$g_training_ground_training_hardness"),
     (val_max, ":hardness_dif", 0),
     (store_sub, ":hardness_dif", 100, ":hardness_dif"),
     (val_mul, ":hardness_dif", ":hardness_dif"),
     (val_div, ":hardness_dif", 10), # value over 1000
##     (assign, reg0, ":hardness_dif"),
##     (display_message, "@Hardness difference: {reg0}/1000"),
     (store_mul, ":xp_ratio_to_add_for_stack", ":xp_ratio_to_add", ":hardness_dif"),
     (val_div, ":xp_ratio_to_add_for_stack", 1000),
     (try_begin),
       (eq, ":troop_id", "trp_player"),
       (val_mul, ":xp_ratio_to_add_for_stack", 1),
     (else_try),
       (try_begin),
         (eq, "$g_mt_mode", ctm_melee),
         (try_begin),
           (this_or_next|troop_is_guarantee_ranged, ":troop_id"),
           (troop_is_guarantee_horse, ":troop_id"),
           (val_div, ":xp_ratio_to_add_for_stack", 4),
         (try_end),
       (else_try),
         (eq, "$g_mt_mode", ctm_mounted),
         (try_begin),
           (neg|troop_is_guarantee_horse, ":troop_id"),
           (assign, ":xp_ratio_to_add_for_stack", 0),
         (try_end),
       (else_try),
         (neg|troop_is_guarantee_ranged, ":troop_id"),
         (assign, ":xp_ratio_to_add_for_stack", 0),
       (try_end),
     (try_end),
     (val_add,  ":level", 1),
     (store_mul, ":xp_to_add", 100, ":level"),
     (val_mul, ":xp_to_add", ":amount"),
     (val_div, ":xp_to_add", 20),
     (val_mul, ":xp_to_add", ":xp_ratio_to_add_for_stack"),
     (val_div, ":xp_to_add", 1000),
     (store_mul, ":max_xp_to_add", ":xp_to_add", 3),
     (val_div, ":max_xp_to_add", 2),
     (store_div, ":min_xp_to_add", ":xp_to_add", 2),
     (store_random_in_range, ":random_xp_to_add", ":min_xp_to_add", ":max_xp_to_add"),
     (gt, ":random_xp_to_add", 0),
     (try_begin),
       (troop_is_hero, ":troop_id"),
       (add_xp_to_troop, ":random_xp_to_add", ":troop_id"),
       (store_div, ":proficiency_to_add", ":random_xp_to_add", 50),
       (try_begin),
         (gt, ":proficiency_to_add", 0),
         (troop_raise_proficiency, ":troop_id", "$g_training_ground_used_weapon_proficiency", ":proficiency_to_add"),
       (try_end),
     (else_try),
       (party_add_xp_to_stack, "p_main_party", ":stack_no", ":random_xp_to_add"),
     (try_end),
     (assign, reg0, ":random_xp_to_add"),
     ]),


##  #script_cf_print_troop_name_with_stack_index_to_s0
##  # INPUT:
##  # param1: stack_index
##  
##  #OUTPUT:
##  # string register 0.
##  ("cf_print_troop_name_with_stack_index_to_s0",
##   [
##     (store_script_param_1, ":stack_index"),
##     (party_get_num_companion_stacks, ":num_stacks", "p_main_party"),
##     (lt, ":stack_index", ":num_stacks"),
##     (party_stack_get_troop_id, ":stack_troop", "p_main_party", ":stack_index"),
##     (str_store_troop_name, s0, ":stack_troop"),
##    ]),

  #script_print_troop_owned_centers_in_numbers_to_s0
  # INPUT:
  # param1: troop_no
  #OUTPUT:
  # string register 0.
  ("print_troop_owned_centers_in_numbers_to_s0",
   [
     (store_script_param_1, ":troop_no"),
     (str_store_string, s0, "@nothing"),
     (assign, ":owned_towns", 0),
     (assign, ":owned_castles", 0),
     (assign, ":owned_villages", 0),
     (try_for_range_backwards, ":cur_center", centers_begin, centers_end),
       (party_slot_eq, ":cur_center", slot_town_lord, ":troop_no"),
       (try_begin),
         (party_slot_eq, ":cur_center", slot_party_type, spt_town),
         (val_add, ":owned_towns", 1),
       (else_try),
         (party_slot_eq, ":cur_center", slot_party_type, spt_castle),
         (val_add, ":owned_castles", 1),
       (else_try),
         (val_add, ":owned_villages", 1),
       (try_end),
     (try_end),
     (assign, ":num_types", 0),
     (try_begin),
       (gt, ":owned_villages", 0),
       (assign, reg0, ":owned_villages"),
       (store_sub, reg1, reg0, 1),
       (str_store_string, s0, "@{reg0} village{reg1?s:}"),
       (val_add, ":num_types", 1),
     (try_end),
     (try_begin),
       (gt, ":owned_castles", 0),
       (assign, reg0, ":owned_castles"),
       (store_sub, reg1, reg0, 1),
       (try_begin),
         (eq, ":num_types", 0),
         (str_store_string, s0, "@{reg0} castle{reg1?s:}"),
       (else_try),
         (str_store_string, s0, "@{reg0} castle{reg1?s:} and {s0}"),
       (try_end),
       (val_add, ":num_types", 1),
     (try_end),
     (try_begin),
       (gt, ":owned_towns", 0),
       (assign, reg0, ":owned_towns"),
       (store_sub, reg1, reg0, 1),
       (try_begin),
         (eq, ":num_types", 0),
         (str_store_string, s0, "@{reg0} town{reg1?s:}"),
       (else_try),
         (eq, ":num_types", 1),
         (str_store_string, s0, "@{reg0} town{reg1?s:} and {s0}"),
       (else_try),
         (str_store_string, s0, "@{reg0} town{reg1?s:}, {s0}"),
       (try_end),
     (try_end),
     (store_add, reg0, ":owned_villages", ":owned_castles"),
     (val_add, reg0, ":owned_towns"),
     ]),

  #script_get_random_melee_training_weapon
  # INPUT: none
  # OUTPUT: reg0 = weapon_1, reg1 = weapon_2
  ("get_random_melee_training_weapon",
   [
     (assign, ":weapon_1", -1),
     (assign, ":weapon_2", -1),
     (store_random_in_range, ":random_no", 0, 3),
     (try_begin),
       (eq, ":random_no", 0),
       (assign, ":weapon_1", "itm_practice_staff"),
     (else_try),
       (eq, ":random_no", 1),
       (assign, ":weapon_1", "itm_practice_sword"),
       (assign, ":weapon_2", "itm_practice_shield"),
     (else_try),
       (assign, ":weapon_1", "itm_heavy_practice_sword"),
     (try_end),
     (assign, reg0, ":weapon_1"),
     (assign, reg1, ":weapon_2"),
     ]),

  #script_start_training_at_training_ground
  # INPUT:
  # param1: training_weapon_type, param2: training_param
  ("start_training_at_training_ground",
   [
     (val_add, "$g_training_ground_training_count", 1),
     (store_script_param, ":mission_weapon_type", 1),
     (store_script_param, ":training_param", 2),

     (set_jump_mission, "mt_training_ground_training"),

     (assign, ":training_default_weapon_1", -1),
     (assign, ":training_default_weapon_2", -1),
     (assign, ":training_default_weapon_3", -1),
     (assign, "$scene_num_total_gourds_destroyed", 0),
     (try_begin),
       (eq, ":mission_weapon_type", itp_type_bow),
       (assign, "$g_training_ground_used_weapon_proficiency", wpt_archery),
       (assign, ":training_default_weapon_1", "itm_practice_bow"),
       (try_begin),
         (eq, "$g_mt_mode", ctm_mounted),
         (assign, ":training_default_weapon_2", "itm_practice_arrows_100_amount"),
       (else_try),
         (assign, ":training_default_weapon_2", "itm_practice_arrows_10_amount"),
       (try_end),
     (else_try),
       (eq, ":mission_weapon_type", itp_type_crossbow),
       (assign, "$g_training_ground_used_weapon_proficiency", wpt_crossbow),
       (assign, ":training_default_weapon_1", "itm_practice_crossbow"),
       (assign, ":training_default_weapon_2", "itm_practice_bolts_9_amount"),
     (else_try),
       (eq, ":mission_weapon_type", itp_type_thrown),
       (assign, "$g_training_ground_used_weapon_proficiency", wpt_throwing),
       (try_begin),
         (eq, "$g_mt_mode", ctm_mounted),
         (assign, ":training_default_weapon_2", "itm_practice_throwing_daggers_100_amount"),
       (else_try),
         (assign, ":training_default_weapon_2", "itm_practice_throwing_daggers"),
       (try_end),
     (else_try),
       (eq, ":mission_weapon_type", itp_type_one_handed_wpn),
       (assign, "$g_training_ground_used_weapon_proficiency", wpt_one_handed_weapon),
       (assign, ":training_default_weapon_1", "itm_practice_sword"),
     (else_try),
       (eq, ":mission_weapon_type", itp_type_polearm),
       (assign, "$g_training_ground_used_weapon_proficiency", wpt_polearm),
       (assign, ":training_default_weapon_1", "itm_practice_lance"),
     (else_try),
       #weapon_type comes as -1 when melee training is selected
       (assign, "$g_training_ground_used_weapon_proficiency", wpt_one_handed_weapon),
       (call_script, "script_get_random_melee_training_weapon"),
       (assign, ":training_default_weapon_1", reg0),
       (assign, ":training_default_weapon_2", reg1),
     (try_end),
     
##     (assign, "$g_training_ground_training_troop_stack_index", ":stack_index"),
     (try_begin),
       (eq, "$g_mt_mode", ctm_mounted),
       (assign, ":training_default_weapon_3", "itm_practice_horse"),
       (store_add, "$g_training_ground_training_scene", "scn_training_ground_horse_track_1", "$g_encountered_party"),
       (val_sub, "$g_training_ground_training_scene", training_grounds_begin),
     (else_try),
       (store_add, "$g_training_ground_training_scene", "scn_training_ground_ranged_melee_1", "$g_encountered_party"),
       (val_sub, "$g_training_ground_training_scene", training_grounds_begin),
     (try_end),

     (modify_visitors_at_site, "$g_training_ground_training_scene"),
     (reset_visitors),
     (set_visitor, 0, "trp_player"),

     (assign, ":selected_weapon", -1),
     (try_for_range, ":cur_slot", 0, 4),#equipment slots
       (troop_get_inventory_slot, ":cur_item", "trp_player", ":cur_slot"),
       (ge, ":cur_item", 0),
       (item_get_type, ":item_type", ":cur_item"),
       (try_begin),
         (eq, ":item_type", ":mission_weapon_type"),
         (eq, ":selected_weapon", -1),
         (assign, ":selected_weapon", ":cur_item"),
       (try_end),
     (try_end),
     (mission_tpl_entry_clear_override_items, "mt_training_ground_training", 0),
     (mission_tpl_entry_add_override_item, "mt_training_ground_training", 0, "itm_practice_boots"),
     (try_begin),
       (ge, ":training_default_weapon_1", 0),
       (try_begin),
         (ge, ":selected_weapon", 0),
         (mission_tpl_entry_add_override_item, "mt_training_ground_training", 0, ":selected_weapon"),
       (else_try),
         (mission_tpl_entry_add_override_item, "mt_training_ground_training", 0, ":training_default_weapon_1"),
       (try_end),
     (try_end),
     (try_begin),
       (ge, ":training_default_weapon_2", 0),
       (mission_tpl_entry_add_override_item, "mt_training_ground_training", 0, ":training_default_weapon_2"),
     (try_end),
     (try_begin),
       (ge, ":training_default_weapon_3", 0),
       (mission_tpl_entry_add_override_item, "mt_training_ground_training", 0, ":training_default_weapon_3"),
     (try_end),

     (assign, ":cur_visitor_point", 5),
     (troop_get_slot, ":num_fit", "trp_stack_selection_amounts", 1),
     (store_add, ":end_cond", 5, ":num_fit"),
     (val_min, ":end_cond", 13),
     (try_for_range, ":cur_visitor_point", 5, ":end_cond"),
       (call_script, "script_remove_random_fit_party_member_from_stack_selection"),
       (set_visitor, ":cur_visitor_point", reg0),
       (val_add, ":cur_visitor_point", 1),
     (try_end),
     (try_begin),
       (eq, "$g_mt_mode", ctm_melee),
       (assign, ":total_difficulty", 0),
       (try_for_range, ":i", 0, ":training_param"),
         (troop_get_slot, ":cur_troop", "trp_temp_array_a", ":i"),
         (store_add, ":cur_entry_point", ":i", 1),
         (set_visitor, ":cur_entry_point", ":cur_troop"),
         (mission_tpl_entry_clear_override_items, "mt_training_ground_training", ":cur_entry_point"),
         (mission_tpl_entry_add_override_item, "mt_training_ground_training", ":cur_entry_point", "itm_practice_boots"),
         (call_script, "script_get_random_melee_training_weapon"),
         (mission_tpl_entry_add_override_item, "mt_training_ground_training", ":cur_entry_point", reg0),
         (try_begin),
           (ge, reg1, 0),
           (mission_tpl_entry_add_override_item, "mt_training_ground_training", ":cur_entry_point", reg1),
         (try_end),
         (store_character_level, ":cur_troop_level", ":cur_troop"),
         (val_add, ":cur_troop_level", 10),
         (val_mul, ":cur_troop_level", ":cur_troop_level"),
         (val_add, ":total_difficulty", ":cur_troop_level"),
       (try_end),

       (assign, "$g_training_ground_training_num_enemies", ":training_param"),
       (assign, "$g_training_ground_training_hardness",  ":total_difficulty"),
       (store_add, ":number_multiplier", "$g_training_ground_training_num_enemies", 4),
       (val_mul, "$g_training_ground_training_hardness", ":number_multiplier"),
       (val_div, "$g_training_ground_training_hardness", 2400),
       (str_store_string, s0, "@Your opponents are ready for the fight."),
     (else_try),
       (eq, "$g_mt_mode", ctm_mounted),
       (try_begin),
         (eq, ":mission_weapon_type", itp_type_bow),
         (assign, "$g_training_ground_training_hardness", 350),
         (assign, "$g_training_ground_training_num_gourds_to_destroy", 30),
       (else_try),
         (eq, ":mission_weapon_type", itp_type_thrown),
         (assign, "$g_training_ground_training_hardness", 400),
         (assign, "$g_training_ground_training_num_gourds_to_destroy", 30),
       (else_try),
         (eq, ":mission_weapon_type", itp_type_one_handed_wpn),
         (assign, "$g_training_ground_training_hardness", 200),
         (assign, "$g_training_ground_training_num_gourds_to_destroy", 45),
       (else_try),
         (eq, ":mission_weapon_type", itp_type_polearm),
         (assign, "$g_training_ground_training_hardness", 280),
         (assign, "$g_training_ground_training_num_gourds_to_destroy", 35),
       (try_end),
       (str_store_string, s0, "@Try to destroy as many targets as you can. You have two and a half minutes to clear the track."),
     (else_try),
       (eq, "$g_mt_mode", ctm_ranged),
       (store_mul, "$g_training_ground_ranged_distance", ":training_param", 100),
       (assign, ":hardness_modifier", ":training_param"),
       (val_mul, ":hardness_modifier", ":hardness_modifier"),
       (try_begin),
         (eq, ":mission_weapon_type", itp_type_bow),
         (val_mul, ":hardness_modifier", 3),
         (val_div, ":hardness_modifier", 2),
       (else_try),
         (eq, ":mission_weapon_type", itp_type_thrown),
         (val_mul, ":hardness_modifier", 5),
         (val_div, ":hardness_modifier", 2),
         (val_mul, ":hardness_modifier", ":training_param"),
         (val_div, ":hardness_modifier", 2),
       (try_end),
       (store_mul, "$g_training_ground_training_hardness", 100, ":hardness_modifier"),
       (val_div, "$g_training_ground_training_hardness", 6000),
       (str_store_string, s0, "@Stay behind the line on the ground and shoot the targets. Try not to waste any shots."),
     (try_end),
     (jump_to_menu, "mnu_training_ground_description"),
     ]),
  
  
  #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 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"),
          (try_begin),
            (neg|troop_is_wounded, ":stack_troop"),
            (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_members_with_full_health
  # Returns the number of unwounded regulars, and heroes other than player with 100% hitpoints in a party
  # INPUT:
  # param1: Party-id
  # OUTPUT: reg0 = result
  ("party_count_members_with_full_health",
    [
      (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"),
          (neq, ":stack_troop", "trp_player"),
          (store_troop_health, ":troop_hp", ":stack_troop"),
          (try_begin),
            (ge, ":troop_hp", 80),
            (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"),
          (val_max, ":num_fit", 0),
        (try_end),
        (val_add, reg0, ":num_fit"),
      (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.
        (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_get_number_of_armies
# Input: arg1 = faction_no
# Output: reg0 = number_of_armies
  ("faction_get_number_of_armies",
   [
      (store_script_param_1, ":faction_no"),
      (assign, ":num_armies", 0),
      (try_for_range, ":troop_no", active_npcs_begin, active_npcs_end),
		(troop_slot_eq, ":troop_no", slot_troop_occupation, slto_kingdom_hero),
    	(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),
        (party_is_active, ":hero_party"),
        (call_script, "script_party_count_fit_regulars", ":hero_party"),
        (assign, ":party_size", reg0),
        (call_script, "script_party_get_ideal_size", ":hero_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),
      (assign, reg0, ":num_armies"),
    ]),  
  

# script_faction_recalculate_strength
# Input: arg1 = faction_no
# Output: reg0 = strength
  ("faction_recalculate_strength",
   [
      (store_script_param_1, ":faction_no"),

      (call_script, "script_faction_get_number_of_armies", ":faction_no"),
      (assign, ":num_armies", reg0),
      (assign, ":num_castles", 0),
      (assign, ":num_towns", 0),

      (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_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_walled_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
  # arg2 = preferred_center_no
  
  #OUTPUT:
  # This script may return false if there is no matching town.
  # reg0 = town_no (Can fail)
  ("cf_select_random_walled_center_with_faction",
    [
      (store_script_param, ":faction_no", 1),
      (store_script_param, ":preferred_center_no", 2),
      (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),
        (eq, ":cur_center", ":preferred_center_no"),
        (val_add, ":no_centers", 99),
      (try_end),
      (gt, ":no_centers", 0), #Fail if there are no centers
      (store_random_in_range, ":random_center", 0, ":no_centers"),
      (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_sub, ":random_center", 1),
        (try_begin),
          (eq, ":cur_center", ":preferred_center_no"),
          (val_sub, ":random_center", 99),
        (try_end),
        (lt, ":random_center", 0),
        (assign, ":result", ":cur_center"),
      (try_end),
      (assign, reg0, ":result"),
  ]),


  #script_cf_select_random_walled_center_with_faction_and_owner_priority_no_siege:
  # INPUT:
  # arg1 = faction_no
  # arg2 = owner_troop_no
  #OUTPUT:
  # This script may return false if there is no matching town.
  # reg0 = center_no (Can fail)
  ("cf_select_random_walled_center_with_faction_and_owner_priority_no_siege",
    [
      (store_script_param, ":faction_no", 1),
      (store_script_param, ":troop_no", 2),
      (assign, ":result", -1),
      (assign, ":no_centers", 0),
      
      (call_script, "script_lord_get_home_center", ":troop_no"),
      (assign, ":home_center", reg0),
      
      (try_for_range,":cur_center", walled_centers_begin, walled_centers_end),
        (store_faction_of_party, ":cur_faction", ":cur_center"),
        (eq, ":cur_faction", ":faction_no"),
        (party_slot_eq, ":cur_center", slot_center_is_besieged_by, -1),
        (val_add, ":no_centers", 1),
        
        #(party_slot_eq, ":cur_center", slot_town_lord, ":troop_no"),
        (eq, ":home_center", ":cur_center"), #I changed it with above line, now if slot_town_lord is a village its home center is bordered walled center. Better this way. ozan-18.01.09
        
        (val_add, ":no_centers", 1000),
      (try_end),
      (gt, ":no_centers", 0), #Fail if there are no centers
      (store_random_in_range, ":random_center", 0, ":no_centers"),
      (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"),
        (party_slot_eq, ":cur_center", slot_center_is_besieged_by, -1),
        (val_sub, ":random_center", 1),
        (try_begin),
          #(party_slot_eq, ":cur_center", slot_town_lord, ":troop_no"),
          (eq, ":home_center", ":cur_center"), #I changed it with above line, now if slot_town_lord is a village its home center is bordered walled center. Better this way. ozan-18.01.09

          (val_sub, ":random_center", 1000),
        (try_end),
        (lt, ":random_center", 0),
        (assign, ":result", ":cur_center"),
      (try_end),
      (assign, reg0, ":result"),
  ]),


  #script_cf_select_random_walled_center_with_faction_and_less_strength_priority:
  # 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
  # arg2 = preferred_center_no
  
  #OUTPUT:
  # This script may return false if there is no matching town.
  # reg0 = town_no (Can fail)
  ("cf_select_random_walled_center_with_faction_and_less_strength_priority",
    [
      (store_script_param, ":faction_no", 1),
      (store_script_param, ":preferred_center_no", 2),
      (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"),
        (party_slot_eq, ":cur_center", slot_center_is_besieged_by, -1),
        (val_add, ":no_centers", 1),
        (try_begin),
          (eq, ":cur_center", ":preferred_center_no"),
          (val_add, ":no_centers", 99),
        (try_end),
##        (call_script, "script_party_calculate_regular_strength", ":cur_center"),
##        (assign, ":strength", reg0),
##        (lt, ":strength", 80),
##        (store_sub, ":strength", 100, ":strength"),
##        (val_div, ":strength", 20),
##        (val_add, ":no_centers", ":strength"),
      (try_end),
      (gt, ":no_centers", 0), #Fail if there are no centers
      (store_random_in_range, ":random_center", 0, ":no_centers"),
      (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"),
        (party_slot_eq, ":cur_center", slot_center_is_besieged_by, -1),
        (val_sub, ":random_center", 1),
        (try_begin),
          (eq, ":cur_center", ":preferred_center_no"),
          (val_sub, ":random_center", 99),
        (try_end),
##        (try_begin),
##          (call_script, "script_party_calculate_regular_strength", ":cur_center"),
##          (assign, ":strength", reg0),
##          (lt, ":strength", 80),
##          (store_sub, ":strength", 100, ":strength"),
##          (val_div, ":strength", 20),
##          (val_sub, ":random_center", ":strength"),
##        (try_end),
        (lt, ":random_center", 0),
        (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"),
  ]),
  
  #script_cf_select_random_town_at_peace_with_faction_in_trade_route
  # INPUT:
  # arg1 = town_no
  # arg2 = 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_in_trade_route",
    [
      (store_script_param, ":town_no", 1),
      (store_script_param, ":faction_no", 2),
      (assign, ":result", -1),
      (assign, ":no_towns", 0),
      (try_for_range, ":cur_slot", slot_town_trade_routes_begin, slot_town_trade_routes_end),
        (party_get_slot, ":cur_town", ":town_no", ":cur_slot"),
        (gt, ":cur_town", 0),
        (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"),
      (try_for_range, ":cur_slot", slot_town_trade_routes_begin, slot_town_trade_routes_end),
        (eq, ":result", -1),
        (party_get_slot, ":cur_town", ":town_no", ":cur_slot"),
        (gt, ":cur_town", 0),
        (store_faction_of_party, ":cur_faction", ":cur_town"),
        (store_relation, ":reln", ":cur_faction", ":faction_no"),
        (ge, ":reln", 0),
        (val_sub, ":random_town", 1),
        (lt, ":random_town", 0),
        (assign, ":result", ":cur_town"),
      (try_end),
      (assign, reg0, ":result"),
  ]),

  
  
	#the following is a very simple adjustment - it measures the difference in prices between two towns
	#all goods are weighted equally except for luxuries
	#it does not take into account the prices of the goods, nor cargo capacity
	#to do that properly, a merchant would have to virtually fill his baggage, slot by slot, for each town
	#i also found that one needed to introduce demand inelasticity -- prices should vary a lot for grain,  relatively little for iron
	
  ("cf_select_most_profitable_town_at_peace_with_faction_in_trade_route",
    [
      (store_script_param, ":town_no", 1),
      (store_script_param, ":faction_no", 2),

      (assign, ":result", -1),
	  (assign, ":best_town_score", 0),
      (store_sub, ":item_to_price_slot", slot_town_trade_good_prices_begin, trade_goods_begin),

      (try_for_range, ":cur_slot", slot_town_trade_routes_begin, slot_town_trade_routes_end),
        (party_get_slot, ":cur_town", ":town_no", ":cur_slot"),
        (gt, ":cur_town", 0),
		
        (store_faction_of_party, ":cur_faction", ":cur_town"),
        (store_relation, ":reln", ":cur_faction", ":faction_no"),
        (ge, ":reln", 0),

		(assign, ":cur_town_score", 0),
		(try_for_range, ":cur_goods", trade_goods_begin, trade_goods_end),
			(neq, ":cur_goods", "itm_butter"), #Don't count perishables
			(neq, ":cur_goods", "itm_cattle_meat"),
			(neq, ":cur_goods", "itm_chicken"),
			(neq, ":cur_goods", "itm_pork"),
			
            (store_add, ":cur_goods_price_slot", ":cur_goods", ":item_to_price_slot"),
			(party_get_slot, ":origin_price", ":town_no", ":cur_goods_price_slot"),
			(party_get_slot, ":destination_price", ":cur_town", ":cur_goods_price_slot"),
						
			(gt, ":destination_price", ":origin_price"),
			(store_sub, ":price_dif", ":destination_price", ":origin_price"),
			
			(try_begin), #weight luxury goods double
				(this_or_next|eq, ":cur_goods", "itm_spice"),
					(eq, ":cur_goods", "itm_velvet"),
				(val_mul, ":price_dif", 2),
			(try_end),
			(val_add, ":cur_town_score", ":price_dif"),
		(try_end),
		
##		(try_begin),
##			(eq, "$cheat_mode", 1),
##			(str_store_party_name, s10, ":town_no"),
##			(str_store_party_name, s11, ":cur_town"),
##			(assign, reg3, ":cur_town_score"),
##			(display_message, "str_caravan_in_s10_considers_s11_total_price_dif_=_reg3"),
##		(try_end),
		
		(gt, ":cur_town_score", ":best_town_score"),
		(assign, ":best_town_score", ":cur_town_score"),
		(assign, ":result", ":cur_town"),
		
	  (try_end),

      (gt, ":result", -1), #Fail if there are no towns

      (assign, reg0, ":result"),

#	  (store_current_hours, ":hour"),
#	  (party_set_slot, ":result", slot_town_caravan_last_visit, ":hour"),

##	  (try_begin),
##		(eq, "$cheat_mode", 1),
##	    (assign, reg3, ":best_town_score"),
##	    (str_store_party_name, s3, ":town_no"),
##	    (str_store_party_name, s4, ":result"),
##	    (display_message, "str_test__caravan_in_s3_selects_for_s4_trade_score_reg3"),
##	  (try_end),
	  
  ]),

  
  ##  ("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),
  ##  ]),
  
  # NE scouts
      ("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),
    ]),
  
    ("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),
    ]),
  
  
  # NE end scouts
  
  #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 cannot 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 cannot 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 cannot 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 cannot 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)),
  ##  ]),
  
  # NE scouts
    ##  #script_cf_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 cannot be spawned.
    ("cf_spawn_party_at_faction_town_if_below_limit",
      [
## Rewriting this to support player kingdom - Jinnai
#        (store_num_parties_of_template, reg(22), "$pin_party_template"),
        (assign,":total",0),
        (try_begin),
          (eq,"$pin_faction","fac_player_supporters_faction"),
          (try_for_parties,":party_no"),
            (store_faction_of_party, ":faction", ":party_no"),
            (eq,":faction","$pin_faction"),
            (party_get_template_id,":template",":party_no"),
            (this_or_next|eq,":template","pt_swadian_patrol"),
            (this_or_next|eq,":template","pt_vaegir_patrol"),
            (this_or_next|eq,":template","pt_khergit_patrol"),
			(this_or_next|eq,":template","pt_rhodok_patrol"),	
            (this_or_next|eq,":template","pt_sarranid_patrol"),			
            (this_or_next|eq,":template","pt_nord_patrol"),
            (eq,":template","pt_rhodok_patrol"),
            (val_add,":total",1),
          (try_end),
        (else_try),
          (try_for_parties,":party_no"),
            (party_get_template_id,":template",":party_no"),
            (eq,":template","$pin_party_template"),
            (store_faction_of_party, ":faction", ":party_no"),
            (eq,":faction","$pin_faction"),
            (val_add,":total",1),
          (try_end),
        (try_end),
        (assign,reg(22),":total"),
        (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)),
        (party_set_faction,"$pout_party","$pin_faction"),
        (try_begin),
          (eq,"$pin_faction","fac_player_supporters_faction"),
          (str_store_party_name,s1,"$pout_town"),
          (str_store_troop_name,s2,"trp_logistics_adviser"),
          (display_message,"@Your {s2} has managed to organize a patrol out of {s1}."),
        (try_end),
    ]),
	# NE endscouts
	
	
  # script_shuffle_troop_slots:
  # Shuffles a range of slots of a given troop.
  # Used for exploiting a troop as an array.
  # Input: arg1 = troop_no, arg2 = slot_begin, arg3 = slot_end
  ("shuffle_troop_slots",
    [
      (store_script_param, ":troop_no", 1),
      (store_script_param, ":slots_begin", 2),
      (store_script_param, ":slots_end", 3),
      (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", ":troop_no", ":cur_slot_no"), #temporarily store the value in slot reg(57) in reg(59)
        (troop_get_slot, ":random_slot_value", ":troop_no", ":random_slot_no"), #temporarily store the value in slot reg(58) in reg(60)
        (troop_set_slot, ":troop_no", ":cur_slot_no", ":random_slot_value"), # Now exchange the two...
        (troop_set_slot, ":troop_no", ":random_slot_no", ":cur_slot_value"),
      (try_end),
  ]),
  
  
  # script_get_quest - combines old get_random_quest with new get_dynamic_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_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),
      (troop_get_slot, ":giver_reputation", ":giver_troop", slot_lord_reputation_type),
      
      (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),
          (assign, ":quests_begin_2", lord_quests_begin_2),
          (assign, ":quests_end_2", lord_quests_end_2),
        (else_try),
          (assign, ":quests_begin", enemy_lord_quests_begin),
          (assign, ":quests_end", enemy_lord_quests_end),
          (assign, ":quests_begin_2", 0),
          (assign, ":quests_end_2", 0),
        (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),
        (assign, ":quests_begin_2", village_elder_quests_begin_2),
        (assign, ":quests_end_2", village_elder_quests_end_2),
      (else_try),
        (is_between, ":giver_troop", mayors_begin, mayors_end),
        (assign, ":quests_begin", mayor_quests_begin),
        (assign, ":quests_end", mayor_quests_end),
        (assign, ":quests_begin_2", mayor_quests_begin_2),
        (assign, ":quests_end_2", mayor_quests_end_2),
      (else_try),
        (assign, ":quests_begin", lady_quests_begin),
        (assign, ":quests_end", lady_quests_end),
        (assign, ":quests_begin_2", lady_quests_begin_2),
        (assign, ":quests_end_2", lady_quests_end_2),
      (try_end),
	  
      (assign, ":result", -1),
	  (assign, ":quest_target_troop", -1),
	  (assign, ":quest_target_center", -1),
	  (assign, ":quest_target_faction", -1),
	  (assign, ":quest_object_faction", -1),
	  (assign, ":quest_object_troop", -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),	 	  
	  
	  (try_begin), #get dynamic quest is a separate script, so that we can scan a number of different troops at once for it
	   	(call_script, "script_get_dynamic_quest", "$g_talk_troop"),
	   		   	
	    (assign, ":result", reg0),
	    (assign, ":relevant_troop", reg1),
	    (assign, ":relevant_party", reg2),
	    (assign, ":relevant_faction", reg3),
		
	    #GUILDMASTER QUESTS
	    (try_begin),
			(eq, ":result", "qst_track_down_bandits"), 
			(assign, ":quest_target_party", ":relevant_party"),
			(assign ,":quest_expiration_days", 60),
			(assign, ":quest_xp_reward", 1000),
			(assign, ":quest_gold_reward", 1000),
			
		(else_try),	
			(eq, ":result", "qst_retaliate_for_border_incident"), 
			(assign, ":quest_target_troop", ":relevant_troop"),
			(assign, ":quest_target_faction", ":relevant_faction"),
			
			(assign ,":quest_expiration_days", 30),
			(assign, ":quest_xp_reward", 1000),
			(assign, ":quest_gold_reward", 1000),
			
		#KINGDOM LORD QUESTS	
		(else_try),
	        (eq, ":result", "qst_cause_provocation"),
			(assign, ":quest_target_faction", ":relevant_faction"),
	        (assign, ":quest_expiration_days", 30),
	        (assign, ":quest_dont_give_again_period", 100),
			(assign, ":quest_xp_reward", 1000),
			(assign, ":quest_gold_reward", 1000),
			
	    (else_try),
			(eq, ":result", "qst_destroy_bandit_lair"), 
			(assign, ":quest_target_party", ":relevant_party"),
			(assign ,":quest_expiration_days", 60),
			(assign, ":quest_xp_reward", 3000),
			(assign, ":quest_gold_reward", 1500),

		#KINGDOM LADY OR KINGDOM HERO QUESTS	
		(else_try),	
	        (eq, ":result", "qst_rescue_prisoner"),
			(assign, ":quest_target_troop", ":relevant_troop"),
			(assign, ":quest_target_center", ":relevant_party"),

	        (assign, ":quest_expiration_days", 30),
	        (assign, ":quest_dont_give_again_period", 5),
			(assign, ":quest_xp_reward", 1500),
			(assign, ":quest_gold_reward", 3000),
		(try_end),	  
	  (try_end),
	  
	  #no dynamic quest available
	  (try_begin),
		(eq, ":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_faction", -1),
	        (assign, ":quest_object_troop", -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_sub, ":num_possible_old_quests", ":quests_end", ":quests_begin"),
            (store_sub, ":num_possible_new_quests", ":quests_end_2", ":quests_begin_2"),
            (store_add, ":num_possible_total_quests", ":num_possible_old_quests", ":num_possible_new_quests"),
            
            (store_random_in_range, ":quest_no", 0, ":num_possible_total_quests"),
            (try_begin),
              (lt, ":quest_no", ":num_possible_old_quests"),
              (store_random_in_range, ":quest_no", ":quests_begin", ":quests_end"), 
            (else_try),
              (store_random_in_range, ":quest_no", ":quests_begin_2", ":quests_end_2"),
            (try_end),
	        
####TODO: Remove this when test is done
####       (assign, ":quest_no", "qst_meet_spy_in_enemy_town"),
#####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),
##############NE quests
############ v585 Josef scholar
         (else_try),
          (eq, ":quest_no", "qst_escort_scholars"),
		  (try_begin),		  
		  ###############uncomment
		  (ge, ":player_level", 10),
          (is_between, ":giver_center_no", villages_begin, villages_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_scholars_mode", 0),
		  (assign, ":quest_dont_give_again_period", 50),
		  (assign, ":result", ":quest_no"),
          (try_end),
### v585 Josef smugglers
        (else_try),
          (eq, ":quest_no", "qst_hunt_down_smugglers"),
          (try_begin),
		    (ge, ":player_level", 5),
            (is_between, ":giver_center_no", villages_begin, villages_end),           
            (assign, ":cur_object_center", ":giver_center_no"),
	        (store_faction_of_party, ":giver_faction_no", ":cur_object_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_smugglers"),
            (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_hunt_down_smugglers_num_parties_returned", 0),
            (assign, "$qst_hunt_down_smugglers_num_parties_fleed", 0),
          (try_end),
### v585 Josef kidnapped wife
          (else_try),
          (eq, ":quest_no", "qst_kidnapped_wife"),
          (is_between, ":giver_center_no", villages_begin, villages_end),
		  (store_faction_of_party, ":cur_object_faction", ":giver_center_no"),
		  (call_script, "script_cf_select_random_village_with_faction", ":cur_object_faction"),   
		  (neq,reg0,":giver_center_no"),
		  (assign, ":quest_target_center", reg0),
		  (assign, ":quest_target_amount",500),
          (assign, ":quest_dont_give_again_period", 40),
          (assign, ":result", ":quest_no"),	  
          ####v585 Josefgirl
	     (else_try),
          (eq, ":quest_no", "qst_hunt_down_girl"),
          (try_begin),
            (is_between, ":giver_center_no", villages_begin, villages_end),
            ###The quest giver is the village elder
			(store_faction_of_party, ":cur_object_faction", ":giver_center_no"),
            (call_script, "script_cf_select_random_village_with_faction", ":cur_object_faction"), 
			(neq,reg0,":giver_center_no"),			
			(neg|party_slot_eq, reg0, slot_village_state, svs_looted),
            (neg|party_slot_eq, reg0, slot_village_state, svs_being_raided),	 
		    (assign, ":quest_target_center", reg0),		
             (store_random_in_range, ":quest_target_dna", 0, 1000000),		
            (assign, ":quest_expiration_days", 3),  #three
            (assign, ":quest_dont_give_again_period", 40),
            (assign, ":result", ":quest_no"),
          (try_end),	  
### v585 Josef lumber 
        (else_try),
          (eq, ":quest_no", "qst_deliver_lumber"),
          (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_lumber"),
            (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),			
###v585 Josef end  


#### NE end quests			  
			  
			  
			  
	        (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),
	          (eq, ":quest_no", "qst_train_peasants_against_bandits"),
	          (try_begin),
	            (is_between, ":giver_center_no", villages_begin, villages_end),
	            ######The quest giver is the village elder
	            (store_skill_level, ":player_trainer", "skl_trainer", "trp_player"),
	            (gt, ":player_trainer", 0),
	            (store_random_in_range, ":quest_target_amount", 5, 8),
	            (assign, ":quest_target_center", ":giver_center_no"),
	            (assign, ":quest_expiration_days", 20),
	            (assign, ":quest_dont_give_again_period", 40),
	            (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"),
# NE quests
# v585 Josef Cheese Rustlers from mayor
		  (else_try),
          (eq, ":quest_no", "qst_cheese_rustlers"),
          (is_between, ":giver_center_no", centers_begin, centers_end),
		  (lt, ":player_level", 15),
          (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",75),
          (val_mul, ":quest_gold_reward", 10),
          (assign, ":quest_expiration_days", 30),
          (assign, ":quest_dont_give_again_period", 30),
          (assign, ":result", ":quest_no"),
# v585 Josef Cheese Paladins from mayor
		  (else_try),
          (eq, ":quest_no", "qst_cheese_paladins"),
          (is_between, ":giver_center_no", centers_begin, centers_end),
		  (gt, ":player_level", 14),
          (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",50),
          (val_mul, ":quest_gold_reward", 10),
          (assign, ":quest_expiration_days", 30),
          (assign, ":quest_dont_give_again_period", 30),
          (assign, ":result", ":quest_no"),
# v585 Josef Bar Brawl
        (else_try),
          (eq, ":quest_no", "qst_bar_brawl"),
          (try_begin),
            (ge, "$g_talk_troop_faction_relation", 0),
            (is_between, ":giver_center_no", towns_begin, towns_end),		
            (assign, ":quest_importance", 1),
            (assign, ":quest_xp_reward", 300),
            (assign, ":quest_gold_reward", 500),
            (assign, ":result", ":quest_no"),
            (assign, ":quest_expiration_days", 20), 
            (assign, ":quest_dont_give_again_period", 20), 
          (try_end),
# end v585 Josef		  			  
		# NE end quests	  
			  
			  
	        (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_expiration_days", 15),
	          (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"),
	          (neq, ":giver_center_no", reg0),
	          (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", 30),
	          (assign, ":quest_dont_give_again_period", 20),
	          (assign, ":result", ":quest_no"),
	        (else_try),
	          (eq, ":quest_no", "qst_persuade_lords_to_make_peace"),
	          (is_between, ":giver_center_no", centers_begin, centers_end),
	          (store_faction_of_party, ":cur_object_faction", ":giver_center_no"),
	          (call_script, "script_cf_faction_get_random_enemy_faction", ":cur_object_faction"),
			  # NE dk
			  (neq,reg0,"fac_dark_knights"),
			  # NE end dk
	          (assign, ":cur_target_faction", reg0),
	          (call_script, "script_cf_get_random_lord_except_king_with_faction", ":cur_object_faction"),
	          (assign, ":cur_object_troop", reg0),
			  (this_or_next|troop_slot_eq, ":cur_object_troop", slot_lord_reputation_type, lrep_quarrelsome),
			  (this_or_next|troop_slot_eq, ":cur_object_troop", slot_lord_reputation_type, lrep_selfrighteous),
			  (this_or_next|troop_slot_eq, ":cur_object_troop", slot_lord_reputation_type, lrep_martial),
				(troop_slot_eq, ":cur_object_troop", slot_lord_reputation_type, lrep_debauched),
			  
	          (call_script, "script_cf_get_random_lord_except_king_with_faction", ":cur_target_faction"),
	          (assign, ":quest_target_troop", reg0),
			  (this_or_next|troop_slot_eq, ":quest_target_troop", slot_lord_reputation_type, lrep_quarrelsome),
			  (this_or_next|troop_slot_eq, ":quest_target_troop", slot_lord_reputation_type, lrep_selfrighteous),
			  (this_or_next|troop_slot_eq, ":quest_target_troop", slot_lord_reputation_type, lrep_martial),
			  (troop_slot_eq, ":quest_target_troop", slot_lord_reputation_type, lrep_debauched),
			  			  
	          (assign, ":quest_object_troop", ":cur_object_troop"),
	          (assign, ":quest_target_faction", ":cur_target_faction"),
	          (assign, ":quest_object_faction", ":cur_object_faction"),
	          (assign, ":quest_gold_reward", 12000),
	          (assign, ":quest_convince_value", 7000),
	          (assign, ":quest_expiration_days", 30),
	          (assign, ":quest_dont_give_again_period", 100),
	          (assign, ":result", ":quest_no"),
	        (else_try),
	          (eq, ":quest_no", "qst_deal_with_looters"),
	          (is_between, ":player_level", 0, 15),
	          (is_between, ":giver_center_no", centers_begin, centers_end),
	          (store_faction_of_party, ":cur_object_faction", ":giver_center_no"),
	          (store_num_parties_destroyed_by_player, ":num_looters_destroyed", "pt_looters"),
	          (party_template_set_slot,"pt_looters",slot_party_template_num_killed,":num_looters_destroyed"),
	          (quest_set_slot,":quest_no",slot_quest_current_state,0),
	          (quest_set_slot,":quest_no",slot_quest_target_party_template,"pt_looters"),
	          (assign, ":quest_gold_reward", 500),
	          (assign, ":quest_xp_reward", 500),
	          (assign, ":quest_expiration_days", 20),
	          (assign, ":quest_dont_give_again_period", 30),
	          (assign, ":result", ":quest_no"),
	        (else_try),
	          (eq, ":quest_no", "qst_deal_with_night_bandits"),
	          (is_between, ":player_level", 0, 15),
	          (is_between, ":giver_center_no", centers_begin, centers_end),
	          (party_slot_ge, ":giver_center_no", slot_center_has_bandits, 1),
	          (assign, ":quest_target_center", ":giver_center_no"),
	          (assign, ":quest_expiration_days", 4),
	          (assign, ":quest_dont_give_again_period", 15),
	          (assign, ":result", ":quest_no"),
	        (else_try),
	          # Lady quests
	          (eq, ":quest_no", "qst_rescue_lord_by_replace"),
			  (eq, 1, 0),
	          (try_begin),
	            (ge, "$g_talk_troop_faction_relation", 0),
	            (is_between, ":player_level", 5, 25), 
	            
	            (assign, ":prisoner_relative", -1),
	            
	            (try_begin),
                  (troop_get_slot, ":cur_target_troop", ":giver_troop", slot_troop_father), #get giver_troop's father
	              (gt, ":cur_target_troop", 0), #if giver_troop has a father as a troop in game
                  (troop_slot_ge, ":cur_target_troop", slot_troop_prisoner_of_party, 0), #if giver_troop's father is in a prison
                  (assign, ":prisoner_relative", ":cur_target_troop"),	              
	            (try_end),
	            
	            (try_begin),
	              (eq, ":prisoner_relative", -1), #if giver_troop has no father or giver_troop's father is not in prison.
	              (troop_get_slot, ":cur_target_troop", ":giver_troop", slot_troop_spouse), #get giver_troop's spouse
	              (gt, ":cur_target_troop", 0), #if giver_troop has a spouse as a troop in game	              
                  (troop_slot_ge, ":cur_target_troop", slot_troop_prisoner_of_party, 0), #if giver_troop's spouse is in a prison
	              (assign, ":prisoner_relative", ":cur_target_troop"),
				(try_end),  
				
	            (try_begin),
	              (eq, ":prisoner_relative", -1), #if ((giver_troop has no father) or (giver_troop's father is not in prison)) and ((giver_troop has no spouse) or (giver_troop's spouse is not in prison)).
	              (troop_get_slot, ":cur_target_troop", ":giver_troop", slot_troop_guardian), #get giver_troop's spouse
	              (gt, ":cur_target_troop", 0), #if giver_troop has a guardian as a troop in game	              
                  (troop_slot_ge, ":cur_target_troop", slot_troop_prisoner_of_party, 0), #if giver_troop's guardian is in a prison
	              (assign, ":prisoner_relative", ":cur_target_troop"),
				(try_end),
				
				(try_begin),
				  (eq, "$cheat_mode", 1),
				  (assign, reg0, ":prisoner_relative"),
				  (display_message, "str_prisoner_relative_is_reg0"),
				(try_end),
									            
				(gt, ":prisoner_relative", -1),
	            #(changed 2) no need to this anymore (troop_slot_ge, ":prisoner_relative", slot_troop_prisoner_of_party, 0),
	            (call_script, "script_search_troop_prisoner_of_party", ":prisoner_relative"),
	            (assign, ":cur_target_center", reg0),	            
	            
	            #(changed 3) no need to check only towns anymore (is_between, ":cur_target_center", towns_begin, towns_end),#Skip if he is not in a town
	            (is_between, ":cur_target_center", walled_centers_begin, walled_centers_end), #Skip if he is not in a walled center
	            
	            (assign, ":quest_target_center", ":cur_target_center"),
	            (assign, ":quest_target_troop", ":prisoner_relative"),
	            (assign, ":quest_expiration_days", 30),
	            (assign, ":quest_dont_give_again_period", 73),
	            (assign, ":result", ":quest_no"),
	          (try_end),
	        (else_try),
	          (eq, ":quest_no", "qst_deliver_message_to_prisoner_lord"),
			  (eq, "$player_has_homage", 0),
			  
	          (try_begin),
	            (ge, "$g_talk_troop_faction_relation", 0),
	            (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
				(gt, ":cur_target_troop", -1),
	            (troop_slot_ge, ":cur_target_troop", slot_troop_prisoner_of_party, 0),
	            (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_expiration_days", 30),
	            (assign, ":quest_dont_give_again_period", 30),
	            (assign, ":result", ":quest_no"),
	          (try_end),
# NE quests 
# v585 Josef Quest fight faction leader
        (else_try),
          (eq, ":quest_no", "qst_fight_king"),
          (try_begin),
            (ge, "$g_talk_troop_faction_relation", 0),		
            (ge, ":player_level", 10),
            # Get the leader of the Lady's faction
            (call_script, "script_cf_get_random_kingdom_hero", ":giver_faction_no", slto_kingdom_hero),#Can fail
            (assign, ":cur_target_troop", reg0),
            (neg|troop_slot_eq, ":giver_troop", slot_troop_spouse, ":cur_target_troop"), #must not be in the family
            (neg|troop_slot_eq, ":giver_troop", slot_troop_father, ":cur_target_troop"),
            (neg|troop_slot_ge, ":cur_target_troop", slot_troop_prisoner_of_party, 0),
			# v585 Josef don't give this quest if Duel for Lady is active - fight conflict
			(neg|check_quest_active, "qst_duel_for_lady"),
			# v585 Josef end
            (assign, ":quest_target_troop", ":cur_target_troop"),
            (assign, ":quest_expiration_days", 20), # 30 change this to a longer timeline??
            (assign, ":quest_dont_give_again_period", 50), 
            (assign, ":result", ":quest_no"),
          (try_end),
# v585 Josef Quest deliver portrait
        (else_try),
          (eq, ":quest_no", "qst_deliver_portrait"),
          (try_begin),
            (ge, "$g_talk_troop_faction_relation", 0),
		  # ne swadia
			(neq, ":giver_faction_no", "fac_kingdom_1"),   
		    (assign, ":quest_target_center", "p_town_6"),		
            (assign, ":quest_expiration_days", 10),
            (assign, ":quest_dont_give_again_period", 9999), #never give it again
            (assign, ":result", ":quest_no"),
          (try_end),		  
# v585 Josef deliver love letter for lady
        (else_try),
          (eq, ":quest_no", "qst_deliver_letter"),
          (try_begin),		 
            (ge, "$g_talk_troop_faction_relation", 0),
			(neg|check_quest_active, "qst_deliver_love_letter"),
            (call_script, "script_cf_get_random_lord_in_a_center_with_faction", ":giver_faction_no"),#Can fail
            (assign, ":cur_target_troop", reg0),
			(neg|faction_slot_eq, ":giver_faction_no", slot_faction_leader, ":cur_target_troop"),#Can not love the king (Katilus)
                        (call_script, "script_troop_get_family_relation_to_troop", ":giver_troop", ":cur_target_troop"),
                        (assign, ":family_relation", reg0),
                        (neg|gt, ":family_relation", 0), # Don't send love letters to any family members (make this less aggressive later, once I know what the return value from get_family_relation means)
            #(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", 100),
            (assign, ":quest_gold_reward", 140),
            (assign, ":result", ":quest_no"),    
			(assign, ":quest_dont_give_again_period", 20),
            (assign, ":quest_expiration_days", 30),
          (try_end),		 		  
# v585 Josef deliver love letter for lord
        (else_try),
          (eq, ":quest_no", "qst_deliver_love_letter"),
          (try_begin),          
            (ge, "$g_talk_troop_faction_relation", 0),
			(neg|check_quest_active, "qst_deliver_letter"),
# don't want it to be the King/Queen (Katilus)
# note
#(troop_slot_ge, ":cur_troop", slot_troop_spouse, 1),
# end note
			(neg|faction_slot_eq, ":giver_faction_no", slot_faction_leader, "$g_talk_troop"),
            (call_script, "script_cf_get_random_lady_in_a_center_with_faction", ":giver_faction_no"),#Can fail
			(assign, ":cur_target_troop", reg0),
                        	(call_script, "script_troop_get_family_relation_to_troop", ":giver_troop", ":cur_target_troop"),
	                        (assign, ":family_relation", reg0),
#        	                (display_message, "@{!}DEBUG : reg0 is: {reg0}"),
	                        (neg|gt, ":family_relation", 0), # Don't send love letters to any family members (make this less aggressive later, once I know what the return value from get_family_relation means)
            (troop_get_slot, ":wife_target_troop", ":giver_troop", slot_troop_spouse),
			# (str_store_troop_name,s1,":wife_target_troop"),
			# (str_store_troop_name,s2,":cur_target_troop"),
		  # debugging, can't be the lord's wife. Check this here
          # (display_message,"@Target {s1} Giver {s2}."),
			
			(try_begin),
			(neq, ":wife_target_troop", ":cur_target_troop"),
            (assign, ":quest_target_troop", ":cur_target_troop"),
            (assign, ":quest_xp_reward", 300),
            (assign, ":quest_gold_reward", 400),
            (assign, ":result", ":quest_no"),
            (assign, ":quest_dont_give_again_period", 30), 
			# commented in case lady isn't easily findable (hidden)
            # (assign, ":quest_expiration_days", 30),
			(try_end),
          (try_end),
# end v585 Josef


# ne end quests			  
			  
			  
	        (else_try),
	          (eq, ":quest_no", "qst_duel_for_lady"),
	          (try_begin),
	            (ge, "$g_talk_troop_faction_relation", 0),
	            (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),
	            (neg|troop_slot_eq, ":giver_troop", slot_troop_spouse, ":cur_target_troop"), #must not be in the family
	            (neg|troop_slot_eq, ":giver_troop", slot_troop_father, ":cur_target_troop"),	            
	            (neg|troop_slot_ge, ":cur_target_troop", slot_troop_prisoner_of_party, 0),
	            (troop_slot_ge, ":cur_target_troop", slot_troop_leaded_party, 0),
	            (neg|troop_slot_eq, ":cur_target_troop", slot_lord_reputation_type, lrep_goodnatured),
	            (neg|troop_slot_eq, ":cur_target_troop", slot_lord_reputation_type, lrep_upstanding),
			# NE quests	
			# v585 Josef don't give this quest if Fight King is active - fight conflict
			(neg|check_quest_active, "qst_fight_king"),
			# v585 Josef end
			# NE End quests 
			
	            (neg|troop_slot_eq, ":cur_target_troop", slot_lord_reputation_type, lrep_martial),
				
	            (assign, ":quest_target_troop", ":cur_target_troop"),
	            (assign, ":quest_expiration_days", 30),
	            (assign, ":quest_dont_give_again_period", 50),
	            (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)
	            (neq, ":giver_reputation", lrep_quarrelsome),
	            (neq, ":giver_reputation", lrep_debauched),
	            (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_meet_spy_in_enemy_town"),
			  (eq, "$player_has_homage", 0),
			  
	          (try_begin),
	            (eq, "$players_kingdom", ":giver_faction_no"),
	            (neq, ":giver_reputation", lrep_goodnatured),
	            (neq, ":giver_reputation", lrep_martial),
				
	            (call_script, "script_troop_get_player_relation", ":giver_troop"),
	            (assign, ":giver_relation", reg0),
	            (gt, ":giver_relation", 3),
	            (call_script, "script_cf_faction_get_random_enemy_faction", ":giver_faction_no"),
	            (assign, ":enemy_faction", reg0),
	            (store_relation, ":reln", ":enemy_faction", "fac_player_supporters_faction"),
	            (lt, ":reln", 0),
	            (call_script, "script_cf_select_random_town_with_faction", ":enemy_faction"),
	            (assign, ":cur_target_center", reg0),
	            #Just to make sure that there is a free walker
	            (call_script, "script_cf_center_get_free_walker", ":cur_target_center"),
	            (assign, ":quest_target_center", ":cur_target_center"),
	            (store_random_in_range, ":quest_target_amount", secret_signs_begin, secret_signs_end),
	            (assign, ":result", ":quest_no"),
	            (assign, ":quest_gold_reward", 500),
	            (assign, ":quest_expiration_days", 30),
	            (assign, ":quest_dont_give_again_period", 50),
	            (quest_set_slot, "qst_meet_spy_in_enemy_town", slot_quest_gold_reward, 500),
	          (try_end),
	        (else_try),
	          (eq, ":quest_no", "qst_raid_caravan_to_start_war"),
			  (eq, 1, 0), #disable this as a random quest
			  
	          (try_begin),
	            (eq, "$players_kingdom", ":giver_faction_no"),
	            (this_or_next|eq, ":giver_reputation", lrep_cunning),
	            (this_or_next|eq, ":giver_reputation", lrep_quarrelsome),
	            (             eq, ":giver_reputation", lrep_debauched),
	            (gt, ":player_level", 10),
				(eq, 1, 0), #disable this as a random quest
				
	            (neg|faction_slot_eq, ":giver_faction_no", slot_faction_leader, ":giver_troop"),#Can not take the quest from the king
	            (call_script, "script_cf_faction_get_random_friendly_faction", ":giver_faction_no"),#Can fail
	            (assign, ":quest_target_faction", reg0),
	            (store_troop_faction, ":quest_object_faction", ":giver_troop"),
	            (assign, ":quest_target_party_template", "pt_kingdom_caravan_party"),
	            (assign, ":quest_target_amount", 2),
	            (assign, ":result", ":quest_no"),
	            (assign, ":quest_expiration_days", 30),
	            (assign, ":quest_dont_give_again_period", 100),
	          (try_end),
	        (else_try),
	          (eq, ":quest_no", "qst_deliver_message"),
			  (eq, "$player_has_homage", 0),
			  
	          (try_begin),
	            (ge, "$g_talk_troop_faction_relation", 0),
	            (lt, ":player_level", 20), 
			    (neg|troop_slot_ge, "trp_player", slot_troop_renown, 125),
	            (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, ":quest_dont_give_again_period", 10),
				
	            (assign, ":result", ":quest_no"),
	      
	            (assign, ":quest_expiration_days", 30),
	          (try_end),
	        (else_try),
	          (eq, ":quest_no", "qst_escort_lady"),
	          (try_begin),
	            (ge, "$g_talk_troop_faction_relation", 0),
	            (ge, ":player_level", 10),

                                (ge, ":giver_troop", 0), #skip troops without fathers in range

                                (assign, ":cur_object_troop", -1),
                 (try_for_range, ":lady", kingdom_ladies_begin, kingdom_ladies_end),
                                 (troop_slot_eq, ":lady", slot_troop_father, ":giver_troop"),
                                  (assign, ":cur_object_troop", ":lady"),
                                (try_end),
 
                                (ge, ":cur_object_troop", 0),

                               (troop_get_slot, ":giver_troop_confirm", ":cur_object_troop", slot_troop_father),  # just to make sure
                               (eq, ":giver_troop", ":giver_troop_confirm"), # just to make sure

				
	            (troop_get_slot, ":giver_troop", ":cur_object_troop", slot_troop_father),
				(gt, ":giver_troop", -1), #skip troops without fathers in range
	            (store_random_in_range, ":random_no", 0, 2),
	            (try_begin),
	              (eq, ":random_no", 0),
	              (troop_get_slot, ":cur_object_troop_2", ":giver_troop", slot_troop_spouse),
                                  (is_between, ":cur_object_troop_2", kingdom_ladies_begin, kingdom_ladies_end),
                                  (troop_get_slot, ":giver_troop_confirm", ":cur_object_troop_2", slot_troop_spouse),  # just to make sure
                                  (eq, ":giver_troop", ":giver_troop_confirm"), # just to make sure

	              (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_expiration_days", 20),
	            (assign, ":quest_dont_give_again_period", 30),
	            (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),
	            (ge, "$g_talk_troop_faction_relation", 0),
	            (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_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_deal_with_bandits_at_lords_village"),
	          (try_begin),
			    
	            (neq, ":giver_reputation", lrep_debauched), 
	            (neq, ":giver_reputation", lrep_quarrelsome), 
	            (ge, "$g_talk_troop_faction_relation", 0),
	            (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),
	              (party_slot_eq, ":cur_village", slot_village_state, svs_normal),
	              (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),
	            (neq, ":giver_reputation", lrep_martial),
	            (neq, ":giver_faction_no", "fac_player_supporters_faction"), #we need tier_1_troop a valid value
	            (ge, "$g_talk_troop_faction_relation", 0),
	            (store_character_level, ":cur_level", "trp_player"),
	            (gt, ":cur_level", 5),
	            (troop_slot_ge, "trp_player", slot_troop_renown, 100),
	             
	            (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"),
	            (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),
			 # NE quests 
			 #v585 Josef Raise Peasants
       (else_try),
	   
         (eq, ":quest_no", "qst_raise_peasants"),
		 
         (try_begin),
           # (neq, ":giver_faction_no", "fac_dark_knights"),
           (ge, "$g_talk_troop_faction_relation", 0),
		   # only give it at castle or center
		   (eq, "$talk_context", tc_court_talk),
		   (neg|faction_slot_eq, ":giver_faction_no", slot_faction_leader, ":giver_troop"),#Can not take the quest from the king
           (store_character_level, ":cur_level", "trp_player"),
           (gt, ":cur_level", 5),				
            (store_random_in_range, ":quest_target_amount", 6, 18),
            (assign, ":quest_target_troop", "trp_peasant_woman"),
            (store_mul, ":quest_gold_reward", ":quest_target_amount", 30),
            (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", 20),
            (assign, ":quest_dont_give_again_period", 30),
          (try_end),
#v585 Josef deliver wine to Lord
       (else_try),
         (eq, ":quest_no", "qst_party"),
		 
         (try_begin),
           # (neq, ":giver_faction_no", "fac_dark_knights"),
           (ge, "$g_talk_troop_faction_relation", 0),
		   (neg|faction_slot_eq, ":giver_faction_no", slot_faction_leader, ":giver_troop"),#Can not take the quest from the king
           (store_character_level, ":cur_level", "trp_player"),
           (gt, ":cur_level", 10),			
            (store_random_in_range, ":quest_target_amount", 3, 7),
            (store_mul, ":quest_gold_reward", ":quest_target_amount", 200),
            (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", 15),
            (assign, ":quest_dont_give_again_period", 30),
          (try_end),
#v585 Josef Kill Elites
       (else_try),
         (eq, ":quest_no", "qst_kill_elites"),
         (try_begin),
		   (neq, ":giver_faction_no", "fac_dark_knights"),
           (ge, "$g_talk_troop_faction_relation", 20),
		   (faction_slot_eq, ":giver_faction_no", slot_faction_leader, ":giver_troop"),#Can only take the quest from the king
           (store_character_level, ":cur_level", "trp_player"),
		   (gt, ":cur_level", 9), 
		   (try_begin),
		     (eq, ":giver_faction_no", "fac_kingdom_1"),
			 (eq, "$fac_kingdom_1_elite", 0), 
			 (assign, ":quest_target_item", "itm_2hand_swadian_regent"),
			 (assign, "$elite_faction",  "fac_kingdom_1"),	
          (assign, ":result", ":quest_no"),			 
			(else_try),
		     (eq, ":giver_faction_no", "fac_kingdom_2"),
			  (eq, "$fac_kingdom_2_elite", 0), 
			 (assign, ":quest_target_item", "itm_varangian_axe"),
			 (assign, "$elite_faction",  "fac_kingdom_2"),	
          (assign, ":result", ":quest_no"),			 
			(else_try),			
		     (eq, ":giver_faction_no", "fac_kingdom_3"),
			  (eq, "$fac_kingdom_3_elite", 0), 
			 (assign, ":quest_target_item", "itm_tulgan_bow"),
			 (assign, "$elite_faction",  "fac_kingdom_3"),	   
          (assign, ":result", ":quest_no"),			 
			(else_try),			
		     (eq, ":giver_faction_no", "fac_kingdom_4"),
			  (eq, "$fac_kingdom_4_elite", 0), 
			 (assign, ":quest_target_item", "itm_nordhammerb"),
			 (assign, "$elite_faction",  "fac_kingdom_4"),	
          (assign, ":result", ":quest_no"),			 
			(else_try),			
		     (eq, ":giver_faction_no", "fac_kingdom_5"),
			  (eq, "$fac_kingdom_5_elite", 0), 
			 (assign, ":quest_target_item", "itm_da_veidar_mark_4"),
			 (assign, "$elite_faction",  "fac_kingdom_5"),		
          (assign, ":result", ":quest_no"),	
			(else_try),			
		     (eq, ":giver_faction_no", "fac_kingdom_6"),
			  (eq, "$fac_kingdom_6_elite", 0), 
			 (assign, ":quest_target_item", "itm_jewelled_kilij"),
			 (assign, "$elite_faction",  "fac_kingdom_6"),		
          (assign, ":result", ":quest_no"),			  
			(try_end),			
		  # no expiry date- if player doesn't kill elites, then quest continues
          #(assign, ":quest_expiration_days", 3), 
          (assign, ":quest_dont_give_again_period", 1), #quest available from next king after 1 day
#          (assign, ":result", ":quest_no"),
		   (try_end),
#end v585 Josef
			 
			 
			 
			 # NE end quests 
	        (else_try),
	          (eq, ":quest_no", "qst_collect_taxes"),
			  (eq, "$player_has_homage", 0),
			  
	          (try_begin),
	            (neq, ":giver_reputation", lrep_goodnatured),
	            (neq, ":giver_reputation", lrep_upstanding),
	            (ge, "$g_talk_troop_faction_relation", 0),
	            (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),
	            (ge, "$g_talk_troop_faction_relation", 0),
	            (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),
	            (assign, ":result", ":quest_no"),
	            (assign, ":quest_expiration_days", 30),
	            (assign, ":quest_dont_give_again_period", 30),
	          (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"),
			 
			  (eq, "$player_has_homage", 0),
			  
	          (try_begin),
	            (this_or_next|eq, ":giver_reputation", lrep_quarrelsome),
	            (this_or_next|eq, ":giver_reputation", lrep_cunning),
	            (             eq, ":giver_reputation", lrep_debauched),
	            (neg|faction_slot_eq, ":giver_faction_no", slot_faction_leader, ":giver_troop"),#Can not take the quest from the king
	            (ge, "$g_talk_troop_faction_relation", 0),
	            (gt, ":player_level", 5),
	            (is_between, ":giver_center_no", towns_begin, towns_end),
	            (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),
	            (neq, ":giver_reputation", lrep_goodnatured),
	            (neq, ":giver_reputation", lrep_upstanding),
	            (ge, "$g_talk_troop_faction_relation", 0),
	            (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_follow_spy"),
			  (eq, "$player_has_homage", 0),
			  
	          (try_begin),
	            (ge, "$g_talk_troop_faction_relation", 0),
	            (neq, ":giver_reputation", lrep_goodnatured),
	            (party_get_skill_level, ":tracking_skill", "p_main_party", "skl_tracking"),
	            (ge, ":tracking_skill", 2),
	            (ge, ":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),
                    (assign, ":cur_object_center", -1),
	            (try_for_range, ":unused_2", 0, 10),
	              (call_script, "script_cf_get_random_enemy_center", ":giver_party_no"),
	              (assign, ":random_object_center", reg0),
	              (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_dont_give_again_period", 50),
	            (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),
	            (assign, "$qst_follow_spy_no_active_parties", 0),
	          (try_end),
	        (else_try),
	          (eq, ":quest_no", "qst_capture_enemy_hero"),
	          (try_begin),
	            (eq, "$players_kingdom", ":giver_faction_no"),
	            (neg|faction_slot_eq, "$players_kingdom", slot_faction_marshall, "trp_player"),
	            (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_expiration_days", 30),
	            (assign, ":quest_dont_give_again_period", 80),
	            (assign, ":quest_gold_reward", 2000),
	            (assign, ":result", ":quest_no"),
	          (try_end),
	        (else_try),
	          (eq, ":quest_no", "qst_lend_companion"),
	          (try_begin),
	            (ge, "$g_talk_troop_faction_relation", 0),
	            (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"),
	              (is_between, ":stack_troop", companions_begin, companions_end),
	              (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"),
	              (is_between, ":stack_troop", companions_begin, companions_end),
	              (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),
	            (is_between, ":cur_target_troop", companions_begin, companions_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"),
			  (eq, 1, 0), #disable this quest pending talk with armagan
	          (try_begin),
	            (ge, "$g_talk_troop_faction_relation", 0),
	          # 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_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"),
			  (eq, "$player_has_homage", 0),
			  
	          (try_begin),
	            (neq, ":giver_reputation", lrep_upstanding),
	            (neq, ":giver_reputation", lrep_goodnatured),
	            (eq, "$players_kingdom", ":giver_faction_no"),
	            (ge, ":player_level", 10),
	            (faction_slot_eq, ":giver_faction_no", slot_faction_leader, ":giver_troop"),
	            (assign, ":try_times", 1),
	            (assign, ":found", 0),
	            (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, ":cur_target_troop", ":cur_target_faction", slot_faction_leader),
	              (assign, ":num_centerless_heroes", 0),
	              (try_for_range, ":cur_kingdom_hero", active_npcs_begin, active_npcs_end),
	                (troop_slot_eq, ":cur_kingdom_hero", slot_troop_occupation, slto_kingdom_hero),
	                #(troop_slot_eq, ":cur_kingdom_hero", slot_troop_is_prisoner, 0),
	                (neg|troop_slot_ge, ":cur_kingdom_hero", slot_troop_prisoner_of_party, 0),
	                (neq, ":cur_target_troop", ":cur_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),
	              (try_end),
	              (gt, ":num_centerless_heroes", 0),
	              (assign, ":cur_object_troop", -1),
	              (store_random_in_range, ":random_kingdom_hero", 0, ":num_centerless_heroes"),
	              (try_for_range, ":cur_kingdom_hero", active_npcs_begin, active_npcs_end),
	                (eq, ":cur_object_troop", -1),
	                (troop_slot_eq, ":cur_kingdom_hero", slot_troop_occupation, slto_kingdom_hero),
	                (neq, ":cur_target_troop", ":cur_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_sub, ":random_kingdom_hero", 1),
	                (lt, ":random_kingdom_hero", 0),
	                (assign, ":cur_object_troop", ":cur_kingdom_hero"),
	              (try_end),

	              (assign, ":cur_target_center", -1),
	              (call_script, "script_get_troop_attached_party", ":cur_target_troop"),
	              (is_between, reg0, towns_begin, towns_end),
	              (party_slot_eq, reg0, slot_town_lord, ":cur_target_troop"),
	              (assign, ":cur_target_center", reg0),

	              (assign, ":try_times", -1),#Exit the second loop
	              (assign, ":found", 1),
	            (try_end),
	            (eq, ":found", 1),

	            (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_target_troop", ":cur_target_troop"),
	            (assign, ":quest_object_troop", ":cur_object_troop"),
	            (assign, ":quest_target_center", ":cur_target_center"),
	            (assign, ":quest_target_faction", ":cur_target_faction"),

	            (assign, ":quest_importance", 1),
	            (assign, ":quest_xp_reward", 700),
	            (assign, ":quest_gold_reward", 1000),
	            (assign, ":result", ":quest_no"),
	            (assign, ":quest_expiration_days", 30),
	            (assign, ":quest_dont_give_again_period", 180),
	          (try_end),
	        (else_try),
	          (eq, ":quest_no", "qst_capture_prisoners"),
			  (eq, "$player_has_homage", 0),
			  
	          (try_begin),
	            (eq, "$players_kingdom", ":giver_faction_no"),
	            (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_2_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_end),
	  #end of quest finding
	  	  	  
	  
      (try_begin),
        (neq, ":result", -1),
        
        (try_begin),
          (party_is_active, ":quest_target_center"),
          (store_faction_of_party, ":quest_target_faction", ":quest_target_center"),
        (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_faction, ":quest_target_faction"),
        (quest_set_slot, ":result", slot_quest_object_faction, ":quest_object_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"),
  ]),
  
  ("get_dynamic_quest",
  #Dynamic quests are rarer, more important quests
  #this is a separate script from get_quest, so that tavern keepers can scan all NPCs for quests 
    [
    (store_script_param_1, ":giver_troop"),
	
	(assign, ":result", -1),
	(assign, ":relevant_troop", -1),
	(assign, ":relevant_party", -1),
	(assign, ":relevant_faction", -1),
		
	(try_begin),
		(eq, ":giver_troop", -1),
		
	(else_try),
		#1 rescue prisoner		
		(neg|check_quest_active, "qst_rescue_prisoner"),
		(this_or_next|troop_slot_eq, ":giver_troop", slot_troop_occupation, slto_kingdom_hero),
			(troop_slot_eq, ":giver_troop", slot_troop_occupation, slto_kingdom_lady),

		(assign, ":target_troop", -1),	
		(try_for_range, ":possible_prisoner", active_npcs_begin, active_npcs_end),	
			(troop_get_slot, ":captor_location", ":possible_prisoner", slot_troop_prisoner_of_party),
			(is_between, ":captor_location", walled_centers_begin, walled_centers_end),
			(store_troop_faction, ":giver_troop_faction_no", ":giver_troop"),
			(store_faction_of_party, ":captor_location_faction_no", ":captor_location"),
			(store_relation, ":giver_captor_relation", ":giver_troop_faction_no", ":captor_location_faction_no"),
			(lt, ":giver_captor_relation", 0),
			
			(call_script, "script_troop_get_family_relation_to_troop", ":giver_troop", ":possible_prisoner"), 
			(ge, reg0, 10),
			
			(assign, ":offered_parole", 0),
			(try_begin),
				(call_script, "script_cf_prisoner_offered_parole", ":possible_prisoner"),
				(assign, ":offered_parole", 1),
			(try_end),
			(eq, ":offered_parole", 0),
			
			(neg|party_slot_eq, ":captor_location", slot_town_lord, "trp_player"),
			
			(assign, ":target_troop", ":possible_prisoner"),
			(assign, ":target_party", ":captor_location"),
		(try_end),

		(gt, ":target_troop", -1),
		(assign, ":result", "qst_rescue_prisoner"),
		(assign, ":relevant_troop", ":target_troop"),
		(assign, ":relevant_party", ":target_party"),
		
	(else_try),
		#2 retaliate for border incident
		(is_between, ":giver_troop", mayors_begin, mayors_end),
		(store_faction_of_troop, ":giver_faction", ":giver_troop"),
		
		(neg|check_quest_active, "qst_retaliate_for_border_incident"),
		(quest_slot_eq, "qst_retaliate_for_border_incident", slot_quest_dont_give_again_remaining_days, 0),
		(assign, ":target_leader", 0),
  
		(try_for_range, ":kingdom", "fac_kingdom_1", kingdoms_end),
			(call_script, "script_diplomacy_faction_get_diplomatic_status_with_faction", ":giver_faction", ":kingdom"),
			(assign, ":diplomatic_status", reg0),
			(eq, ":diplomatic_status", -1),
			(assign, ":duration", reg1),
			(ge, ":duration", 10),
			
			
			(try_for_range, ":lord", active_npcs_begin, active_npcs_end),
				(store_faction_of_troop, ":lord_faction", ":lord"),
				(eq, ":lord_faction", ":kingdom"),
		
				(troop_slot_eq, ":lord", slot_lord_reputation_type, lrep_debauched),
				
				(assign, ":target_leader", ":lord"),
				(assign, ":target_faction", ":kingdom"),
			(try_end),
		(try_end),
		(is_between, ":target_leader", active_npcs_begin, active_npcs_end),
		
		(assign, ":result", "qst_retaliate_for_border_incident"),
		(assign, ":relevant_troop", ":target_leader"),  
		(assign, ":relevant_faction", ":target_faction"),  
	(else_try), #Find bandit hideout
		(troop_slot_eq, ":giver_troop", slot_troop_occupation, slto_kingdom_hero),
		(neg|check_quest_active, "qst_destroy_bandit_lair"),
		(quest_slot_eq, "qst_destroy_bandit_lair", slot_quest_dont_give_again_remaining_days, 0),

#		(display_message, "@Checking for bandit lair quest"),
				
		(assign, ":lair_found", -1),
		
		(try_for_range, ":bandit_template", "pt_steppe_bandits", "pt_deserters"),
			(party_template_get_slot, ":bandit_lair", ":bandit_template", slot_party_template_lair_party),
						
			#No party is active because bandit lairs are removed as soon as they are attacked, by the player -- but can only be removed by the player. This will reset bandit lair to zero
			(gt, ":bandit_lair", "p_spawn_points_end"),
			
			(assign, ":closest_town", -1),
			(assign, ":score_to_beat", 99999),
			
			(try_for_range, ":town_no", towns_begin, towns_end),
				(store_distance_to_party_from_party, ":distance", ":bandit_lair", ":town_no"),
				(lt, ":distance", ":score_to_beat"),
				(assign, ":closest_town", ":town_no"),
				(assign, ":score_to_beat", ":distance"),
			(try_end),
			
			#(str_store_party_name, s7, ":closest_town"),
			#(party_get_slot, ":closest_town_lord", ":closest_town", slot_town_lord),						
			#(str_store_troop_name, s8, ":closest_town_lord"),						
			
			(party_slot_eq, ":closest_town", slot_town_lord, ":giver_troop"),
			(assign, ":lair_found", ":bandit_lair"),
		(try_end),
		
		(gt, ":lair_found", "p_spawn_points_end"),
		
		(assign ,":result", "qst_destroy_bandit_lair"),
		(assign, ":relevant_party", ":lair_found"),  						  
	(else_try),  #3 - bounty on bandit party
		(is_between, ":giver_troop", mayors_begin, mayors_end),
		(neg|check_quest_active, "qst_track_down_bandits"),
		(quest_slot_eq, "qst_track_down_bandits", slot_quest_dont_give_again_remaining_days, 0),

		(assign, ":cur_town", -1),
		(try_for_range, ":town", towns_begin, towns_end),
			(party_slot_eq, ":town", slot_town_elder, ":giver_troop"),
			(assign, ":cur_town", ":town"),
		(try_end),
		(gt, ":cur_town", -1),
		
		(call_script, "script_merchant_road_info_to_s42", ":cur_town"), 
		(assign, ":bandit_party_found", reg0),
		(party_is_active, ":bandit_party_found"),
		(gt, ":bandit_party_found", 0),

        (try_begin),
            (eq, "$cheat_mode", 1),
            (display_message, "str_traveller_attack_found"),
        (try_end),
		
		(assign ,":result", "qst_track_down_bandits"),
		(assign, ":relevant_party", ":bandit_party_found"),  
	(else_try),  #raid a caravan to start war
		(troop_slot_eq, ":giver_troop", slot_lord_reputation_type, lrep_debauched),
		(store_faction_of_troop, ":giver_troop_faction", ":giver_troop"),
		
		(assign, ":junior_debauched_lord_in_faction", -1),
		(try_for_range, ":lord_in_faction", active_npcs_begin, active_npcs_end),
			(troop_slot_eq, ":lord_in_faction", slot_lord_reputation_type, lrep_debauched),
			(store_faction_of_troop, ":debauched_lord_faction", ":lord_in_faction"),
			(eq, ":debauched_lord_faction", ":giver_troop_faction"),
			(assign, ":junior_debauched_lord_in_faction", ":lord_in_faction"),
		(try_end),
		(eq, ":giver_troop", ":junior_debauched_lord_in_faction"),
		
		(assign, ":faction_to_attack", 0),
		(assign, ":faction_to_attack_score", 0),
		
	    (try_for_range, ":faction_candidate", kingdoms_begin, kingdoms_end),
			(neq, ":faction_to_attack", -1),
			(neq, ":faction_candidate", ":giver_troop_faction"),
			(faction_slot_eq, ":faction_candidate", slot_faction_state, sfs_active),
			(neq, ":faction_candidate", "$players_kingdom"),

			(store_relation, ":relation", ":faction_candidate", ":giver_troop_faction"),
			
			(store_add, ":provocation_slot", ":giver_troop_faction", slot_faction_provocation_days_with_factions_begin),
			(val_sub, ":provocation_slot", kingdoms_begin),				
			(faction_get_slot, ":provocation_days", ":faction_candidate", ":provocation_slot"),
			
			(try_begin),
				(lt, ":relation", 0),
				(assign, ":faction_to_attack", -1), #disqualifies if thefaction is already at war
			(else_try),
				(ge, ":provocation_days", 1),
				(assign, ":faction_to_attack", -1), #disqualifies if the faction has already provoked someone
			(else_try),
				(ge, ":relation", 0),
				(assign, ":faction_to_attack_temp_score", 2),
				#add in scores - no truce?
				
#				(store_add, ":truce_slot", ":giver_troop_faction", slot_faction_truce_days_with_factions_begin),
#				(store_add, ":provocation_slot", ":giver_troop_faction", slot_faction_provocation_days_with_factions_begin),
#				(val_sub, ":truce_slot", kingdoms_begin),
#				(val_sub, ":provocation_slot", kingdoms_begin),				
#				(faction_slot_eq, ":faction_candidate", ":provocation_slot", 0),
#				(try_begin),
#					(faction_slot_ge, ":faction_candidate", ":truce_slot", 1),
#					(val_sub, ":faction_to_attack_temp_score", 1),
#				(try_end),
				
				(gt, ":faction_to_attack_temp_score", ":faction_to_attack_score"),
				
				(assign, ":faction_to_attack", ":faction_candidate"),
				(assign, ":faction_to_attack_temp_score", ":faction_to_attack_score"),
			(try_end),	
	    (try_end),
		
		(is_between, ":faction_to_attack", kingdoms_begin, kingdoms_end),
		
		(assign ,":result", "qst_cause_provocation"),
		(assign, ":relevant_faction", ":faction_to_attack"),  
		
	(try_end),  
  
    (assign, reg0, ":result"),
    (assign, reg1, ":relevant_troop"),
    (assign, reg2, ":relevant_party"),
    (assign, reg3, ":relevant_faction"),
  
    ]),  
  
  ("get_political_quest", 
  #Political quests are given by the player's political "coach" -- ie, a spouse or the minister -- to improve standing in the faction
  [
	(store_script_param, ":giver_troop", 1),
  
	(assign, ":result", -1),
	(assign, ":quest_target_troop", -1),
	(assign, ":quest_object_troop", -1),
	(assign, ":quest_dont_give_again_period", 7), #one week on average
	
	
	
	(try_begin), #this for kingdom hero, "we have a mutual enemy"
		(neg|check_quest_active, "qst_denounce_lord"),
		(try_begin),
			(ge, "$cheat_mode", 1),
			(quest_get_slot, reg4, "qst_denounce_lord", slot_quest_dont_give_again_remaining_days),
			(display_message, "@{!}DEBUG -- Checking for denounce lord, eligible in {reg4} days"),
		(try_end),	
		
		(neg|quest_slot_ge, "qst_denounce_lord", slot_quest_dont_give_again_remaining_days, 1),
		(neq, ":giver_troop", "$g_player_minister"),
		(neg|troop_slot_eq, "trp_player", slot_troop_spouse, ":giver_troop"),
		(neg|faction_slot_eq, "$players_kingdom", slot_faction_leader, "trp_player"),


#		(neg|troop_slot_eq, "$g_talk_troop", slot_lord_reputation_type, lrep_martial),
		(neg|troop_slot_eq, "$g_talk_troop", slot_lord_reputation_type, lrep_quarrelsome),
		(neg|troop_slot_eq, "$g_talk_troop", slot_lord_reputation_type, lrep_goodnatured),
		
#		(neg|troop_slot_ge, "trp_player", slot_troop_controversy, 10),
		
		
		(assign, ":target_lord", -1),
		(assign, ":score_to_beat", 1),
		
		(try_for_range, ":potential_target", active_npcs_begin, active_npcs_end),
			(store_faction_of_troop, ":potential_target_faction", ":potential_target"),
			(eq, ":potential_target_faction", "$players_kingdom"),
			(neq, ":potential_target", ":giver_troop"),
			(neg|faction_slot_eq, ":potential_target_faction", slot_faction_leader, ":potential_target"),
			
			#cannot denounce if you also have an intrigue against lord active
			(this_or_next|neg|check_quest_active, "qst_intrigue_against_lord"),
				(neg|quest_slot_eq, "qst_intrigue_against_lord", slot_quest_target_troop, ":potential_target"),

			(call_script, "script_troop_get_relation_with_troop", ":potential_target", ":giver_troop"),
			(assign, ":relation_with_giver_troop", reg0),
			(lt, ":relation_with_giver_troop", ":score_to_beat"),
			
			(str_store_troop_name, s4, ":potential_target"),
			(try_begin),
				(ge, "$cheat_mode", 1),
				(display_message, "@{!}DEBUG -- Rival found in {s4}"),
			(try_end),			
			
			(try_begin),
				(troop_slot_eq, "$g_talk_troop", slot_lord_reputation_type, lrep_debauched),
				(assign, ":max_rel_w_player", 15),
			(else_try),
				(troop_slot_eq, "$g_talk_troop", slot_lord_reputation_type, lrep_quarrelsome),
				(assign, ":max_rel_w_player", 10),
			(else_try),
				(assign, ":max_rel_w_player", 5),
			(try_end),
			
			(call_script, "script_troop_get_relation_with_troop", ":potential_target", "trp_player"),
			(assign, ":relation_with_player", reg0),
			(lt, ":relation_with_player", ":max_rel_w_player"),
	
			(str_store_troop_name, s4, ":potential_target"),
			(try_begin),
				(ge, "$cheat_mode", 1),
				(display_message, "@{!}DEBUG -- {s4} is not close friend of player"),
			(try_end),			

			(assign, ":enemies_in_faction", 0),
			(try_for_range, ":other_lord", active_npcs_begin, active_npcs_end),
				(store_faction_of_troop, ":other_lord_faction", ":other_lord"),
				(eq, ":other_lord_faction", "$players_kingdom"),
				(call_script, "script_troop_get_relation_with_troop", ":potential_target", ":other_lord"),
				(lt, reg0, 0),
				(val_add, ":enemies_in_faction", 1),
			(try_end),

			(str_store_troop_name, s4, ":potential_target"),
			(try_begin),
				(ge, "$cheat_mode", 1),
				(assign, reg3, ":enemies_in_faction"),
				(display_message, "@{!}DEBUG -- {s4} has {reg3} rivals"),
			(try_end),						

			(this_or_next|ge, ":enemies_in_faction", 3),
				(ge, "$cheat_mode", 1),
			
			(assign, ":score_to_beat", ":relation_with_giver_troop"),
			(assign, ":target_lord", ":potential_target"),
		(try_end),

		(is_between, ":target_lord", active_npcs_begin, active_npcs_end),
		
		
		(assign, ":result", "qst_denounce_lord"),
		(assign, ":quest_target_troop", ":target_lord"),

	(else_try),
		(neg|check_quest_active, "qst_intrigue_against_lord"),
		(try_begin),
			(eq, "$cheat_mode", 1),
			(quest_get_slot, reg4, "qst_intrigue_against_lord", slot_quest_dont_give_again_remaining_days),
			(display_message, "@{!}DEBUG -- Checking for intrigue, eligible in {reg4} days"),
		(try_end),		
		
		(neg|quest_slot_ge, "qst_intrigue_against_lord", slot_quest_dont_give_again_remaining_days, 1),
		

		
		(neq, ":giver_troop", "$g_player_minister"),
		(neg|troop_slot_eq, "trp_player", slot_troop_spouse, ":giver_troop"),
		(neg|faction_slot_eq, "$players_kingdom", slot_faction_leader, "trp_player"),

		(try_begin),
			(ge, "$cheat_mode", 1),
			(display_message, "@{!}DEBUG -- Trying for intrigue against lord"),
		(try_end),

		
		(assign, ":target_lord", -1),
		(assign, ":score_to_beat", 10),
		
		(try_for_range, ":potential_target", active_npcs_begin, active_npcs_end),
			(store_faction_of_troop, ":potential_target_faction", ":potential_target"),
			(eq, ":potential_target_faction", "$players_kingdom"),
			(neq, ":potential_target", ":giver_troop"),
			(neg|faction_slot_eq, ":potential_target_faction", slot_faction_leader, ":potential_target"),
			
			
			(this_or_next|neg|check_quest_active, "qst_denounce_lord"),
				(neg|quest_slot_eq, "qst_denounce_lord", slot_quest_target_troop, ":potential_target"),

			(faction_get_slot, ":faction_liege", "$players_kingdom", slot_faction_leader),
			(call_script, "script_troop_get_relation_with_troop", ":potential_target", ":faction_liege"),
			(assign, ":relation_with_liege", reg0),
			(lt, ":relation_with_liege", ":score_to_beat"),

			(str_store_troop_name, s4, ":potential_target"),
			(try_begin),
				(ge, "$cheat_mode", 1),
				(display_message, "@{!}DEBUG -- {s4} has sufficiently low relation with liege"),
			(try_end),			

			
			(call_script, "script_troop_get_relation_with_troop", ":potential_target", ":giver_troop"),
			(assign, ":relation_with_giver_troop", reg0),
			(lt, ":relation_with_giver_troop", 0),

			(str_store_troop_name, s4, ":potential_target"),
			(try_begin),
				(ge, "$cheat_mode", 1),
				(display_message, "@{!}DEBUG -- {s4} has sufficiently low relation with giver troop"),
			(try_end),			

			
			(call_script, "script_troop_get_relation_with_troop", ":potential_target", "trp_player"),
			(assign, ":relation_with_player", reg0),
			(lt, ":relation_with_player", 0),
	
			(str_store_troop_name, s4, ":potential_target"),
			(try_begin),
				(ge, "$cheat_mode", 1),
				(display_message, "@{!}DEBUG -- {s4} has sufficiently low relation with player"),
			(try_end),			
			
			(assign, ":score_to_beat", ":relation_with_liege"),
			(assign, ":target_lord", ":potential_target"),
		(try_end),

		(is_between, ":target_lord", active_npcs_begin, active_npcs_end),
		
		
		(assign, ":result", "qst_intrigue_against_lord"),
		(assign, ":quest_target_troop", ":target_lord"),

		
	(else_try),
		#Resolve dispute, if there is a good chance of achieving the result
		(try_begin),
			(ge, "$cheat_mode", 1),
			(quest_get_slot, reg4, "qst_resolve_dispute", slot_quest_dont_give_again_remaining_days),
			(display_message, "@{!}DEBUG -- Checking for resolve dispute, eligible in {reg4} days"),
		(try_end),
		
		(neg|quest_slot_ge, "qst_resolve_dispute", slot_quest_dont_give_again_remaining_days, 1),

		
		
		(this_or_next|troop_slot_eq, "trp_player", slot_troop_spouse, "$g_talk_troop"),
			(eq, "$g_talk_troop", "$g_player_minister"),
			
		(assign, ":target_lord", -1),
		(assign, ":object_lord", -1),
		(assign, ":best_chance_of_success", 20),
		
		(try_for_range, ":lord_1", active_npcs_begin, active_npcs_end),
			(store_faction_of_troop, ":lord_1_faction", ":lord_1"),
			(eq, ":lord_1_faction", "$players_kingdom"),
			(neq, ":lord_1", "$g_talk_troop"),
			
			(try_for_range, ":lord_2", active_npcs_begin, active_npcs_end),
				(store_faction_of_troop, ":lord_2_faction", ":lord_2"),
				(eq, ":lord_2_faction", "$players_kingdom"),
			
				(neq, ":lord_1", ":lord_2"),
				(neq, ":lord_2", "$g_talk_troop"),
				
				(call_script, "script_troop_get_relation_with_troop", ":lord_1", ":lord_2"),
				(assign, ":lord_1_relation_with_lord_2", reg0),
				(lt, ":lord_1_relation_with_lord_2", -5),
				
				(call_script, "script_troop_get_relation_with_troop", ":lord_1", "trp_player"),
				(assign, ":relation_with_lord_1", reg0),
				
				(call_script, "script_troop_get_relation_with_troop", ":lord_2", "trp_player"),
				(assign, ":relation_with_lord_2", reg0),
				
				(gt, ":relation_with_lord_1", 0),
				(gt, ":relation_with_lord_2", 0),
				
				(store_mul, ":chance_of_success", ":relation_with_lord_1", ":relation_with_lord_2"),
				
				
				(gt, ":chance_of_success", ":best_chance_of_success"),
				(assign, ":best_chance_of_success", ":chance_of_success"),
				(assign, ":target_lord", ":lord_1"),
				(assign, ":object_lord", ":lord_2"),
			(try_end),
		(try_end),
		
		
		(is_between, ":target_lord", active_npcs_begin, active_npcs_end),

		(assign, ":result", "qst_resolve_dispute"),
		(assign, ":quest_target_troop", ":target_lord"),
		(assign, ":quest_object_troop", ":object_lord"),
		
	(else_try),
		(try_begin),
			(ge, "$cheat_mode", 1),
			(quest_get_slot, reg4, "qst_offer_gift", slot_quest_dont_give_again_remaining_days),
			(display_message, "@{!}DEBUG -- Checking for offer gift, eligible in {reg4} days"),
		(try_end),	
	
		(neg|quest_slot_ge, "qst_offer_gift", slot_quest_dont_give_again_remaining_days, 1),

		(assign, ":relative_found", -1),
		(assign, ":score_to_beat", 5),
		
		(try_for_range, ":potential_relative", active_npcs_begin, active_npcs_end),
			(store_faction_of_troop, ":relative_faction", ":potential_relative"),
			(eq, ":relative_faction", "$players_kingdom"),
			(neq, ":potential_relative", ":giver_troop"),
			(neg|faction_slot_eq, ":relative_faction", slot_faction_leader, ":potential_relative"),
			
			(call_script, "script_troop_get_family_relation_to_troop", ":giver_troop", ":potential_relative"),
			(assign, ":family_relation", reg0),
			(ge, ":family_relation", ":score_to_beat"),
			
			(store_sub, ":min_relation_w_player", 0, ":family_relation"),
		
			(call_script, "script_troop_get_relation_with_troop", "trp_player", ":potential_relative"),
			(assign, ":relation_with_player", reg0),
			(is_between, ":relation_with_player", ":min_relation_w_player", 0),
			
			(assign, ":score_to_beat", ":family_relation"),
			(assign, ":relative_found", ":potential_relative"),
			
		(try_end),
		
		(is_between, ":relative_found", active_npcs_begin, active_npcs_end),
		
		(assign, ":result", "qst_offer_gift"),
		(assign, ":quest_target_troop", ":relative_found"),
	(try_end),
	
  
	(try_begin),
		(gt, ":result", -1),
		(quest_set_slot, ":result", slot_quest_target_troop, ":quest_target_troop"),
		(quest_set_slot, ":result", slot_quest_target_troop, ":quest_object_troop"),
		
		(quest_set_slot, ":result", slot_quest_giver_troop, ":giver_troop"),
        (quest_set_slot, ":result", slot_quest_dont_give_again_period, ":quest_dont_give_again_period"),
    (try_end), 
  
    (assign, reg0, ":result"),
    (assign, reg1, ":quest_target_troop"),
    (assign, reg2, ":quest_object_troop"),
  
  ]),
  
  
  ("npc_find_quest_for_player_to_s11", 
  [
  (store_script_param, ":faction", 1),

  (assign, ":quest_giver_found", -1),
  (try_for_range, ":quest_giver", active_npcs_begin, mayors_end),
    (eq, ":quest_giver_found", -1),

	(neg|troop_slot_eq, "trp_player", slot_troop_spouse, ":quest_giver"),
	
	(gt, ":quest_giver", "$g_troop_list_no"),
	
	(assign, "$g_troop_list_no", ":quest_giver"),
	
	(this_or_next|troop_slot_eq, ":quest_giver", slot_troop_occupation, slto_kingdom_hero),
		(is_between, ":quest_giver", mayors_begin, mayors_end),

	(neg|troop_slot_ge, ":quest_giver", slot_troop_prisoner_of_party, centers_begin),
	
	(try_begin),
		(is_between, ":quest_giver", mayors_begin, mayors_end),
		(assign, ":quest_giver_faction", -1),
		(try_for_range,":town", towns_begin, towns_end),
			(party_slot_eq, ":town", slot_town_elder, ":quest_giver"),
			(store_faction_of_party, ":quest_giver_faction", ":town"),
		(try_end),
	(else_try),
		(store_faction_of_troop, ":quest_giver_faction", ":quest_giver"),	
	(try_end),
	(eq, ":faction", ":quest_giver_faction"),
	
	(call_script, "script_get_dynamic_quest", ":quest_giver"),	
    (gt, reg0, -1),
	
    (assign, ":quest_giver_found", ":quest_giver"),
	(try_begin),
          (eq, "$cheat_mode", 1),
	  (str_store_troop_name, s4, ":quest_giver_found"),
	  (display_message, "str_test_diagnostic_quest_found_for_s4"),
        (try_end),
	
  (try_end),
 
  (assign, reg0, ":quest_giver_found"), 
  
    ]),  
  
  
  
  # script_cf_get_random_enemy_center_within_range
  # Input: arg1 = party_no, arg2 = range (in kms)
  # Output: reg0 = center_no
  ("cf_get_random_enemy_center_within_range",
    [
      (store_script_param, ":party_no", 1),
      (store_script_param, ":range", 2),

      (assign, ":num_centers", 0),
      (store_faction_of_party, ":faction_no", ":party_no"),
      (try_for_range, ":cur_center", centers_begin, centers_end),
        (store_faction_of_party, ":cur_faction", ":cur_center"),
        (store_relation, ":cur_relation", ":faction_no", ":cur_faction"),
        (lt, ":cur_relation", 0),
        (store_distance_to_party_from_party, ":dist", ":party_no", ":cur_center"),
        (le, ":dist", ":range"),
        (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, ":cur_center", centers_begin, ":end_cond"),
        (store_faction_of_party, ":cur_faction", ":cur_center"),
        (store_relation, ":cur_relation", ":faction_no", ":cur_faction"),
        (lt, ":cur_relation", 0),
        (store_distance_to_party_from_party, ":dist", ":party_no", ":cur_center"),
        (le, ":dist", ":range"),
        (val_sub, ":random_center", 1),
        (lt, ":random_center", 0),
        (assign, ":result", ":cur_center"),
        (assign, ":end_cond", 0),#break
      (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),
        (faction_slot_eq, ":cur_faction", slot_faction_state, sfs_active),
        (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),
        (faction_slot_eq, ":cur_faction", slot_faction_state, sfs_active),
        (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_faction_get_random_friendly_faction
  # Input: arg1 = faction_no
  # Output: reg0 = faction_no (Can fail)
  ("cf_faction_get_random_friendly_faction",
    [
      (store_script_param_1, ":faction_no"),
      
      (assign, ":result", -1),
      (assign, ":count_factions", 0),
      (try_for_range, ":cur_faction", kingdoms_begin, kingdoms_end),
        (faction_slot_eq, ":cur_faction", slot_faction_state, sfs_active),
        (neq, ":cur_faction", ":faction_no"),
        (store_relation, ":cur_relation", ":faction_no", ":cur_faction"),
        (ge, ":cur_relation", 0),
        (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),
        (faction_slot_eq, ":cur_faction", slot_faction_state, sfs_active),
        (neq, ":cur_faction", ":faction_no"),
        (store_relation, ":cur_relation", ":faction_no", ":cur_faction"),
        (ge, ":cur_relation", 0),
        (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, ":enemy_troop_no", active_npcs_begin, active_npcs_end),
        (troop_slot_eq, ":enemy_troop_no", slot_troop_occupation, ":occupation"),
        (call_script, "script_troop_get_relation_with_troop", ":troop_no", ":enemy_troop_no"),         
        (lt, reg0, -10), 
        (val_add, ":count_enemies", 1),
      (try_end),
      
      (gt, ":count_enemies", 0),
      (store_random_in_range,":random_enemy",0,":count_enemies"),
      
      (assign, ":count_enemies", 0),
      (try_for_range, ":enemy_troop_no", active_npcs_begin, active_npcs_end),
        (troop_slot_eq, ":enemy_troop_no", slot_troop_occupation, ":occupation"),
        (call_script, "script_troop_get_relation_with_troop", ":troop_no", ":enemy_troop_no"), 
        (lt, reg0, -10),
        (val_add, ":count_enemies", 1),
        (eq, ":random_enemy", ":count_enemies"),
        (assign, ":result", ":enemy_troop_no"),
      (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 - removed

  
  
##  # 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"),
##  ]),
  
   # NE quests
    # v585 Josef love letter
   
  # script_cf_get_random_lady_in_a_center_with_faction
  # Input: arg1 = faction_no
  # Output: reg0 = troop_no, Can(not) Fail!
  ("cf_get_random_lady_in_a_center_with_faction",
    [
      (store_script_param_1, ":faction_no"),
      (assign, ":result", -1),
      (assign, ":count_ladies", 0),
       (try_for_range, ":lady_no", kingdom_ladies_begin, kingdom_ladies_end),
         (store_troop_faction, ":lady_faction_no", ":lady_no"),
         (eq, ":faction_no", ":lady_faction_no"),
		 (store_random_in_range, ":choose_lady", 1, 4),
        (val_add, ":count_ladies", 1),
		(try_begin),
		(eq, ":count_ladies", ":choose_lady"),
		(assign, ":result", ":lady_no"),
		(try_end),
       (try_end),
      (neq, ":result", -1),
      (assign, reg0, ":result"),
  ]), 
  
  
  # end v585 Josef
  
   # Get King 
  # 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", kings_begin, kings_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", kings_begin, kings_end),
       (val_add, ":count_heroes", 1),
       (lt, ":random_hero", ":count_heroes"),
       (assign, ":result", ":cur_lord"),
     (try_end),
     (neq, ":result", -1),
     (assign, reg0, ":result"),
 ]),
 # v585 Josef end
 
 
   # v585 Josef peasant 
  
    # script_get peasant woman
  # Input: none
  # Output: reg0 = peasant woman
  ("get_peasant_woman",
    [
      (assign, reg0, -1),
      (try_for_range, ":peasant_woman", peasants_begin, peasants_end),
        (assign, reg0, ":peasant_woman"),
      (try_end),
  ]),
  
  
  # NE end quests
  
  # 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),
        (neg|troop_slot_ge, ":lord_no", slot_troop_prisoner_of_party, 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),
        (neg|troop_slot_ge, ":lord_no", slot_troop_prisoner_of_party, 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_except_king_with_faction
  # Input: arg1 = faction_no
  # Output: reg0 = troop_no, Can Fail!
  ("cf_get_random_lord_except_king_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"),
        (neg|faction_slot_eq, ":faction_no", slot_faction_leader, ":lord_no"),
        (troop_slot_eq, ":lord_no", slot_troop_occupation, slto_kingdom_hero),
        #(troop_slot_eq, ":lord_no", slot_troop_is_prisoner, 0),
        (neg|troop_slot_ge, ":lord_no", slot_troop_prisoner_of_party, 0),
        (troop_get_slot, ":lord_party", ":lord_no", slot_troop_leaded_party),
        (ge, ":lord_party", 0),
        (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"),
        (neg|faction_slot_eq, ":faction_no", slot_faction_leader, ":lord_no"),
        (troop_slot_eq, ":lord_no", slot_troop_occupation, slto_kingdom_hero),
        #(troop_slot_eq, ":lord_no", slot_troop_is_prisoner, 0),
        (neg|troop_slot_ge, ":lord_no", slot_troop_prisoner_of_party, 0),
        (troop_get_slot, ":lord_party", ":lord_no", slot_troop_leaded_party),
        (ge, ":lord_party", 0),
        (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_supporters_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),
        (neg|troop_slot_ge, ":lord_no", slot_troop_prisoner_of_party, 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_supporters_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),
        (neg|troop_slot_ge, ":lord_no", slot_troop_prisoner_of_party, 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: arg1 = besiege_mode, arg2 = dont_add_friends_other_than_accompanying
  # Output: none
  ("let_nearby_parties_join_current_battle",
    [
      (store_script_param, ":besiege_mode", 1),
      (store_script_param, ":dont_add_friends_other_than_accompanying", 2),
              
      (store_character_level, ":player_level", "trp_player"),      
      (try_for_parties, ":party_no"),
        (party_is_active, ":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),
              
        (party_stack_get_troop_id, ":stack_troop", ":party_no", 0),  
        (try_begin),
          (neg|is_between, ":stack_troop", "trp_looter", "trp_black_khergit_horseman"),

		  # NE Parties - x2
          (assign, ":join_distance", 10), #day/not bandit
          (try_begin),
            (is_currently_night),
            (assign, ":join_distance", 6), #nigh/not bandit
          (try_end),    
        (else_try),  
          (assign, ":join_distance", 6), #day/bandit
          (try_begin),
            (is_currently_night),
            (assign, ":join_distance", 4), #night/bandit
          (try_end),    
        (try_end),          

		#Quest bandits do not join battle
		(this_or_next|neg|check_quest_active, "qst_track_down_bandits"),
			(neg|quest_slot_eq, "qst_track_down_bandits", slot_quest_target_party, ":party_no"),
		(this_or_next|neg|check_quest_active, "qst_troublesome_bandits"),
			(neg|quest_slot_eq, "qst_troublesome_bandits", slot_quest_target_party, ":party_no"),
			
			
			
        (store_distance_to_party_from_party, ":distance", ":party_no", "p_main_party"),
        (lt, ":distance", ":join_distance"),

        (store_faction_of_party, ":faction_no", ":party_no"),
        (store_faction_of_party, ":enemy_faction", "$g_enemy_party"),
        (try_begin),
          (eq, ":faction_no", "fac_player_supporters_faction"),
          (assign, ":reln_with_player", 100),
        (else_try),
          (store_relation, ":reln_with_player", ":faction_no", "fac_player_supporters_faction"),
        (try_end),
        (try_begin),
          (eq, ":faction_no", ":enemy_faction"),
          (assign, ":reln_with_enemy", 100),
        (else_try),
          (store_relation, ":reln_with_enemy", ":faction_no", ":enemy_faction"),
        (try_end),

        (assign, ":enemy_side", 1),
        (try_begin),
          (neq, "$g_enemy_party", "$g_encountered_party"),
          (assign, ":enemy_side", 2),
        (try_end),

        (try_begin),
          (eq, ":besiege_mode", 0),
          (lt, ":reln_with_player", 0),
          (gt, ":reln_with_enemy", 0),
          (party_get_slot, ":party_type", ":party_no"),
          
          (assign, ":enemy_is_bandit_party_and_level_is_greater_than_6", 0),
          (try_begin),
            (party_stack_get_troop_id, ":stack_troop", ":party_no", 0),
            (is_between, ":stack_troop", "trp_looter", "trp_black_khergit_horseman"),                    
            (gt, ":player_level", 6),
            (assign, ":enemy_is_bandit_party_and_level_is_greater_than_6", 1),
          (try_end),  

          (this_or_next|eq, ":party_type", spt_kingdom_hero_party),          
          (eq, ":enemy_is_bandit_party_and_level_is_greater_than_6", 1),
                                          
          (get_party_ai_behavior, ":ai_bhvr", ":party_no"),
          (neq, ":ai_bhvr", ai_bhvr_avoid_party),
          (party_quick_attach_to_current_battle, ":party_no", ":enemy_side"), #attach as enemy
          (str_store_party_name, s1, ":party_no"),
          (display_message, "str_s1_joined_battle_enemy"),
        (else_try),          
          (try_begin),
            (party_slot_eq, ":party_no", slot_party_ai_state, spai_accompanying_army),
            (party_slot_eq, ":party_no", slot_party_ai_object, "trp_player"),
            (assign, ":party_is_accompanying_player", 1),
          (else_try),  
            (assign, ":party_is_accompanying_player", 0),
          (try_end),
          
          (this_or_next|eq, ":dont_add_friends_other_than_accompanying", 0),
          (eq, ":party_is_accompanying_player", 1),
          (gt, ":reln_with_player", 0),
          (lt, ":reln_with_enemy", 0),
          
          (assign, ":following_player", 0),
          (try_begin),
            (party_slot_eq, ":party_no", slot_party_ai_state, spai_accompanying_army),            
            (party_slot_eq, ":party_no", slot_party_ai_object, "p_main_party"),
            (assign, ":following_player", 1),
          (try_end),             

          (assign, ":do_join", 1),
          (try_begin),
            (eq, ":besiege_mode", 1),                        
            (eq, ":following_player", 0),                        
            (assign, ":do_join", 0),
            (eq, ":faction_no", "$players_kingdom"),
            (faction_slot_eq, "$players_kingdom", slot_faction_marshall, "trp_player"),
            (assign, ":do_join", 1),
          (try_end),          
          (eq, ":do_join", 1),
          
          (party_get_slot, ":party_type", ":party_no"),
          (eq, ":party_type", spt_kingdom_hero_party),
          (party_stack_get_troop_id, ":leader", ":party_no", 0),
          #(troop_get_slot, ":player_relation", ":leader", slot_troop_player_relation),
          (call_script, "script_troop_get_player_relation", ":leader"),
          (assign, ":player_relation", reg0),
          
          (assign, ":join_even_you_do_not_like_player", 0),
          (try_begin),
            (faction_slot_eq, "$players_kingdom", slot_faction_marshall, "trp_player"), #new added, if player is marshal and if he is accompanying then join battle even lord do not like player
            (eq, ":following_player", 1),
            (assign, ":join_even_you_do_not_like_player", 1),
          (try_end),              
          
          (this_or_next|ge, ":player_relation", 0),          
          (eq, ":join_even_you_do_not_like_player", 1),
          
          (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),
  ]),
    
  # 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, ":raw_advantage", 2),
      
      (val_mul, ":player_party_tactics", 30),
      (val_mul, ":enemy_party_tactics", 30),
      (val_add, ":raw_advantage", ":player_party_tactics"),
      (val_sub, ":raw_advantage", ":enemy_party_tactics"),
      (val_div, ":raw_advantage", 100),
      
	  # NE building
       (try_begin), #University tactics upgrade - Jinnai
        (faction_slot_eq, "fac_player_supporters_faction", slot_faction_state, sfs_active),
        (faction_slot_eq, "fac_player_supporters_faction", slot_faction_univ_tactics, 1),
        (val_add,":raw_advantage",2),
      (try_end),
      # NE end building
	  
      (assign, reg0, ":raw_advantage"),
      (display_message, "@Battle Advantage = {reg0}.", 0xFFFFFFFF),
  ]),
  
  
  # 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"),
      (agent_get_position, pos1, ":player_agent"),
      (assign, ":result", 0),
      (set_fixed_point_multiplier, 100),
      (try_for_agents,":cur_agent"),
        (neq, ":cur_agent", ":player_agent"),
        (agent_is_alive, ":cur_agent"),
        (agent_is_human, ":cur_agent"),
        (neg|agent_is_ally, ":cur_agent"),
        (agent_get_position, pos2, ":cur_agent"),
        (get_distance_between_positions, ":cur_distance", pos1, pos2),
        (le, ":cur_distance", 1500), #15 meters
        (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"),

#rebellion changes begin -Arma
     (try_for_range, ":pretender", pretenders_begin, pretenders_end),
        (neq, ":pretender", "$supported_pretender"),
        (troop_slot_eq, ":pretender", slot_troop_cur_center, ":center_no"),
        (party_add_members, ":party_no_to_collect_heroes", ":pretender", 1),
     (try_end),

#     (try_for_range, ":rebel_faction", rebel_factions_begin, rebel_factions_end),
#        (faction_slot_eq, ":rebel_faction", slot_faction_state, sfs_inactive_rebellion),
#        (faction_slot_eq, ":rebel_faction", slot_faction_inactive_leader_location, ":center_no"),
#        (faction_get_slot, ":pretender", ":rebel_faction", slot_faction_leader),
#        (party_add_members, ":party_no_to_collect_heroes", ":pretender", 1),
#     (try_end),
#rebellion changes end


  ]),
  
  
  # 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"),
      
      (try_begin),
        (eq, ":faction_no", "fac_player_supporters_faction"),        
        (faction_get_slot, ":player_faction_king", "fac_player_supporters_faction", slot_faction_leader),
        (eq, ":player_faction_king", "trp_player"),
        
        (try_begin),
          (is_between, ":center_no", walled_centers_begin, walled_centers_end),
          (assign, ":number_of_walled_centers_players_kingdom_has", 1),
        (else_try),
          (assign, ":number_of_walled_centers_players_kingdom_has", 0),
        (try_end),
        
        (try_for_range, ":walled_center", walled_centers_begin, walled_centers_end),
          (store_faction_of_party, ":owner_faction_no", ":walled_center"),
          (eq, ":owner_faction_no", "fac_player_supporters_faction"),          
          (val_add, ":number_of_walled_centers_players_kingdom_has", 1),
        (try_end),
        
        (ge, ":number_of_walled_centers_players_kingdom_has", 10),
        (unlock_achievement, ACHIEVEMENT_VICTUM_SEQUENS),
      (try_end),  
      
      (try_begin),
        (check_quest_active, "qst_join_siege_with_army"),
        (quest_slot_eq, "qst_join_siege_with_army", slot_quest_target_center, ":center_no"),
        (call_script, "script_abort_quest", "qst_join_siege_with_army", 0),
        #Reactivating follow army quest
        (faction_get_slot, ":faction_marshall", "$players_kingdom", slot_faction_marshall),
        (str_store_troop_name_link, s9, ":faction_marshall"),
        (setup_quest_text, "qst_follow_army"),
        (str_store_string, s2, "@{s9} wants you to resume following his army until further notice."),
        (call_script, "script_start_quest", "qst_follow_army", ":faction_marshall"),
        (assign, "$g_player_follow_army_warnings", 0),
      (try_end),

      #(store_faction_of_party, ":old_faction", ":center_no"),
      (call_script, "script_give_center_to_faction_aux", ":center_no", ":faction_no"),
      (call_script, "script_update_village_market_towns"),

      (try_for_range, ":cur_faction", kingdoms_begin, kingdoms_end),
        (call_script, "script_faction_recalculate_strength", ":cur_faction"),
      (try_end),
      (assign, "$g_recalculate_ais", 1),
	  
	  (try_begin),
        (eq, ":faction_no", "fac_player_supporters_faction"),
		(faction_slot_eq, "fac_player_supporters_faction", slot_faction_state, sfs_inactive),
		(call_script, "script_activate_player_faction", "trp_player"),
	  (try_end),
	  	  
      #(call_script, "script_activate_deactivate_player_faction", ":old_faction"),
      #(try_begin),
      #(eq, ":faction_no", "fac_player_supporters_faction"),
      #(faction_slot_eq, "fac_player_supporters_faction", slot_faction_leader, "trp_player"),
      #(call_script, "script_give_center_to_lord", ":center_no", "trp_player", 0),
	
      #check with Armagan -- what is this here for?
      #(try_for_range, ":cur_village", villages_begin, villages_end),
      #(store_faction_of_party, ":cur_village_faction", ":cur_village"),
      #(eq, ":cur_village_faction", "fac_player_supporters_faction"),
      #(neg|party_slot_eq, ":cur_village", slot_town_lord, "trp_player"),
      #(call_script, "script_give_center_to_lord", ":cur_village", "trp_player", 0),
      #(try_end),
      #(try_end),
    ]),
  
  # 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"),

      (store_faction_of_party, ":old_faction", ":center_no"),
      (party_set_faction, ":center_no", ":faction_no"),

      (try_begin),
        (party_slot_eq, ":center_no", slot_party_type, spt_village),
        (party_get_slot, ":farmer_party", ":center_no", slot_village_farmer_party),
        (gt, ":farmer_party", 0),
        (party_is_active, ":farmer_party"),
        (party_set_faction, ":farmer_party", ":faction_no"),
      (try_end),

      (try_begin),
	    #This bit of seemingly redundant code (the neq condition) is designed to prevent a bug that occurs when a player first conquers a center -- apparently this script is called again AFTER it is handed to a lord
		#Without this line, then the player's dialog selection does not have any affect, because town_lord is set again to stl_unassigned after the player makes his or her choice
	    (neq, ":faction_no", ":old_faction"),
		
        (party_set_slot, ":center_no", slot_center_ex_faction, ":old_faction"),
        (party_get_slot, ":old_town_lord", ":center_no", slot_town_lord),
        (party_set_slot, ":center_no", slot_town_lord, stl_unassigned),
        (party_set_banner_icon, ":center_no", 0),#Removing banner
        (call_script, "script_update_faction_notes", ":old_faction"),
      (try_end),  
      
      (call_script, "script_update_faction_notes", ":faction_no"),
      (call_script, "script_update_center_notes", ":center_no"),
      
      (try_begin),
        (ge, ":old_town_lord", 0),
        (call_script, "script_troop_set_title_according_to_faction", ":old_town_lord", ":old_faction"),
        (neq, ":faction_no", "fac_player_supporters_faction"),
        (call_script, "script_update_troop_notes", ":old_town_lord"),
      (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_change_troop_faction
  # Input: arg1 = troop_no, arg2 = faction
  ("change_troop_faction",
    [
      (store_script_param_1, ":troop_no"),
      (store_script_param_2, ":faction_no"),
      (try_begin),
        #Reactivating inactive or defeated faction
        (is_between, ":faction_no", kingdoms_begin, kingdoms_end),
        (neg|faction_slot_eq, ":faction_no", slot_faction_state, sfs_active),
        (faction_set_slot, ":faction_no", slot_faction_state, sfs_active),
        #(call_script, "script_store_average_center_value_per_faction"),
      (try_end),

	  #Political ramifications
	  (store_faction_of_troop, ":orig_faction", ":troop_no"),
	  
	  #remove if he is marshal
	  (try_begin),
		(faction_slot_eq, ":orig_faction", slot_faction_marshall, ":troop_no"),
        (call_script, "script_check_and_finish_active_army_quests_for_faction", ":orig_faction"),       

		#No current issue on the agenda
		(try_begin),
			(faction_slot_eq, ":orig_faction", slot_faction_political_issue, 0),
		
			(faction_set_slot, ":orig_faction", slot_faction_political_issue, 1), #Appointment of marshal
			(store_current_hours, ":hours"),
			(val_max, ":hours", 0),
			(faction_set_slot, ":orig_faction", slot_faction_political_issue_time, ":hours"), #Appointment of marshal
			(try_for_range, ":active_npc", active_npcs_begin, active_npcs_end),
				(store_faction_of_troop, ":active_npc_faction", ":active_npc"),
				(eq, ":active_npc_faction", ":orig_faction"),
				(troop_set_slot, ":active_npc", slot_troop_stance_on_faction_issue, -1),
			(try_end),		
			(try_begin),
				(eq, "$players_kingdom", ":orig_faction"),
				(troop_set_slot, "trp_player", slot_troop_stance_on_faction_issue, -1),
			(try_end),		
		(try_end),
		
        (try_begin),
		  (troop_get_slot, ":old_marshall_party", ":troop_no", slot_troop_leaded_party),
          (party_is_active, ":old_marshall_party"),
          (party_set_marshall, ":old_marshall_party", 0),
        (try_end),  

		(faction_set_slot, ":orig_faction", slot_faction_marshall, -1),
	  (try_end),
	  #Removal as marshal ends
	  
	  #Other political ramifications
	  (troop_set_slot, ":troop_no", slot_troop_stance_on_faction_issue, -1),
	  (try_for_range, ":active_npc", active_npcs_begin, active_npcs_end),
		(troop_slot_eq, ":active_npc", slot_troop_stance_on_faction_issue, ":troop_no"),
		(troop_set_slot, ":active_npc", slot_troop_stance_on_faction_issue, -1),
	  (try_end),
	  #Political ramifications end
	  
	  
		(try_begin),
			(ge, "$cheat_mode", 1),
			(str_store_troop_name, s4, ":troop_no"),
			(display_message, "@{!}DEBUG - {s4} faction changed in normal faction change"), 
		(try_end),
	  
      (troop_set_faction, ":troop_no", ":faction_no"),
      (troop_set_slot, ":troop_no", slot_troop_recruitment_random, 0),
      (troop_set_slot, ":troop_no", slot_lord_recruitment_argument, 0),
      (troop_set_slot, ":troop_no", slot_lord_recruitment_candidate, 0),
      (troop_set_slot, ":troop_no", slot_troop_promised_fief, 0),

      #Give new title
      (call_script, "script_troop_set_title_according_to_faction", ":troop_no", ":faction_no"),
      (call_script, "script_set_icon_for_lord_party", ":troop_no"),
      
      (try_begin),
        (this_or_next|eq, ":faction_no", "$players_kingdom"),
        (eq, ":faction_no", "fac_player_supporters_faction"),
        (call_script, "script_check_concilio_calradi_achievement"),
      (try_end),

	  #Takes walled centers and dependent villages with him
      (try_for_range, ":center_no", walled_centers_begin, walled_centers_end),
        (party_slot_eq, ":center_no", slot_town_lord, ":troop_no"),
        (party_set_faction, ":center_no", ":faction_no"),
        (try_for_range, ":village_no", villages_begin, villages_end),
          (party_slot_eq, ":village_no", slot_village_bound_center, ":center_no"),
          (party_set_faction, ":village_no", ":faction_no"),
          (party_get_slot, ":farmer_party_no", ":village_no", slot_village_farmer_party),
          (try_begin),
            (gt, ":farmer_party_no", 0),
            (party_is_active, ":farmer_party_no"),
            (party_set_faction, ":farmer_party_no", ":faction_no"),
          (try_end),
          (try_begin),
            (party_get_slot, ":old_town_lord", ":village_no", slot_town_lord),
            (neq, ":old_town_lord", ":troop_no"),
            (party_set_slot, ":village_no", slot_town_lord, stl_unassigned),
          (try_end),
        (try_end),
      (try_end),
	  
	  #Dependant kingdom ladies switch faction
	  (try_for_range, ":kingdom_lady", kingdom_ladies_begin, kingdom_ladies_end),
		(call_script, "script_get_kingdom_lady_social_determinants", ":kingdom_lady"),
		(assign, ":closest_male_relative", reg0),
		(assign, ":new_center", reg1),
		
		(eq, ":closest_male_relative", ":troop_no"),
		
		(try_begin),
			(ge, "$cheat_mode", 1),
			(str_store_troop_name, s4, ":kingdom_lady"),
			(display_message, "@{!}DEBUG - {s4} faction changed by guardian moving"), 
		(try_end),
		
		(troop_set_faction, ":kingdom_lady", ":faction_no"),
		(troop_slot_eq, ":kingdom_lady", slot_troop_prisoner_of_party, -1),
		(troop_set_slot, ":kingdom_lady", slot_troop_cur_center, ":new_center"),
	  (try_end),
	  
	  #Remove his control over villages under another fortress
      (try_for_range, ":village_no", villages_begin, villages_end),
        (party_slot_eq, ":village_no", slot_town_lord, ":troop_no"),
        (store_faction_of_party, ":village_faction", ":village_no"),
        (try_begin),
          (neq, ":village_faction", ":faction_no"),
          (party_set_slot, ":village_no", slot_town_lord, stl_unassigned),
        (try_end),
      (try_end),
	  
	  #Free prisoners
      (try_begin),
        (troop_get_slot, ":leaded_party", ":troop_no", slot_troop_leaded_party),
        (gt, ":leaded_party", 0),
        (party_set_faction, ":leaded_party", ":faction_no"),
        (party_get_num_prisoner_stacks, ":num_stacks", ":leaded_party"),
        (try_for_range_backwards, ":troop_iterator", 0, ":num_stacks"),
          (party_prisoner_stack_get_troop_id, ":cur_troop_id", ":leaded_party", ":troop_iterator"),
          (store_troop_faction, ":cur_faction", ":cur_troop_id"),
          (troop_is_hero, ":cur_troop_id"),
          (eq, ":cur_faction", ":faction_no"),
          (call_script, "script_remove_troop_from_prison", ":cur_troop_id"),
          (party_remove_prisoners, ":leaded_party", ":cur_troop_id", 1),
        (try_end),
      (try_end),
	  
	  #Annull all quests of which the lord is giver
	  (try_for_range, ":quest", all_quests_begin, all_quests_end),
		(check_quest_active, ":quest"),
		(quest_slot_eq, ":quest", slot_quest_giver_troop, ":troop_no"),
		
		(str_store_troop_name, s4, ":troop_no"),
		(try_begin),
		  (eq, "$cheat_mode", 1),
  		  (display_message, "str_s4_changing_sides_aborts_quest"),
        (try_end),
		(call_script, "script_abort_quest", ":quest", 0),
	  (try_end),
	  
	  #Boot all lords out of centers whose faction has changed
	  (try_for_range, ":lord_to_move", active_npcs_begin, active_npcs_end),
		(troop_get_slot, ":lord_led_party", ":lord_to_move", slot_troop_leaded_party),
	    (party_is_active, ":lord_led_party"),
		(party_get_attached_to, ":led_party_attached", ":lord_led_party"),
		(is_between, ":led_party_attached", walled_centers_begin, walled_centers_end),
		(store_faction_of_party, ":led_party_faction", ":lord_led_party"),
		(store_faction_of_party, ":attached_party_faction", ":led_party_attached"),
		(neq, ":led_party_faction", ":attached_party_faction"),
		
		(party_detach, ":lord_led_party"),
	  (try_end),
	  
	  #Increase relation with lord in new faction by 5
	  #Or, if player kingdom, make inactive pending confirmation
	  (faction_get_slot, ":faction_liege", ":faction_no", slot_faction_leader),
	  (try_begin),
		(eq, ":faction_liege", "trp_player"),
		(neq, ":troop_no", "$g_talk_troop"),
	    (troop_set_slot, ":troop_no", slot_troop_occupation, slto_inactive), #POSSIBLE REASON 1
	  (else_try),
		(is_between, ":faction_liege", active_npcs_begin, active_npcs_end),
		(is_between, ":troop_no", active_npcs_begin, active_npcs_end),
		(call_script, "script_troop_change_relation_with_troop", ":faction_liege", ":troop_no", 5),
		(val_add, "$total_indictment_changes", 5),
	  (try_end),
	  
	  #Break courtship relations
	  (try_begin),
	  	(troop_slot_ge, ":troop_no", slot_troop_spouse, 0),
		#Already married, do nothing
	  (else_try),
		(is_between, ":troop_no", active_npcs_begin, active_npcs_end),
	    (try_for_range, ":love_interest_slot", slot_troop_love_interest_1, slot_troop_love_interests_end),
			(troop_get_slot, ":courted_lady", ":troop_no", ":love_interest_slot"),
			(call_script, "script_courtship_event_lady_break_relation_with_suitor", ":courted_lady", ":troop_no"),
	    (try_end),
		(call_script, "script_assign_troop_love_interests", ":troop_no"),
	  (else_try),	
		(is_between, ":troop_no", kingdom_ladies_begin, kingdom_ladies_end),
		(try_for_range, ":active_npc", active_npcs_begin, active_npcs_end),
			(try_for_range, ":love_interest_slot", slot_troop_love_interest_1, slot_troop_love_interests_end),
				(troop_slot_eq, ":active_npc", ":love_interest_slot", ":troop_no"),
				(call_script, "script_courtship_event_lady_break_relation_with_suitor", ":troop_no", ":active_npc"),
			(try_end),
		(try_end),
	  (try_end),
	  
	  #Stop raidings/sieges of new faction's fief if there is any
	  (troop_get_slot, ":troop_party", ":troop_no", slot_troop_leaded_party),
	  (try_for_range, ":center_no", centers_begin, centers_end),
	    (party_slot_eq, ":center_no", slot_party_type, spt_village),
	    (party_get_slot, ":raided_by", ":center_no", slot_village_raided_by),	    
	    (eq, ":raided_by", ":troop_party"),
	    (party_set_slot, ":center_no", slot_village_raided_by, -1),
	    (try_begin),
	      (party_slot_eq, ":center_no", slot_village_state, svs_being_raided),	      
	      (party_set_slot, ":center_no", slot_village_state, svs_normal),
	      (party_set_extra_text, ":center_no", "str_empty_string"),
	    (try_end),
	  (else_try),  	    
	    (party_get_slot, ":besieged_by", ":center_no", slot_center_is_besieged_by),
	    (eq, ":besieged_by", ":troop_party"),
	    (party_set_slot, ":center_no", slot_center_is_besieged_by, -1),
	    (try_begin),	    
	      (party_slot_eq, ":center_no", slot_village_state, svs_under_siege),	      
	      (party_set_slot, ":center_no", slot_village_state, svs_normal),
	      (party_set_extra_text, ":center_no", "str_empty_string"),
	    (try_end),
	  (try_end),
	  	  
      (call_script, "script_update_all_notes"),

      (call_script, "script_update_village_market_towns"),
      (assign, "$g_recalculate_ais", 1),
      ]),

  # script_troop_set_title_according_to_faction
  # Input: arg1 = troop_no, arg2 = faction_no
  (
  "troop_set_title_according_to_faction",
    [
      (store_script_param, ":troop_no", 1),
      (store_script_param, ":faction_no", 2),
      (try_begin),
        (neq, ":troop_no", "trp_player"),
        (is_between, ":faction_no", kingdoms_begin, kingdoms_end),
        (str_store_troop_name_plural, s0, ":troop_no"),
        (assign, ":title_index", 0), # Not found
        (try_begin),
          # Override by Lav in 0.608b7 unofficial patch
          (troop_slot_eq, ":troop_no", slot_troop_occupation, slto_kingdom_hero),
          (store_sub, ":title_index", ":faction_no", "fac_kingdom_1"),
          (try_begin),
              (lt, ":title_index", 0), # Player's own kingdom
              (assign, ":title_index", 7), # Fixed for now, later player will be able to choose any noble title set
          (try_end),
          (val_mul, ":title_index", 5),
          (val_add, ":title_index", noble_titles_begin),
          # Title set found, now to identify the actual title in the set
          (try_begin),
            (faction_slot_eq, ":faction_no", slot_faction_leader, ":troop_no"),
            (val_add, ":title_index", 4), # King offset
          (else_try),
            (assign, ":fief", -1),
            (try_for_range_backwards, ":center", centers_begin, centers_end),
              (party_slot_eq, ":center", slot_town_lord, ":troop_no"),
              (assign, ":fief", ":center"),
            (try_end),
            (try_begin),
              (is_between, ":fief", towns_begin, towns_end),
              (val_add, ":title_index", 3), # Town lord offset
            (else_try),
              (is_between, ":fief", castles_begin, castles_end),
              (val_add, ":title_index", 2), # Castle lord offset
            (else_try),
              (is_between, ":fief", villages_begin, villages_end),
              (val_add, ":title_index", 1), # Village lord offset
            (try_end),
          (try_end),
        (else_try),
          (troop_slot_eq, ":troop_no", slot_troop_occupation, slto_kingdom_lady),
          (troop_get_type, ":gender", ":troop_no"),
          (store_sub, ":title_index", ":faction_no", kingdoms_begin),
          (try_begin),
            (eq, ":gender", 0), #male
            (val_add, ":title_index", kingdom_titles_male_begin),
          (else_try),
            (val_add, ":title_index", kingdom_titles_female_begin),
          (try_end),
        (try_end),
        (gt, ":title_index", 0),
        (str_store_string, s5, ":title_index"),
        (troop_set_name, ":troop_no", s5),
        (troop_get_slot, ":troop_party", ":troop_no", slot_troop_leaded_party),
        (gt, ":troop_party", 0),
        (party_set_name, ":troop_party", "str_s5_s_party"),
      (try_end),
      ]),

  # script_give_center_to_lord
  # Input: arg1 = center_no, arg2 = lord_troop, arg3 = add_garrison_to_center
  ("give_center_to_lord",
    [
      (store_script_param, ":center_no", 1),
      (store_script_param, ":lord_troop_id", 2), #-1 only in the case of a player deferring ownership of a center
      (store_script_param, ":add_garrison", 3),

	  (try_begin),
	    (eq, "$cheat_mode", 1),
		(ge, ":lord_troop_id", 0),
		(str_store_party_name, s4, ":center_no"),
		(str_store_troop_name, s5, ":lord_troop_id"),
		(display_message, "@{!}DEBUG -- {s4} awarded to {s5}"),
	  (try_end),
	  
	  (try_begin),
	    (eq, ":lord_troop_id", "trp_player"),
	    (unlock_achievement, ACHIEVEMENT_ROYALITY_PAYMENT),
	    
	    (assign, ":number_of_fiefs_player_have", 1),
	    (try_for_range, ":cur_center", centers_begin, centers_end),
	      (neq, ":cur_center", ":center_no"),
	      (party_slot_eq, ":cur_center", slot_town_lord, "trp_player"),
	      (val_add, ":number_of_fiefs_player_have", 1),
	    (try_end),
	    
	    (ge, ":number_of_fiefs_player_have", 5),
	    (unlock_achievement, ACHIEVEMENT_MEDIEVAL_EMLAK),	    
	  (try_end),
	  
      (party_get_slot, ":old_lord_troop_id", ":center_no", slot_town_lord),
      
	  (try_begin), #This script is ONLY called with lord_troop_id = -1 when it is the player faction 
	    (eq, ":lord_troop_id", -1),
	    (assign, ":lord_troop_faction", "fac_player_supporters_faction"),
        (party_set_banner_icon, ":center_no", 0),#Removing banner
		
      (else_try),	
	    (eq, ":lord_troop_id", "trp_player"),
	    (assign, ":lord_troop_faction", "$players_kingdom"), #was changed on Apr 27 from fac_plyr_sup_fac

      (else_try),	  
		(store_troop_faction, ":lord_troop_faction", ":lord_troop_id"),
	  (try_end),	
	  (faction_get_slot, ":faction_leader", ":lord_troop_faction", slot_faction_leader),
	  
	  (try_begin),
		(eq, ":faction_leader", ":old_lord_troop_id"),
		(call_script, "script_add_log_entry", logent_liege_grants_fief_to_vassal, ":faction_leader", ":center_no", ":lord_troop_id", ":lord_troop_faction"),
        (troop_set_slot, ":lord_troop_id", slot_troop_promised_fief, 0),		
	  (try_end),

      (try_begin),
	    (eq, ":lord_troop_id", -1), #Lord troop ID -1 is only used when a player is deferring assignment of a fief
        (party_set_faction, ":center_no", "$players_kingdom"),
	  (else_try),
        (eq, ":lord_troop_id", "trp_player"),
        (gt, "$players_kingdom", 0),
        (party_set_faction, ":center_no", "$players_kingdom"),
      (else_try),
        (eq, ":lord_troop_id", "trp_player"),
        (neg|is_between, "$players_kingdom", kingdoms_begin, kingdoms_end),
        (party_set_faction, ":center_no", "fac_player_supporters_faction"),
      (else_try),
        (party_set_faction, ":center_no", ":lord_troop_faction"),
      (try_end),
      (party_set_slot, ":center_no", slot_town_lord, ":lord_troop_id"),

      (try_begin),
        (party_slot_eq, ":center_no", slot_party_type, spt_village),
        (party_get_slot, ":farmer_party_no", ":center_no", slot_village_farmer_party),
        (gt, ":farmer_party_no", 0),
        (party_is_active, ":farmer_party_no"),
        (store_faction_of_party, ":center_faction", ":center_no"),
        (party_set_faction, ":farmer_party_no", ":center_faction"),
      (try_end),

    (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),
		(gt, ":lord_troop_id", -1),
		
#normal_banner_begin
        (troop_get_slot, ":cur_banner", ":lord_troop_id", slot_troop_banner_scene_prop),
        (gt, ":cur_banner", 0),
        (val_sub, ":cur_banner", banner_scene_props_begin),
        (val_add, ":cur_banner", banner_map_icons_begin),
        (party_set_banner_icon, ":center_no", ":cur_banner"),
# custom_banner_begin
#        (troop_get_slot, ":flag_icon", ":lord_troop_id", slot_troop_custom_banner_map_flag_type),
#        (ge, ":flag_icon", 0),
#        (val_add, ":flag_icon", custom_banner_map_icons_begin),
#        (party_set_banner_icon, ":center_no", ":flag_icon"),
    (try_end),

#    (try_begin),
#		(eq, 1, 0),
 #       (eq, ":lord_troop_id", "trp_player"),
 #       (neq, ":old_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),
 #       (gt, ":old_lord_troop_id", 0),
 #       (call_script, "script_change_player_relation_with_troop", ":old_lord_troop_id", -25),
 #   (try_end),
	(try_begin),
		(gt, ":lord_troop_id", -1),
        (call_script, "script_troop_set_title_according_to_faction", ":lord_troop_id", ":lord_troop_faction"),
		(call_script, "script_update_troop_notes", ":lord_troop_id"),
	(try_end),
	
    (call_script, "script_update_center_notes", ":center_no"),
    
    (try_begin),
      (gt, ":lord_troop_faction", 0),
      (call_script, "script_update_faction_notes", ":lord_troop_faction"),
    (try_end),  
    
    (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_troop_set_title_according_to_faction", ":old_lord_troop_id", ":old_lord_troop_faction"),
        (call_script, "script_update_faction_notes", ":old_lord_troop_faction"),
    (try_end),

    (try_begin),
        (eq, ":add_garrison", 1),
        (this_or_next|party_slot_eq, ":center_no", slot_party_type, spt_town),
			(party_slot_eq, ":center_no", slot_party_type, spt_castle),
        (assign, ":garrison_strength", 3), 
        (try_begin),
          (party_slot_eq, ":center_no", slot_party_type, spt_town),
          (assign, ":garrison_strength", 9),
        (try_end),
        (try_for_range, ":unused", 0, ":garrison_strength"),
          (call_script, "script_cf_reinforce_party", ":center_no"),
        (try_end),
        ## ADD some XP initially
        (try_for_range, ":unused", 0, 7),
          (store_mul, ":xp_range_min", 150, ":garrison_strength"),
          (store_mul, ":xp_range_max", 200, ":garrison_strength"),
          (store_random_in_range, ":xp", ":xp_range_min", ":xp_range_max"),
          (party_upgrade_with_xp, ":center_no", ":xp", 0),
        (try_end),
    (try_end),

	(faction_get_slot, ":faction_leader", ":lord_troop_faction", slot_faction_leader),
	(store_current_hours, ":hours"),
	
	#the next block handles gratitude, objections and jealousies
	(try_begin),
	  	(gt, ":hours", 0),
		(gt, ":lord_troop_id", 0),
		
    	(call_script, "script_troop_change_relation_with_troop", ":lord_troop_id", ":faction_leader", 10),
		(val_add, "$total_promotion_changes", 10),
		
		#smaller factions are more dramatically influenced by internal jealousies
		#Disabled as of NOV 2010
#		(try_begin),
#			(neg|faction_slot_ge, ":lord_troop_faction", slot_faction_number_of_parties, 4),
#			(assign, ":faction_size_multiplier", 6),
#		(else_try),
#			(neg|faction_slot_ge, ":lord_troop_faction", slot_faction_number_of_parties, 8),
#			(assign, ":faction_size_multiplier", 5),
#		(else_try),
#			(neg|faction_slot_ge, ":lord_troop_faction", slot_faction_number_of_parties, 16),
#			(assign, ":faction_size_multiplier", 4),
#		(else_try),
#			(neg|faction_slot_ge, ":lord_troop_faction", slot_faction_number_of_parties, 32),
#			(assign, ":faction_size_multiplier", 3),
#		(else_try),	
#			(assign, ":faction_size_multiplier", 2),
#		(try_end),
		
		#factional politics -- each lord in the faction adjusts his relation according to the relation with the lord receiving the faction
		(try_for_range, ":other_lord", active_npcs_begin, active_npcs_end),
			(troop_slot_eq, ":other_lord", slot_troop_occupation, slto_kingdom_hero),
			(neq, ":other_lord", ":lord_troop_id"),
			
		    (store_troop_faction, ":other_troop_faction", ":other_lord"),
		    (eq, ":lord_troop_faction", ":other_troop_faction"),

		    (neq, ":other_lord", ":faction_leader"),
			
	        (call_script, "script_troop_get_relation_with_troop", ":other_lord", ":lord_troop_id"),
			(assign, ":relation_with_troop", reg0),

			#relation reduction = relation/10 minus 2. So,0 = -2, 8 = -1, 16+ = no change or bonus, 24+ gain one point
		    (store_div, ":relation_with_liege_change", ":relation_with_troop", 8), #changed from 16
		    (val_sub, ":relation_with_liege_change", 2),

		    (val_clamp, ":relation_with_liege_change", -5, 3),
			
			(try_begin),
				#upstanding and goodnatured lords will not lose relation unless they actively dislike the other lord
				(this_or_next|troop_slot_eq, ":other_lord", slot_lord_reputation_type, lrep_upstanding),
					(troop_slot_eq, ":other_lord", slot_lord_reputation_type, lrep_goodnatured),
				(ge, ":relation_with_troop", 0),
				(val_max, ":relation_with_liege_change", 0),
			(else_try),
				#penalty is increased for lords who have the more unpleasant reputation types
				(this_or_next|troop_slot_eq, ":other_lord", slot_lord_reputation_type, lrep_selfrighteous),
				(this_or_next|troop_slot_eq, ":other_lord", slot_lord_reputation_type, lrep_debauched),
					(troop_slot_eq, ":other_lord", slot_lord_reputation_type, lrep_quarrelsome),
				(lt, ":relation_with_liege_change", 0),
				(val_mul, ":relation_with_liege_change", 3),
				(val_div, ":relation_with_liege_change", 2),
			(try_end),

			
		    (neq, ":relation_with_liege_change", 0),
			#removed Nov 2010
#		  	(val_mul, ":relation_reduction", ":faction_size_multiplier"),
#		  	(val_div, ":relation_reduction", 2),
			#removed Nov 2010
			
			(try_begin),
				(troop_slot_eq, ":other_lord", slot_troop_stance_on_faction_issue, ":lord_troop_id"),
				(val_add, ":relation_with_liege_change", 1),
				(val_max, ":relation_with_liege_change", 1),
			(try_end),
			
 	        (call_script, "script_troop_change_relation_with_troop", ":other_lord", ":faction_leader", ":relation_with_liege_change"),
			(val_add, "$total_promotion_changes", ":relation_with_liege_change"),
			
		    (try_begin),
				(this_or_next|le, ":relation_with_liege_change", -4), #Nov 2010 - changed from -8
				(this_or_next|troop_slot_eq, ":other_lord", slot_troop_promised_fief, 1), #1 is any fief
					(troop_slot_eq, ":other_lord", slot_troop_promised_fief, ":center_no"),
				(call_script, "script_add_log_entry", logent_troop_feels_cheated_by_troop_over_land, ":other_lord", ":center_no", ":lord_troop_id", ":lord_troop_faction"),
		    (try_end),
		  
		(try_end),
	(try_end),
	
	#Villages from another faction will also be transferred along with a fortress
    (try_begin),
		(is_between, ":center_no", walled_centers_begin, walled_centers_end),
        (try_for_range, ":cur_village", villages_begin, villages_end),
			(party_slot_eq, ":cur_village", slot_village_bound_center, ":center_no"),
			(store_faction_of_party, ":cur_village_faction", ":cur_village"),
			(neq, ":cur_village_faction", ":lord_troop_faction"),
			
			(call_script, "script_give_center_to_lord", ":cur_village", ":lord_troop_id", 0),
        (try_end),
    (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_cf_get_random_enemy_center
  # Input: arg1 = party_no
  # Output: reg0 = center_no
  ("cf_get_random_enemy_center",
    [
      (store_script_param_1, ":party_no"),
      
      (assign, ":result", -1),
      (assign, ":total_enemy_centers", 0),
      (store_faction_of_party, ":party_faction", ":party_no"),
      
      (try_for_range, ":center_no", centers_begin, centers_end),
        (store_faction_of_party, ":center_faction", ":center_no"),
        (store_relation, ":party_relation", ":center_faction", ":party_faction"),
        (lt, ":party_relation", 0),
        (val_add, ":total_enemy_centers", 1),
      (try_end),

      (gt, ":total_enemy_centers", 0),
      (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"),
        (store_relation, ":party_relation", ":center_faction", ":party_faction"),
        (lt, ":party_relation", 0),
        (val_sub, ":random_center", 1),
        (lt, ":random_center", 0),
        (assign, ":result", ":center_no"),
      (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", ":party_no"),
##      
##      (try_for_range, ":center_no", towns_begin, towns_end),
##        (store_faction_of_party, ":center_faction", ":center_no"),
##        (neq, ":center_faction", ":party_faction"),
##        (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"),
##          (store_relation, ":party_relation", ":center_faction", ":party_faction"),
##          (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"),
        (call_script, "script_npc_get_troop_wage", ":stack_troop", ":party_no"),
        (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
  ("calculate_player_faction_wage",
    [(assign, ":nongarrison_wages", 0),
     (assign, ":garrison_wages", 0),
     (try_for_parties, ":party_no"),
       (assign, ":garrison_troop", 0),
       (try_begin),
         (this_or_next|party_slot_eq, ":party_no", slot_party_type, spt_town),
         (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_no", "p_main_party"),
       (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"),
         (call_script, "script_game_get_troop_wage", ":stack_troop", ":party_no"),
         (assign, ":cur_wage", reg0),
         (val_mul, ":cur_wage", ":stack_size"),
         (try_begin),
           (eq, ":garrison_troop", 1),
           (val_add, ":garrison_wages", ":cur_wage"),
         (else_try),
           (val_add, ":nongarrison_wages", ":cur_wage"),
         (try_end),
       (try_end),
     (try_end),
     (val_div, ":garrison_wages", 2),#Half payment for garrisons
     (store_sub, ":total_payment", 14, "$g_cur_week_half_daily_wage_payments"), #between 0 and 7
     (val_mul, ":nongarrison_wages", ":total_payment"),
     (val_div, ":nongarrison_wages", 14),
     (store_add, reg0, ":nongarrison_wages", ":garrison_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", 750), #let every hero receive 750 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", 1000),
      (try_end),
      
      (try_begin), #check if troop is marshall
        (faction_slot_eq, ":faction_no", slot_faction_marshall, ":troop_no"),
        (val_add, ":weekly_income", 1000),
      (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"),
	  
	  (try_begin),
		(lt, ":cur_wealth", 0),
		(store_sub, ":percent_under", 0, ":cur_wealth"),
		(val_mul, ":percent_under", 100),
		(val_div, ":percent_under", ":cur_weekly_wage"),
		(val_div, ":percent_under", 5), #Max 20 percent
		
		(call_script, "script_party_inflict_attrition", ":party_no", ":percent_under", 1),
	  (try_end),
	  
      (val_max, ":cur_wealth", 0),
      (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
  # Called from several places, simple_triggers for centers, script_hire_men_to_kingdom_hero_party for hero parties
  ("cf_reinforce_party",
    [
      (store_script_param_1, ":party_no"),
      
      (store_faction_of_party, ":party_faction", ":party_no"),
      (party_get_slot, ":party_type",":party_no", slot_party_type),

#Rebellion changes begin: 
      (try_begin),
        (eq, ":party_type", spt_kingdom_hero_party),
        (party_stack_get_troop_id, ":leader", ":party_no"),
        (troop_get_slot, ":party_faction",  ":leader", slot_troop_original_faction),
      (try_end),
#Rebellion changes end

      (try_begin),
        (eq, ":party_faction", "fac_player_supporters_faction"),
        (party_get_slot, ":town_lord", ":party_no", slot_town_lord),
        (try_begin),
          (gt, ":town_lord", 0),
          (troop_get_slot, ":party_faction", ":town_lord", slot_troop_original_faction),
        (else_try),
          (party_get_slot, ":party_faction", ":party_no", slot_center_original_faction),
        (try_end),
      (try_end),
      
      (faction_get_slot, ":party_template_a", ":party_faction", slot_faction_reinforcements_a),
      (faction_get_slot, ":party_template_b", ":party_faction", slot_faction_reinforcements_b),
      (faction_get_slot, ":party_template_c", ":party_faction", 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", 65),
          (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", 50),
          (assign, ":party_template", ":party_template_a"),
        (else_try),
          (lt, ":rand", 75),
          (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),
      
      #while hiring reinforcements party leaders can only use 3/4 of their budget. This value is holding in ":hiring budget".
      (assign, ":hiring_budget", ":cur_wealth"),
      (val_mul, ":hiring_budget", 3),
      (val_div, ":hiring_budget", 4),            
    
      (call_script, "script_party_get_ideal_size", ":party_no"),
      (assign, ":ideal_size", reg0),
      (store_mul, ":ideal_top_size", ":ideal_size", 3),
      (val_div, ":ideal_top_size", 2),

	  #(try_begin),
	  #	(ge, "$cheat_mode", 1),
      #  (str_store_troop_name, s7, ":troop_no"),
      #  (assign, reg9, ":cur_wealth"),
      #  (display_message, "@{!}DEBUGS : {s7} total budget is {reg9}"),
      #  (assign, reg6, ":ideal_size"),
      #  (assign, reg7, ":ideal_top_size"),
      #  (assign, reg8, ":hiring_budget"),
      #  (display_message, "str_debug__hiring_men_to_s7_ideal_size__reg6_ideal_top_size__reg7_hiring_budget__reg8"),
      #(try_end),
	  	  
      (party_get_num_companions, ":party_size", ":party_no"),
      
      (store_faction_of_party, ":party_faction", ":party_no"),
      (try_begin),
        (this_or_next|eq, ":party_faction", "fac_player_supporters_faction"),
        (eq, ":party_faction", "$players_kingdom"),        
        (assign, ":reinforcement_cost", reinforcement_cost_moderate),
      (else_try),
        (game_get_reduce_campaign_ai, ":reduce_campaign_ai"),
        (assign, ":reinforcement_cost", reinforcement_cost_moderate),
        (try_begin), 
          (eq, ":reduce_campaign_ai", 0), #hard
          (assign, ":reinforcement_cost", reinforcement_cost_hard),
        (else_try), 
          (eq, ":reduce_campaign_ai", 1), #moderate
          (assign, ":reinforcement_cost", reinforcement_cost_moderate),
        (else_try), 
          (eq, ":reduce_campaign_ai", 2), #easy
          (assign, ":reinforcement_cost", reinforcement_cost_easy),
        (try_end),           
      (try_end),  
      
      (assign, ":num_rounds", 1),            
      (try_for_range, ":unused", 0 , ":num_rounds"),
        (try_begin),
          (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"),
        (else_try),
          (gt, ":party_size", ":ideal_top_size"),
          (store_troop_faction, ":troop_faction", ":troop_no"),
          (party_get_num_companion_stacks, ":num_stacks", ":party_no"),
          (assign, ":total_regulars", 0),
          (assign, ":total_regular_levels", 0),
          (try_for_range_backwards, ":i_stack", 0, ":num_stacks"),
            (party_stack_get_troop_id, ":stack_troop", ":party_no", ":i_stack"),
            (neg|troop_is_hero, ":stack_troop"),
            (party_stack_get_size, ":stack_size", ":party_no", ":i_stack"),
            (store_character_level, ":stack_level", ":stack_troop"),
            (store_troop_faction, ":stack_faction", ":stack_troop"),
            (try_begin),
              (eq, ":troop_faction", ":stack_faction"),
              (val_mul, ":stack_level", 3), #reducing the chance of the faction troops' removal
            (try_end),
            (val_mul, ":stack_level", ":stack_size"),
            (val_add, ":total_regulars", ":stack_size"),
            (val_add, ":total_regular_levels", ":stack_level"),
          (try_end),
          (gt, ":total_regulars", 0),
          (store_div, ":average_level", ":total_regular_levels", ":total_regulars"),
          (try_for_range_backwards, ":i_stack", 0, ":num_stacks"),
            (party_stack_get_troop_id, ":stack_troop", ":party_no", ":i_stack"),
            (neg|troop_is_hero, ":stack_troop"),
            (party_stack_get_size, ":stack_size", ":party_no", ":i_stack"),
            (store_character_level, ":stack_level", ":stack_troop"),
            (store_troop_faction, ":stack_faction", ":stack_troop"),
            (try_begin),
              (eq, ":troop_faction", ":stack_faction"),
              (val_mul, ":stack_level", 3),
            (try_end),
            (store_sub, ":level_dif", ":average_level", ":stack_level"),
            (val_div, ":level_dif", 3),
            (store_add, ":prune_chance", 10, ":level_dif"),
            (gt, ":prune_chance", 0),
            (call_script, "script_get_percentage_with_randomized_round", ":stack_size", ":prune_chance"),
            (gt, reg0, 0),
            (party_remove_members, ":party_no", ":stack_troop", reg0),
          (try_end),
        (try_end),
      (try_end),
  ]),

  # script_get_percentage_with_randomized_round
  # Input: arg1 = value, arg2 = percentage
  # Output: none
  ("get_percentage_with_randomized_round",
    [
      (store_script_param, ":value", 1),
      (store_script_param, ":percentage", 2),

      (store_mul, ":result", ":value", ":percentage"),
      (val_div, ":result", 100),
      (store_mul, ":used_amount", ":result", 100),
      (val_div, ":used_amount", ":percentage"),
      (store_sub, ":left_amount", ":value", ":used_amount"),
      (try_begin),
        (gt, ":left_amount", 0),
        (store_mul, ":chance", ":left_amount", ":percentage"),
        (store_random_in_range, ":random_no", 0, 100),
        (lt, ":random_no", ":chance"),
        (val_add, ":result", 1),
      (try_end),
      (assign, reg0, ":result"),
      ]),
  
  # 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", slfot_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_cattle_herd
  # Input: arg1 = center_no, arg2 = amount (0 = default)
  # Output: reg0 = party_no
  ("create_cattle_herd",
    [
      (store_script_param_1, ":center_no"),
      (store_script_param_2, ":amount"),
      
      (assign, ":herd_party", -1),
      (set_spawn_radius,1),

      (spawn_around_party,":center_no", "pt_cattle_herd"),
      (assign, ":herd_party", reg0),
      (party_get_position, pos1, ":center_no"),
      (call_script, "script_map_get_random_position_around_position_within_range", 1, 2),
      (party_set_position, ":herd_party", pos2),

      (party_set_slot, ":herd_party", slot_party_type, spt_cattle_herd),
      (party_set_slot, ":herd_party", slot_party_ai_state, spai_undefined),
      (party_set_ai_behavior, ":herd_party", ai_bhvr_hold),

      (party_set_slot, ":herd_party", slot_party_commander_party, -1), #we need this because 0 is player's party!

      (try_begin),
        (gt, ":amount", 0),
        (party_clear, ":herd_party"),
        (party_add_members, ":herd_party", "trp_cattle", ":amount"),
      (try_end),
       
      (assign, reg0, ":herd_party"),
  ]),

  #script_buy_cattle_from_village
  # Input: arg1 = village_no, arg2 = amount, arg3 = single_cost
  # Output: reg0 = party_no
  ("buy_cattle_from_village",
    [
      (store_script_param, ":village_no", 1),
      (store_script_param, ":amount", 2),
      (store_script_param, ":single_cost", 3),

      #Changing price of the cattle
      (try_for_range, ":unused", 0, ":amount"),
        (call_script, "script_game_event_buy_item", "itm_cattle_meat", 0),
        (call_script, "script_game_event_buy_item", "itm_cattle_meat", 0),
      (try_end),

      (party_get_slot, ":num_cattle", ":village_no", slot_village_number_of_cattle),
      (val_sub, ":num_cattle", ":amount"),
      (party_set_slot, ":village_no", slot_village_number_of_cattle, ":num_cattle"),
      (store_mul, ":cost", ":single_cost", ":amount"),
      (troop_remove_gold, "trp_player", ":cost"),
	  # NE finances
	  (val_mul,":cost",-1),
      (call_script, "script_adjust_finances", slot_finance_cattle_bought, ":cost"),
	  # NE end finances

      (assign, ":continue", 1),
      (try_for_parties, ":cur_party"),
        (eq, ":continue", 1),
        (party_slot_eq, ":cur_party", slot_party_type, spt_cattle_herd),
        (store_distance_to_party_from_party, ":dist", ":village_no", ":cur_party"),
        (lt, ":dist", 6),
        (assign, ":subcontinue", 1),
        (try_begin),
          (check_quest_active, "qst_move_cattle_herd"),
          (quest_slot_eq, "qst_move_cattle_herd", slot_quest_target_party, ":cur_party"),
          (assign, ":subcontinue", 0),
        (try_end),
        (eq, ":subcontinue", 1),
        (party_add_members, ":cur_party", "trp_cattle", ":amount"),
        (assign, ":continue", 0),
        (assign, reg0, ":cur_party"),
      (try_end),
      (try_begin),
        (eq, ":continue", 1),
        (call_script, "script_create_cattle_herd", ":village_no", ":amount"),
      (try_end),
  ]),

  #script_kill_cattle_from_herd
  # Input: arg1 = party_no, arg2 = amount
  # Output: none (fills trp_temp_troop's inventory)
  ("kill_cattle_from_herd",
    [
      (store_script_param_1, ":party_no"),
      (store_script_param_2, ":amount"),

      (troop_clear_inventory, "trp_temp_troop"),
      (store_mul, ":meat_amount", ":amount", 2),
      (troop_add_items, "trp_temp_troop", "itm_cattle_meat", ":meat_amount"),

      (troop_get_inventory_capacity, ":inv_size", "trp_temp_troop"),
      (try_for_range, ":i_slot", 0, ":inv_size"),
        (troop_get_inventory_slot, ":item_id", "trp_temp_troop", ":i_slot"),
        (eq, ":item_id", "itm_cattle_meat"),
        (troop_set_inventory_slot_modifier, "trp_temp_troop", ":i_slot", imod_fresh),
      (try_end),

      (party_get_num_companions, ":num_cattle", ":party_no"),
      (try_begin),
        (ge, ":amount", ":num_cattle"),
        (remove_party, ":party_no"),
      (else_try),
        (party_remove_members, ":party_no", "trp_cattle", ":amount"),
      (try_end),
      ]),
  
  # script_create_kingdom_hero_party
  # Input: arg1 = troop_no, arg2 = center_no
  # Output: $pout_party = party_no
  ("create_kingdom_hero_party",
    [
      (store_script_param, ":troop_no", 1),
      (store_script_param, ":center_no", 2),
     
      (store_troop_faction, ":troop_faction_no", ":troop_no"),
      
      (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),
      (call_script, "script_party_set_ai_state", "$pout_party", spai_undefined, -1),
      (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"),
      
      (party_set_slot, "$pout_party", slot_party_commander_party, -1), #we need this because 0 is player's party!

      #Setting base icon
      (call_script, "script_set_icon_for_lord_party", ":troop_no"),

      #Setting the flag icon
      #normal_banner_begin
      (troop_get_slot, ":cur_banner", ":troop_no", slot_troop_banner_scene_prop),
      (try_begin),
        (gt, ":cur_banner", 0),
        (val_sub, ":cur_banner", banner_scene_props_begin),
        (val_add, ":cur_banner", banner_map_icons_begin),
        (party_set_banner_icon, "$pout_party", ":cur_banner"),
      ##custom_banner_begin
      ##(troop_get_slot, ":flag_icon", ":troop_no", slot_troop_custom_banner_map_flag_type),
      #(#try_begin),
      ##  (ge, ":flag_icon", 0),
      # # (val_add, ":flag_icon", custom_banner_map_icons_begin),
      # # (party_set_banner_icon, "$pout_party", ":flag_icon"),
      (try_end),

      (try_begin),
        #because of below two lines, lords can only hire more than one party_template(stack) at game start once a time during all game.
        (troop_slot_eq, ":troop_no", slot_troop_spawned_before, 0),
        (troop_set_slot, ":troop_no", slot_troop_spawned_before, 1),
        (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),

        #(str_store_troop_name, s0, ":troop_no"),
        #(display_message, "{!}str_debug__hiring_men_to_party_for_s0"),

        (try_for_range, ":unused", 0, ":num_tries"),
          (call_script, "script_hire_men_to_kingdom_hero_party", ":troop_no"),
        (try_end),
        
        (assign, ":xp_rounds", 0),

        (game_get_reduce_campaign_ai, ":reduce_campaign_ai"),
        (try_begin),
          (this_or_next|eq, ":troop_faction_no", "$players_kingdom"),
          (eq, ":troop_faction_no", "fac_player_supporters_faction"),
          (assign, ":xp_rounds", 0),
        (else_try),
          (eq, ":reduce_campaign_ai", 0), #hard
          (assign, ":xp_rounds", 2),
        (else_try),
          (eq, ":reduce_campaign_ai", 1), #moderate
          (assign, ":xp_rounds", 1),
        (else_try),                        
          (eq, ":reduce_campaign_ai", 2), #easy
          (assign, ":xp_rounds", 0),
        (try_end),           

        (troop_get_slot, ":renown", ":troop_no", slot_troop_renown),
        (store_div, ":renown_xp_rounds", ":renown", 100),
        (val_add, ":xp_rounds", ":renown_xp_rounds"),
        (try_for_range, ":unused", 0, ":xp_rounds"),
          (call_script, "script_upgrade_hero_party", "$pout_party", 4000),
        (try_end),
      (try_end),      
  ]),
  
# NE dk
  # script_create_kingdom_hero_party_dk
  # Input: arg1 = troop_no, arg2 = center_no
  # Output: $pout_party = party_no
  ("create_kingdom_hero_party_dk",
    [
      (store_script_param, ":troop_no", 1),
      (store_script_param, ":center_no", 2),
     
      (store_troop_faction, ":troop_faction_no", ":troop_no"),
      
	  
	  
	 (str_store_faction_name, s4, ":troop_faction_no"),
	 (str_store_troop_name, s5, ":troop_no"),
     # (display_message, "@{!}DEBUG -- Faction {s4} troop fucking {s5}"),
			
      (assign, "$pout_party", -1),
      (set_spawn_radius, 2),
      (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),
      (call_script, "script_party_set_ai_state", "$pout_party", spai_undefined, -1),
      (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"),
      
      (party_set_slot, "$pout_party", slot_party_commander_party, -1), #we need this because 0 is player's party!

      #Setting the flag icon
      #normal_banner_begin
      (troop_get_slot, ":cur_banner", ":troop_no", slot_troop_banner_scene_prop),
      (try_begin),
        (gt, ":cur_banner", 0),
        (val_sub, ":cur_banner", banner_scene_props_begin),
        (val_add, ":cur_banner", banner_map_icons_begin),
        (party_set_banner_icon, "$pout_party", ":cur_banner"),
      #custom_banner_begin
      #(troop_get_slot, ":flag_icon", ":troop_no", slot_troop_custom_banner_map_flag_type),
      #(try_begin),
      #  (ge, ":flag_icon", 0),
      #  (val_add, ":flag_icon", custom_banner_map_icons_begin),
      #  (party_set_banner_icon, "$pout_party", ":flag_icon"),
      (try_end),

      (try_begin),
        #because of below two lines, lords can only hire more than one party_template(stack) at game start once a time during all game.
        (troop_slot_eq, ":troop_no", slot_troop_spawned_before, 0),
        (troop_set_slot, ":troop_no", slot_troop_spawned_before, 1),
        (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),

        #(str_store_troop_name, s0, ":troop_no"),
        #(display_message, "{!}str_debug__hiring_men_to_party_for_s0"),

        (try_for_range, ":unused", 0, ":num_tries"),
          (call_script, "script_hire_men_to_kingdom_hero_party", ":troop_no"),
        (try_end),
        
        (assign, ":xp_rounds", 0),

        (game_get_reduce_campaign_ai, ":reduce_campaign_ai"),
        (try_begin),
          (this_or_next|eq, ":troop_faction_no", "$players_kingdom"),
          (eq, ":troop_faction_no", "fac_player_supporters_faction"),
          (assign, ":xp_rounds", 0),
        (else_try),
          (eq, ":reduce_campaign_ai", 0), #hard
          (assign, ":xp_rounds", 2),
        (else_try),
          (eq, ":reduce_campaign_ai", 1), #moderate
          (assign, ":xp_rounds", 1),
        (else_try),                        
          (eq, ":reduce_campaign_ai", 2), #easy
          (assign, ":xp_rounds", 0),
        (try_end),           

        (troop_get_slot, ":renown", ":troop_no", slot_troop_renown),
        (store_div, ":renown_xp_rounds", ":renown", 100),
        (val_add, ":xp_rounds", ":renown_xp_rounds"),
        (try_for_range, ":unused", 0, ":xp_rounds"),
          (call_script, "script_upgrade_hero_party", "$pout_party", 4000),
        (try_end),
      (try_end),      
  ]),
  
  # NE end dk
  
  
  # 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"),

      (call_script, "script_count_parties_of_faction_and_party_type", ":faction_no", ":party_type"),
      (assign, ":party_count", reg0),
      
      (assign, ":party_count_limit", 0),

      (faction_get_slot, ":num_towns", ":faction_no", slot_faction_num_towns),

      (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),
        (try_begin),
          (eq, ":num_towns", 0),
          (assign, ":party_count_limit", 0),
        (else_try),
          (eq, ":num_towns", 1),
          (assign, ":party_count_limit", 1),
        (else_try),
          (eq, ":num_towns", 2),
          (assign, ":party_count_limit", 3),
        (else_try),
          (assign, ":party_count_limit", 5),
        (try_end),
##      (else_try),
##        (eq, ":party_type", spt_prisoner_train),
##        (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"),
      (try_end),
      
      (assign, ":result", -1),
      (try_begin),
        (try_begin),
          (eq, ":party_type", spt_kingdom_caravan),
          (call_script,"script_cf_select_random_town_with_faction", ":faction_no", -1),
          (set_spawn_radius, 0),
        (else_try), #not used at the moment
          (call_script,"script_cf_select_random_walled_center_with_faction", ":faction_no", -1),
          (set_spawn_radius, 1),
        (try_end),
        (assign, ":spawn_center", reg0),
        (is_between, ":spawn_center", centers_begin, centers_end),
        (spawn_around_party,":spawn_center",":party_template"),
        (assign, ":result", reg0),
        (party_set_faction, ":result", ":faction_no"),
        (try_begin),
          (eq, ":party_type", spt_kingdom_caravan),
          (party_set_slot, ":result", slot_party_home_center, ":spawn_center"),
# NE building
#Escort stuff - Jinnai
          (party_slot_eq, ":spawn_center", slot_center_has_caravan_escort, 1),
          (store_random_in_range,":rand",8,11),
          (party_add_members, ":result", "trp_mercenary_crossbowman", ":rand"),
          (store_random_in_range,":rand",8,11),
          (party_add_members, ":result", "trp_female_archer", ":rand"),
          (store_random_in_range,":rand",8,11),
          (party_add_members, ":result", "trp_mercenary_swordsman", ":rand"),
          (store_random_in_range,":rand",3,9),
          (party_add_members, ":result", "trp_mercenary_equite", ":rand"),
          (store_random_in_range,":rand",3,9),
          (party_add_members, ":result", "trp_female_shield_sister", ":rand"),
# ne end building		  	  
          (party_set_slot, ":result", slot_party_last_traded_center, ":spawn_center"),
		(try_end),
        (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),
          (try_begin),
            (eq, ":faction_no", "fac_player_supporters_faction"),
            (party_get_slot, ":reinforcement_faction", ":spawn_center", slot_center_original_faction),
            (faction_get_slot, ":reinforcements_b", ":reinforcement_faction", slot_faction_reinforcements_b),
          (try_end),
          (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,3),
##            (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),
        (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),
        (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", 50000),
      (else_try),
        (party_slot_eq, ":center_no", slot_party_type, spt_castle),
        (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_elder),
      (reset_item_probabilities,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),
	    (call_script, "script_center_get_production", ":village_no", ":cur_goods"),
		(assign, ":cur_probability", reg0),
	    (call_script, "script_center_get_consumption", ":village_no", ":cur_goods"),
		(val_add, ":cur_probability", reg0),
	  
	    (try_begin),
			(this_or_next|eq, ":cur_goods", "itm_chicken"),
				(eq, ":cur_goods", "itm_pork"),
			(assign, ":cur_probability", 5),
	    (try_end),
	  
	    (val_mul, ":cur_probability", 3),
	  
        (store_add, ":cur_price_slot", ":cur_goods", ":item_to_price_slot"),
        (party_get_slot, ":cur_price", ":village_no", ":cur_price_slot"),
        (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"),
#        (val_mul, ":cur_probability", average_price_factor),
#        (val_div, ":cur_probability", ":cur_price"),
        (set_item_probability_in_merchandise, ":cur_goods", ":cur_probability"),
      (try_end),
#      (set_item_probability_in_merchandise, "itm_spice", 0),
#      (set_item_probability_in_merchandise, "itm_velvet", 0),

	  (try_begin),
		(party_get_slot, ":prosperity", ":village_no", slot_town_prosperity),
		(val_div, ":prosperity", 17), #up to 5
		(store_add, ":number_of_goods", ":prosperity", 1),
	  (try_end),

      (troop_add_merchandise, ":merchant_troop", itp_type_goods, ":number_of_goods"),
      (troop_ensure_inventory_space, ":merchant_troop", 80),

      #Adding 1 prosperity to the village while reducing each 3000 gold from the elder
      (store_troop_gold, ":gold",":merchant_troop"),
      (try_begin),
        (gt, ":gold", 3500),
        (store_div, ":prosperity_added", ":gold", 3000),
        (store_mul, ":gold_removed", ":prosperity_added", 3000),
        (troop_remove_gold, ":merchant_troop", ":gold_removed"),
        (call_script, "script_change_center_prosperity", ":village_no", ":prosperity_added"),
      (try_end),

# NE building
## Distillery stuff - Jinnai
      (try_begin),
        (party_slot_eq, ":village_no", slot_center_has_distillery, 1),
        (store_random_in_range,":rand",1,3),
        (try_for_range, ":unused", 0, ":rand"),
          (troop_add_item,":merchant_troop",itm_ale,0),
        (try_end),
        (store_random_in_range,":rand",1,3),
        (try_for_range, ":unused", 0, ":rand"),
          (troop_add_item,":merchant_troop",itm_wine,0),
        (try_end),
      (try_end),

# Ne end building	  
	  
	  
	  
	  
	  
  ]),

  # 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),
        (call_script, "script_change_center_prosperity", ":village_no", -60), #reduced from 30
		(val_add, "$newglob_total_prosperity_from_villageloot", -60),

		(try_begin), #optional - lowers the relationship between a lord and his liege if his fief is looted
			(eq, 5, 0),
			(party_get_slot, ":town_lord", ":village_no", slot_town_lord),
			(is_between, ":town_lord", active_npcs_begin, active_npcs_end),
			(store_faction_of_troop, ":town_lord_faction", ":town_lord"),
			(faction_get_slot, ":faction_leader", ":town_lord_faction", slot_faction_leader),
			(call_script, "script_troop_change_relation_with_troop", ":town_lord", ":faction_leader", -1),
			(val_add, "$total_battle_ally_changes", -1),
		(try_end),
      (else_try),
        (eq, ":new_state", svs_under_siege),
        (party_set_extra_text, ":village_no", "@(Under Siege)"),
				
		#Divert all caravans heading to the center
		#Note that occasionally, no alternative center will be found. In that case, the caravan will try to run the blockade
		(try_for_parties, ":party_no"), 
			(gt, ":party_no", "p_spawn_points_end"),
			(party_slot_eq, ":party_no", slot_party_type, spt_kingdom_caravan),
            (party_slot_eq, ":party_no", slot_party_ai_object, ":village_no"),

			(party_get_slot, ":origin", ":party_no", slot_party_last_traded_center),
			(store_faction_of_party, ":merchant_faction", ":party_no"),
			
            (call_script, "script_cf_select_most_profitable_town_at_peace_with_faction_in_trade_route", ":origin", ":merchant_faction"),
            (assign, ":target_center", reg0),
			(is_between, ":target_center", centers_begin, centers_end),
			
            (party_set_ai_behavior, ":party_no", ai_bhvr_travel_to_party),
            (party_set_ai_object, ":party_no", ":target_center"),
            (party_set_flags, ":party_no", pf_default_behavior, 0),
            (party_set_slot, ":party_no", slot_party_ai_state, spai_trading_with_town),
            (party_set_slot, ":party_no", slot_party_ai_object, ":target_center"),
		(try_end),		
      (try_end),
      (party_set_slot, ":village_no", slot_village_state, ":new_state"),
  ]),


  # script_process_village_raids
  # Input: none
  # Output: none
  # called from triggers every two hours
  ("process_village_raids",
    [
       (try_for_range, ":village_no", villages_begin, villages_end),
         # CABA's patch from Native
         (try_begin), 
           (this_or_next|is_between, ":village_no", "p_village_16", "p_village_23"), #Shapeshte through Shulus (up to Ilvia) 
           (this_or_next|is_between, ":village_no", "p_village_49", "p_village_51"), #Tismirr and Karindi 
           (this_or_next|eq, ":village_no", "p_village_75"), #Bhulaban 
           (is_between, ":village_no", "p_village_85", "p_village_87"), #Ismirala and Slezkh 
           (assign, ":normal_village_icon", "icon_village_snow_a"),  
           (assign, ":burnt_village_icon", "icon_village_snow_burnt_a"), 
           (assign, ":deserted_village_icon", "icon_village_snow_deserted_a"), 
         (else_try), 
           (is_between, ":village_no", "p_village_91", "p_salt_mine"), #Ayn Assuadi through Rushdigh 
           (assign, ":normal_village_icon", "icon_village_c"),  
           (assign, ":burnt_village_icon", "icon_village_burnt_c"), 
           (assign, ":deserted_village_icon", "icon_village_deserted_c"), 
         (else_try), 
           (assign, ":normal_village_icon", "icon_village_a"), 
           (assign, ":burnt_village_icon", "icon_village_burnt_a"), 
           (assign, ":deserted_village_icon", "icon_village_deserted_a"), 
         (try_end), 
         # End patch
         (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", 5),
           (val_max, ":village_raid_progress", 0),
           (party_set_slot, ":village_no", slot_village_raid_progress, ":village_raid_progress"),
           (try_begin),
             (lt, ":village_raid_progress", 50),
             
             (try_begin),
               (party_get_icon, ":village_icon", ":village_no"),
               (neq, ":village_icon", "icon_village_a"),
               (party_set_icon, ":village_no", ":normal_village_icon"),
             (try_end),
             
             (party_slot_ge, ":village_no", slot_village_smoke_added, 1),
             (party_set_slot, ":village_no", slot_village_smoke_added, 0),             
             (party_clear_particle_systems, ":village_no"),
           (try_end),
         (else_try),
           (party_slot_eq, ":village_no", slot_village_state, svs_being_raided), #village is being raided
           #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", svs_normal), #clear raid flag
             (party_set_slot, ":village_no", slot_village_smoke_added, 0),
             (party_clear_particle_systems, ":village_no"),                          
           (else_try),
             (assign, ":raid_progress_increase", 11),
             (party_get_slot, ":looter_party", ":village_no", slot_village_raided_by),
             (try_begin),
               (party_get_skill_level, ":looting_skill", ":looter_party", "skl_looting"),
               (val_add, ":raid_progress_increase", ":looting_skill"),
             (try_end),
             (try_begin),
               (party_slot_eq, ":village_no", slot_center_has_watch_tower, 1),
               (val_mul, ":raid_progress_increase", 2),
               (val_div, ":raid_progress_increase", 3),
             (try_end),
             # NE 600 series militia slows down raids
             (try_begin),
               (party_get_slot, ":militia_completed", "$current_town", slot_militia_quest_completed),
               (gt, ":militia_completed", 0),
               (val_div, ":raid_progress_increase", 2),
             (try_end),
             # NE 600 series end militia slows down raids
			 # NE building 
	     (try_begin),
               (party_slot_eq, ":village_no", slot_center_has_palisade, 1),
               (val_mul, ":raid_progress_increase", 75),
               (val_div, ":raid_progress_increase", 100),
             (try_end),
			 # Ne end building 
             (val_add, ":village_raid_progress", ":raid_progress_increase"),
             (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", ":burnt_village_icon"),
               (party_set_slot, ":village_no", slot_village_smoke_added, 1),
             (try_end),
             (try_begin),
               (gt, ":village_raid_progress", 100),
               (str_store_party_name_link, s1, ":village_no"),
               (party_stack_get_troop_id, ":raid_leader", ":looter_party", 0),
               (ge, ":raid_leader", 0),
               (str_store_party_name, s2, ":looter_party"),
               (display_log_message, "@The village of {s1} has been looted by {s2}."),

               (try_begin),
                 (party_get_slot, ":village_lord", ":village_no", slot_town_lord),
                 (is_between, ":village_lord", active_npcs_begin, active_npcs_end),
                 (call_script, "script_troop_change_relation_with_troop", ":raid_leader", ":village_lord", -1),
                 (val_add, "$total_battle_enemy_changes", -1),
               (try_end),

               #give loot gold to raid leader
               (troop_get_slot, ":raid_leader_gold", ":raid_leader", slot_troop_wealth),
               (party_get_slot, ":village_prosperity", ":village_no"),
               (store_mul, ":value_of_loot", ":village_prosperity", 60), #average is 3000
               (val_add, ":raid_leader_gold", ":value_of_loot"),
               (troop_set_slot, ":raid_leader", slot_troop_wealth, ":raid_leader_gold"),			   			   
               
               #take loot gold from village lord #new 1.126
               (try_begin),
                 (is_between, ":village_lord", active_npcs_begin, active_npcs_end),
                 (troop_get_slot, ":village_lord_gold", ":village_lord", slot_troop_wealth),
                 (val_sub, ":village_lord_gold", ":value_of_loot"),
                 (val_max, ":village_lord_gold", 0),
                 (troop_set_slot, ":village_lord", slot_troop_wealth, ":village_lord_gold"),
               (try_end),
			   
               (call_script, "script_village_set_state",  ":village_no", svs_looted),
               (party_set_slot, ":village_no", slot_center_accumulated_rents, 0), #new 1.126
               (party_set_slot, ":village_no", slot_center_accumulated_tariffs, 0), #new 1.126

               (party_set_slot, ":village_no", slot_village_raid_progress, 0),
               (party_set_slot, ":village_no", slot_village_recover_progress, 0),
               (try_begin),
                 (store_faction_of_party, ":village_faction", ":village_no"),
                 (this_or_next|party_slot_eq, ":village_no", slot_town_lord, "trp_player"),
                 (eq, ":village_faction", "fac_player_supporters_faction"),
                 (call_script, "script_add_notification_menu", "mnu_notification_village_raided", ":village_no", ":raid_leader"),
               (try_end),
               (call_script, "script_add_log_entry", logent_village_raided, ":raid_leader",  ":village_no", -1, -1),
               (store_faction_of_party, ":looter_faction", ":looter_party"),
               (call_script, "script_faction_inflict_war_damage_on_faction", ":looter_faction", ":village_faction", 5),			   
             (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", ":deserted_village_icon"),
           (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", ":normal_village_icon"),
           (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),
         #Reducing siege hardness every day by 20
         (party_get_slot, ":siege_hardness", ":center_no", slot_center_siege_hardness),
         (val_sub, ":siege_hardness", 20),
         (val_max, ":siege_hardness", 0),
         (party_set_slot, ":center_no", slot_center_siege_hardness, ":siege_hardness"),
       
         (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
       
           #Reduce prosperity of besieged castle/town by -0.33/-4 every day.
            (try_begin),
             (try_begin),
               (is_between, ":center_no", castles_begin, castles_end),
               (store_random_in_range, ":random_value", 0, 3),
               (try_begin),
                 (eq, ":random_value", 0),
                 (assign, ":daily_siege_effect_on_prosperity", -1),
               (else_try),
                 (assign, ":daily_siege_effect_on_prosperity", 0),
               (try_end),
             (else_try),
               (assign, ":daily_siege_effect_on_prosperity", -4),
             (try_end),
       
             (call_script, "script_change_center_prosperity", ":center_no", ":daily_siege_effect_on_prosperity"),
             (val_add, "$newglob_total_prosperity_from_townloot", ":daily_siege_effect_on_prosperity"),
            (try_end),
    
           (store_faction_of_party, ":center_faction", ":center_no"),
        # Lift siege unless there is an enemy party nearby
           (assign, ":siege_lifted", 0),
           (try_begin),
             (try_begin),
               (neg|party_is_active, ":besieger_party"),
               (assign, ":siege_lifted", 1),
             (else_try),
               (store_distance_to_party_from_party, ":besieger_distance", ":center_no", ":besieger_party"),
               (gt, ":besieger_distance", 5),
               (assign, ":siege_lifted", 1),
			 (else_try),  
			   (store_faction_of_party, ":besieger_faction", ":besieger_party"),
               (store_relation, ":reln", ":besieger_faction", ":center_faction"),
               (ge, ":reln", 0),
               (assign, ":siege_lifted", 1),
             (try_end),
			 
			 
             (eq, ":siege_lifted", 1),
			 #If another lord can take over the siege, it isn't lifted
             (try_for_range, ":enemy_hero", active_npcs_begin, active_npcs_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),
               (party_is_active, ":enemy_party"),
               (store_faction_of_party, ":party_faction", ":enemy_party"),
               (store_relation, ":reln", ":party_faction", ":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),
             (call_script, "script_lift_siege", ":center_no", 1),
           (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_lift_siege
  # Input: arg1 = center_no, arg2 = display_message
  # Output: none
  #called from triggers
  ("lift_siege",
    [
      (store_script_param, ":center_no", 1),
      (store_script_param, ":display_message", 2),
      (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),
      (try_begin),
        (eq, ":display_message", 1),
        (str_store_party_name_link, s3, ":center_no"),
        (display_message, "@{s3} is no longer under siege."),
      (try_end),
      ]),


  # script_process_alarms
  # Input: none
  # Output: none
  #called from triggers
  ("process_alarms",
    [	
      (assign, ":current_modula", "$g_alarm_modula"),
      (val_add, "$g_alarm_modula", 1),
      (try_begin),
        (eq, "$g_alarm_modula", 3),
        (assign, "$g_alarm_modula", 0),
      (try_end),
      
      (try_for_range, ":center_no", centers_begin, centers_end),
        (store_mod, ":center_modula", ":center_no", 3),
        (eq, ":center_modula", ":current_modula"),
        
        (party_set_slot, ":center_no", slot_center_last_spotted_enemy, -1),
        (party_set_slot, ":center_no", slot_center_sortie_strength, 0),
        (party_set_slot, ":center_no", slot_center_sortie_enemy_strength, 0),
        
        (assign, ":spotting_range", 3),
        (try_begin),
          (is_currently_night),
          (assign, ":spotting_range", 2),
        (try_end),
        
        (try_begin),
          (party_slot_eq, ":center_no", slot_center_has_watch_tower, 1),
          (val_mul, ":spotting_range", 2),
        (else_try),
          (neg|is_between, ":center_no", villages_begin, villages_end),
          (val_add, ":spotting_range", 1),
          (val_mul, ":spotting_range", 2),
        (try_end),

        (store_faction_of_party, ":center_faction", ":center_no"),
		
        (try_for_parties, ":party_no"),
          (this_or_next|party_slot_eq, ":party_no", slot_party_type, spt_kingdom_hero_party),
          (eq, ":party_no", "p_main_party"),
          
          (store_faction_of_party, ":party_faction", ":party_no"),
          
          (try_begin),
            (eq, ":party_no", "p_main_party"),
            (assign, ":party_faction", "$players_kingdom"),
          (try_end),
          
          (try_begin),          
            (eq, ":party_faction", ":center_faction"),
            
            (store_distance_to_party_from_party, ":distance", ":party_no", ":center_no"),
            (le, ":distance", ":spotting_range"),
            
            (party_get_slot, ":cached_strength", ":party_no", slot_party_cached_strength),
            (party_get_slot, ":sortie_strength", ":center_no", slot_center_sortie_strength),
            (val_add, ":sortie_strength", ":cached_strength"),
            (party_set_slot, ":center_no", slot_center_sortie_strength, ":sortie_strength"),		 
          (else_try),
            (neq, ":party_faction", ":center_faction"),
		  
            (store_distance_to_party_from_party, ":distance", ":party_no", ":center_no"),

			(try_begin),
				(lt, ":distance", 10),
				(store_current_hours, ":hours"),
				(store_sub, ":faction_recce_slot", ":party_faction", kingdoms_begin),
				(val_add, ":faction_recce_slot", slot_center_last_reconnoitered_by_faction_time),
				(party_set_slot, ":center_no", ":faction_recce_slot", ":hours"),
				
				#(eq, "$cheat_mode", 1),
				#(str_store_faction_name, s4, ":party_faction"),
				#(str_store_party_name, s5, ":center_no"),
				#(display_message, "@{!}DEBUG -- {s4} reconnoiters {s5}"),
			(try_end),

		    (store_relation, ":reln", ":center_faction", ":party_faction"),
            (lt, ":reln", 0),
			(try_begin),
	            (le, ":distance", ":spotting_range"),
	            
	            (party_get_slot, ":cached_strength", ":party_no", slot_party_cached_strength),
	            (party_get_slot, ":enemy_strength", ":center_no", slot_center_sortie_enemy_strength),
	            (val_add, ":enemy_strength", ":cached_strength"),
	            (party_set_slot, ":center_no", slot_center_sortie_enemy_strength, ":enemy_strength"),
	            (party_set_slot, ":center_no", slot_center_last_spotted_enemy, ":party_no"),
			(try_end),
			
          (try_end),		  		  		  		  		  
        (try_end),
      (try_end),
      
      (try_for_range, ":center_no", centers_begin, centers_end),
        (store_mod, ":center_modula", ":center_no", 3),
        (eq, ":center_modula", ":current_modula"),
        
        (try_begin), #eligible units sortie out of castle
          (is_between, ":center_no", walled_centers_begin, walled_centers_end),
          (party_slot_ge, ":center_no", slot_center_last_spotted_enemy, 0),
          
          (party_get_slot, ":sortie_strength", ":center_no", slot_center_sortie_strength),
          (party_get_slot, ":enemy_strength", ":center_no", slot_center_sortie_enemy_strength),
          
          #Below two lines are new added by ozan. While AI want to drive nearby besieging enemy parties by making sortie them, they give up current battle if they are already joining one.
          #Lets assume there is a battle inside the castle, because enemies are inside castle and they are so close to castle they will be also added to slot_center_sortie_enemy_strength
          #But in this scenario, they are not outside the castle, so searching/patrolling enemy outside the castle is useless at this point. 
          #So if there is already a battle inside the center, do not sortie and search enemy outside.
          (party_get_battle_opponent, ":center_battle_opponent", ":center_no"),
          (try_begin),
		    (ge, "$cheat_mode", 1),
            (ge, ":center_battle_opponent", 0),
            (str_store_party_name, s7, ":center_no"),
            (str_store_party_name, s6, ":center_battle_opponent"),
            (display_message, "@{!}DEBUG : There are already enemies ({s6}) inside {s7}."),
          (try_end),
          (lt, ":center_battle_opponent", 0), 
          #New added by ozan ended.
                                        
          (try_begin),
            (eq, "$cheat_mode", 1),
            (str_store_party_name, s4, ":center_no"),
            (assign, reg3, ":sortie_strength"),
            (assign, reg4, ":enemy_strength"),
            (display_message, "@{!}DEBUG -- Calculating_sortie for {s4} strength of {reg3} vs {reg4} enemies"),
          (try_end),
          
          (store_mul, ":enemy_strength_mul_14_div_10", ":enemy_strength", 14),
          (val_div, ":enemy_strength_mul_14_div_10", 10),
          (gt, ":sortie_strength", ":enemy_strength_mul_14_div_10"),
          
          (assign, ":at_least_one_party_sorties", 0),
          (try_for_parties, ":sortie_party"),
            (party_get_attached_to, ":town", ":sortie_party"),
            (eq, ":town", ":center_no"),
            
            (party_slot_eq, ":sortie_party", slot_party_type, spt_kingdom_hero_party),
            
            (party_get_slot, ":cached_strength", ":sortie_party", slot_party_cached_strength),
            (ge, ":cached_strength", 100),
            
            (party_detach, ":sortie_party"),
            (call_script, "script_party_set_ai_state", ":sortie_party",  spai_patrolling_around_center, ":center_no"),
            
            (try_begin),          
              (eq, "$cheat_mode", 1),
              (str_store_party_name, s4, ":sortie_party"),
              (display_message, "str_s4_sorties"),
            (try_end),
            
            (eq, ":at_least_one_party_sorties", 0),
            (assign, ":at_least_one_party_sorties", ":sortie_party"),
          (try_end),
          
          (try_begin),
            (party_is_in_town, "p_main_party", ":center_no"),
			(eq, "$g_player_is_captive", 0),
            (gt, ":at_least_one_party_sorties", 0),
            (call_script, "script_add_notification_menu", "mnu_notification_sortie_possible", ":center_no", ":sortie_party"),	
          (try_end),
		(try_end),
		
		(store_faction_of_party, ":center_faction", ":center_no"),
		
		#Send message
		(this_or_next|eq, "$cheat_mode", 1), #this is message
		(this_or_next|party_slot_eq, ":center_no", slot_town_lord, "trp_player"),
		(eq, ":center_faction", "$players_kingdom"),
		
		(party_get_slot, ":enemy_party", ":center_no", slot_center_last_spotted_enemy),
		(ge, ":enemy_party", 0),
		(store_distance_to_party_from_party, ":dist", "p_main_party", ":center_no"),
		(assign, ":has_messenger", 0),
		(try_begin),
		  (this_or_next|party_slot_eq, ":center_no", slot_town_lord, "trp_player"),
		  (eq, ":center_faction", "fac_player_supporters_faction"),
		  (party_slot_eq, ":center_no", slot_center_has_messenger_post, 1),
		  (assign, ":has_messenger", 1),
		(try_end),
		
		(this_or_next|eq, "$cheat_mode", 1),
		(this_or_next|lt, ":dist", 30),
			(eq, ":has_messenger", 1),
		
		(str_store_party_name_link, s1, ":center_no"),
        (party_get_slot, ":exact_enemy_strength", ":center_no", slot_center_sortie_enemy_strength),
		
		(try_begin),
			(lt, ":exact_enemy_strength", 500),
			(display_message, "@Small bands of enemies spotted near {s1}."),
		(else_try),
			(lt, ":exact_enemy_strength", 1000),
			(display_message, "@Enemy patrols spotted near {s1}."),
		(else_try),
			(lt, ":exact_enemy_strength", 2000),
			(display_message, "@Medium-sized group of enemies spotted near {s1}."),
		(else_try),
			(lt, ":exact_enemy_strength", 4000),
			(display_message, "@Significant group of enemies spotted near {s1}."),
		(else_try),
			(lt, ":exact_enemy_strength", 8000),
			(display_message, "@Army of enemies spotted near {s1}."),
		(else_try),
			(lt, ":exact_enemy_strength", 16000),
			(display_message, "@Large army of enemies spotted near {s1}."),
		(else_try),
			(display_message, "@Great host of enemies spotted near {s1}."),
		(try_end),
		#maybe do audio sound?
		
      (try_end),
     ]),

  # script_allow_vassals_to_join_indoor_battle
  # Input: none
  # Output: none 
  ("allow_vassals_to_join_indoor_battle",
    [
     #if our commander attacks an enemy army
     (try_for_range, ":troop_no", active_npcs_begin, active_npcs_end),
       (troop_slot_eq, ":troop_no", slot_troop_occupation, slto_kingdom_hero),
       (neg|troop_slot_ge, ":troop_no", slot_troop_prisoner_of_party, 0),
       (troop_get_slot, ":party_no", ":troop_no", slot_troop_leaded_party),
       (gt, ":party_no", 0),
       (party_is_active, ":party_no"),
                
       (party_get_attached_to, ":party_is_attached_to", ":party_no"),
       (lt, ":party_is_attached_to", 0),

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

       (try_begin),
         #(faction_slot_eq, ":faction_no", slot_faction_ai_state, sfai_attacking_enemies_around_center),
         (party_slot_eq, ":party_no", slot_party_ai_state, spai_accompanying_army),
         (party_get_slot, ":commander_party", ":party_no", slot_party_ai_object),
         (gt, ":commander_party", 0),
         (party_is_active, ":commander_party"),
               
         (assign, ":besieged_center", -1),          
         (try_begin),
           (party_slot_eq, ":commander_party", slot_party_ai_state, spai_holding_center), #if commander is holding a center
           (party_get_slot, ":commander_object", ":commander_party", slot_party_ai_object), #get commander's ai object (center they are holding)
           (party_get_battle_opponent, ":besieger_enemy", ":commander_object"), #get this object's battle opponent
           (party_is_active, ":besieger_enemy"),
           (assign, ":besieged_center", ":commander_object"),
           (assign, ":commander_object", ":besieger_enemy"),
         (else_try),
           (party_slot_eq, ":commander_party", slot_party_ai_state, spai_engaging_army), #if commander is engaging an army          
           (party_get_slot, ":commander_object", ":commander_party", slot_party_ai_object), #get commander's ai object (army which they engaded)
           (ge, ":commander_object", 0), #if commander has an object
           (neg|is_between, ":commander_object", centers_begin, centers_end), #if this object is not a center, so it is a party
           (party_is_active, ":commander_object"),
           (party_get_battle_opponent, ":besieged_center", ":commander_object"), #get this object's battle opponent
         (else_try),
           (assign, ":besieged_center", -1),
         (try_end),
         
         (is_between, ":besieged_center", walled_centers_begin, walled_centers_end), #if battle opponent of our commander's ai object is a walled center

         (party_get_attached_to, ":attached_to_party", ":commander_party"), #if commander is attached to besieged center already.
         (eq, ":attached_to_party", ":besieged_center"),

         (store_faction_of_party, ":besieged_center_faction", ":besieged_center"),#get (battle opponent of our commander's ai object)'s faction
         (eq, ":besieged_center_faction", ":faction_no"), #if battle opponent of our commander's ai object is from same faction with current party
         (party_is_active, ":commander_object"),
         #make also follow_or_not check if needed

         (call_script, "script_party_set_ai_state", ":party_no", spai_engaging_army, ":commander_object"), #go and help commander

         (try_begin),
           (eq, "$cheat_mode", 1),
           (str_store_party_name, s7, ":party_no"),
           (str_store_party_name, s6, ":commander_object"),         
           (display_message, "@{!}DEBUG : {s7} is helping his commander by fighting with {s6}."),
         (try_end),
       (else_try),
         #(faction_slot_eq, ":faction_no", slot_faction_ai_state, sfai_attacking_center),

         (party_slot_eq, ":party_no", slot_party_ai_state, spai_accompanying_army),
         (party_get_slot, ":commander_party", ":party_no", slot_party_ai_object),
         (gt, ":commander_party", 0),
         (party_is_active, ":commander_party"),
                
         (party_get_battle_opponent, ":besieged_center", ":commander_party"), #get this object's battle opponent

         #make also follow_or_not check if needed
                  
         (is_between, ":besieged_center", walled_centers_begin, walled_centers_end), #if this object is a center
         (party_get_attached_to, ":attached_to_party", ":party_no"),
         (neq, ":attached_to_party", ":besieged_center"),
         (party_is_active, ":besieged_center"),

         (call_script, "script_party_set_ai_state", ":party_no", spai_engaging_army, ":besieged_center"), #go and help commander         
                  
         #(try_begin),
         #  (eq, "$cheat_mode", 1),
         #  (str_store_party_name, s7, ":party_no"),
         #  (str_store_party_name, s6, ":besieged_center"),         
         #  (display_message, "@{!}DEBUG : {s7} is helping his commander by attacking {s6}."),
         #(try_end),  

         #(party_set_ai_behavior, ":party_no", ai_bhvr_attack_party),
         #(party_set_ai_object, ":party_no", ":besieged_center"),
         #(party_set_flags, ":party_no", pf_default_behavior, 1), #is these needed?
         #(party_set_slot, ":party_no", slot_party_ai_substate, 1), #is these needed?
       (try_end),
     (try_end),       
     ]),
  
  # script_party_set_ai_state
  # Input: arg1 = party_no, arg2 = new_ai_state, arg3 = action_object (if necessary)
  # Output: none (Can fail)
  
  #Redone somewhat on Feb 18 to make sure that initative is set properly
  
  ("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),
          
      (assign, ":commander", -1),          
      (try_begin),
        (party_is_active, ":party_no"),
	    (party_stack_get_troop_id, ":commander", ":party_no", 0),	
	    (store_faction_of_party, ":faction_no", ":party_no"),
	  (try_end),  
	  
	  (try_begin),
	    (lt, ":commander", 0),
        #sometimes 0 sized parties enter "party_set_ai_state" script. So only discard them	    
	    #(try_begin),
        #  (eq, "$cheat_mode", 1),        
	    #  (str_store_troop_name, s6, ":party_no"),      
        #  (party_get_num_companions, reg6, ":party_no"),
        #  (display_message, "@{!}DEBUGS : party name is : {s6}, party size is : {reg6}, new ai discarded."),
        #(try_end),  
	  (else_try),
	    #Party does any business in town
	    (try_begin),
	      (is_between, ":party_is_in_town", walled_centers_begin, walled_centers_end),
	      (party_slot_eq, ":party_is_in_town", slot_center_is_besieged_by, -1),
	      (call_script, "script_troop_does_business_in_center", ":commander", ":party_is_in_town"),
	    (else_try),	      
	      (party_slot_eq, ":party_no", slot_party_ai_state, spai_visiting_village),
	      (party_get_slot, ":party_is_in_village", ":party_no", slot_party_ai_object),	     
	      (is_between, ":party_is_in_village", villages_begin, villages_end),
	      #(party_slot_eq, ":party_is_in_village", slot_center_is_looted_by, -1),
		  (neg|party_slot_eq, ":party_is_in_village", slot_village_state, svs_being_raided),
		  (neg|party_slot_eq, ":party_is_in_village", slot_village_state, svs_looted),
	      (store_distance_to_party_from_party, ":distance", ":party_no", ":party_is_in_village"),
	      (lt, ":distance", 3),
	      (call_script, "script_troop_does_business_in_center", ":commander", ":party_is_in_village"),
	    (try_end),
	    
	    (party_set_slot, ":party_no", slot_party_follow_me, 0),
	    
	    (try_begin),
	      (eq, ":old_ai_state", ":new_ai_state"),
	      (eq, ":old_ai_object", ":new_ai_object"),
          #do nothing. Nothing is changed.
        (else_try),
          (assign, ":initiative", 100),
          (assign, ":aggressiveness", 8),
          (assign, ":courage", 8),
          
          (try_begin),
            (this_or_next|eq, ":new_ai_state", spai_accompanying_army),
            (eq, ":new_ai_state", spai_screening_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),
            
            (try_begin),
              (eq, ":new_ai_state", spai_screening_army),
              (assign, ":aggressiveness", 9),
              (assign, ":courage", 9),
              (assign, ":initiative", 80),
            (else_try),
              (assign, ":aggressiveness", 6),
              (assign, ":courage", 9),
              (assign, ":initiative", 10),
            (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),
            (party_set_slot, ":party_no", slot_party_follow_me, 1),
            (party_set_slot, ":party_no", slot_party_ai_substate, 0),
            
            (try_begin),
              (gt, ":party_is_in_town", 0),
              (neq, ":party_is_in_town", ":new_ai_object"),
              (party_detach, ":party_no"),
            (try_end),
            
            (assign, ":aggressiveness", 1),
            (assign, ":courage", 9),
            (assign, ":initiative", 20),
            #(assign, ":initiative", 100),
          (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),
            
            (assign, ":aggressiveness", 7),
            (assign, ":courage", 9),
            (assign, ":initiative", 100),
            #(party_set_ai_initiative, ":party_no", 99),
          (else_try),
            (eq, ":new_ai_state", spai_patrolling_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_travel_to_point),
            (party_set_ai_target_position, ":party_no", pos2),
            (party_set_ai_object, ":party_no", ":new_ai_object"),
            
            (try_begin),
              (faction_slot_eq, ":faction_no", slot_faction_ai_state, sfai_attacking_enemies_around_center),
              (party_set_ai_patrol_radius, ":party_no", 1), #line 100
            (else_try),  
              (party_set_ai_patrol_radius, ":party_no", 5), #line 100
            (try_end),
            
            (party_set_flags, ":party_no", pf_default_behavior, 0),
            (party_set_slot, ":party_no", slot_party_follow_me, 1),
            (party_set_slot, ":party_no", slot_party_ai_substate, 0),
            
            (try_begin),
              (gt, ":party_is_in_town", 0),
              (party_detach, ":party_no"),
            (try_end),
            
            (try_begin),
              #new to avoid losing time of marshal with attacking unimportant targets while there is a threat in our centers.
              (ge, ":commander", 0),
              (faction_slot_eq, ":faction_no", slot_faction_marshall, ":commander"),
	          (faction_slot_eq, ":faction_no", slot_faction_ai_state, sfai_attacking_enemies_around_center),	        	  
	          
	          (party_get_position, pos3, ":party_no"),
	          (get_distance_between_positions, ":distance_to_center", pos1, pos3),
	          	          	      
	          (try_begin),    
	            (ge, ":distance_to_center", 800), #added new (1.122)
                (assign, ":initiative", 10), 
                (assign, ":aggressiveness", 1),
                (assign, ":courage", 8), 
              (else_try), #below added new (1.122)
                (assign, ":initiative", 100), 
                (assign, ":aggressiveness", 8),
                (assign, ":courage", 8),              
              (try_end),
            (else_try),              
              (assign, ":aggressiveness", 8),
              (assign, ":courage", 8),
              (assign, ":initiative", 100),
            (try_end),  
          (else_try),
            (eq, ":new_ai_state", spai_visiting_village),
            (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),
            (party_set_slot, ":party_no", slot_party_ai_substate, 0),
            (try_begin),
              (gt, ":party_is_in_town", 0),
              (neq, ":party_is_in_town", ":new_ai_object"),
              (party_detach, ":party_no"),
            (try_end),
            
            (assign, ":aggressiveness", 8),
            (assign, ":courage", 8),
            (assign, ":initiative", 100),
          (else_try), #0.660: this is where the 1625/1640 bugs happen with an improper ai_object
            (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),
	        (party_set_slot, ":party_no", slot_party_follow_me, 1),
	        (party_set_slot, ":party_no", slot_party_ai_substate, 0),
	        (try_begin),
	          (gt, ":party_is_in_town", 0),
	          (neq, ":party_is_in_town", ":new_ai_object"),
	          (party_detach, ":party_no"),
	        (try_end),
	        
	        (try_begin),
	          (ge, ":commander", 0),
	          (faction_slot_eq, ":faction_no", slot_faction_marshall, ":commander"),
	          (assign, ":aggressiveness", 1),
	          (assign, ":courage", 8),
	          (assign, ":initiative", 20),
	        (else_try),
	          (assign, ":aggressiveness", 7),
	          (assign, ":courage", 8),
	          (assign, ":initiative", 100),
	        (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),
	        
            (try_begin),
              #new to avoid losing time of marshal with attacking unimportant targets while there is a threat in our centers.
              (ge, ":commander", 0),
              (faction_slot_eq, ":faction_no", slot_faction_marshall, ":commander"),
	          (faction_slot_eq, ":faction_no", slot_faction_ai_state, sfai_attacking_enemies_around_center),	        	  
              (assign, ":initiative", 10), 
              (assign, ":aggressiveness", 1),
              (assign, ":courage", 8),
            (else_try),              
              (assign, ":aggressiveness", 8),
	          (assign, ":courage", 8),
	          (assign, ":initiative", 100),
	        (try_end),  
	      (else_try),
	        (eq, ":new_ai_state", spai_retreating_to_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, 1),
	        (party_set_slot, ":party_no", slot_party_commander_party, -1),
	        (try_begin),
	          (gt, ":party_is_in_town", 0),
	          (neq, ":party_is_in_town", ":new_ai_object"),
	          (party_detach, ":party_no"),
	        (try_end),
	        
	        (assign, ":aggressiveness", 3),
	        (assign, ":courage", 4),
	        (assign, ":initiative", 100),
	      (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_begin),
	        (troop_slot_eq, ":commander", slot_lord_reputation_type, lrep_martial),	
	        (val_add, ":aggressiveness", 2),
	        (val_add, ":courage", 2),
	      (else_try),
	        (troop_slot_eq, ":commander", slot_lord_reputation_type, lrep_debauched),
	        (val_sub, ":aggressiveness", 1),
	        (val_sub, ":courage", 1),
	      (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"),
	      (party_set_aggressiveness, ":party_no", ":aggressiveness"),
	      (party_set_courage, ":party_no", ":courage"),
	      (party_set_ai_initiative, ":party_no", ":initiative"),
	    (try_end),
	  (try_end),

	  #Helpfulness
	  (try_begin),
	    (ge, ":commander", 0),
	  
	    (party_set_helpfulness, ":party_no", 101),
	    (try_begin),
  	      (troop_slot_eq, ":commander", slot_lord_reputation_type, lrep_martial),
 	      (party_set_helpfulness, ":party_no", 200),
	    (else_try),
  	      (troop_slot_eq, ":commander", slot_lord_reputation_type, lrep_upstanding),
	      (party_set_helpfulness, ":party_no", 150),
	    (else_try),
	      (party_slot_eq, ":party_no", slot_party_ai_state, spai_accompanying_army),
	      (party_set_helpfulness, ":party_no", 110),
	    (else_try),
	      (troop_slot_eq, ":commander", slot_lord_reputation_type, lrep_quarrelsome),
	      (party_set_helpfulness, ":party_no", 90),	  
	    (else_try),
	      (troop_slot_eq, ":commander", slot_lord_reputation_type, lrep_selfrighteous),
	      (party_set_helpfulness, ":party_no", 80),	  
	    (else_try),
	      (troop_slot_eq, ":commander", slot_lord_reputation_type, lrep_debauched),
	      (party_set_helpfulness, ":party_no", 50),
	    (try_end),	  
	  (try_end),  
  ]),

  ("cf_party_under_player_suggestion",
    [
    (store_script_param, ":party_no", 1),
	
	(party_slot_eq, ":party_no", slot_party_following_orders_of_troop, "trp_kingdom_heroes_including_player_begin"),
	
	(party_get_slot, ":ai_state", ":party_no", slot_party_ai_state),
	(party_slot_eq, ":party_no", slot_party_orders_type, ":ai_state"),

	(party_get_slot, ":ai_object", ":party_no", slot_party_ai_object),
	(party_slot_eq, ":party_no", slot_party_orders_object, ":ai_object"),
	
	(store_current_hours, ":hours_since_orders_given"),
	(party_get_slot, ":orders_time", ":party_no", slot_party_orders_time),
	
	(val_sub, ":hours_since_orders_given", ":orders_time"),
	(lt, ":hours_since_orders_given", 12),  
	]),
	    
  #Currently called from process_ai_state, could be called from elsewhere
  #It is used for lord to (1)Court ladies (2)Collect rents (3)Look for volunteers
  ("troop_does_business_in_center", 
  [
    (store_script_param, ":troop_no", 1),
    (store_script_param, ":center_no", 2),
    
    (troop_get_slot, ":led_party", ":troop_no", slot_troop_leaded_party),
    
    (store_current_hours, ":current_time"),
    (try_begin),
#      (party_slot_eq, ":center_no", slot_town_lord, ":troop_no"), #this was added to get lords in centers out and visiting their fiefs, but I've adjusted the decision checklist
      (is_between, ":center_no", walled_centers_begin, walled_centers_end),
      (party_set_slot, ":led_party", slot_party_last_in_any_center, ":current_time"),
      (try_begin),
        (call_script, "script_lord_get_home_center", ":troop_no"),
        (eq, ":center_no", reg0),
        (party_set_slot, ":led_party", slot_party_last_in_home_center, ":current_time"),
      (try_end),
    (try_end),
    
    #Collect the rents
    (try_begin),
      (party_slot_eq, ":center_no", slot_town_lord, ":troop_no"),
      
      (party_get_slot, ":accumulated_rents", ":center_no", slot_center_accumulated_rents),
      (party_get_slot, ":accumulated_tariffs", ":center_no", slot_center_accumulated_tariffs),
      (troop_get_slot, ":troop_wealth", ":troop_no", slot_troop_wealth),
      (val_add, ":troop_wealth", ":accumulated_rents"),
      (val_add, ":troop_wealth", ":accumulated_tariffs"),
      
      (troop_set_slot, ":troop_no", slot_troop_wealth, ":troop_wealth"),
      (party_set_slot, ":center_no", slot_center_accumulated_rents, 0),
      (party_set_slot, ":center_no", slot_center_accumulated_tariffs, 0),
      
      (try_begin),
        (this_or_next|eq, "$cheat_mode", 1),
        (eq, "$cheat_mode", 3),
        (assign, reg1, ":troop_wealth"),
        (str_store_party_name, s4, ":center_no"),
        (add_troop_note_from_sreg, ":troop_no", 1, "str_current_wealth_reg1_taxes_last_collected_from_s4", 0),
      (try_end),
    (try_end),
	
	#Recruit volunteers
    (try_begin),
		(is_between, ":center_no", villages_begin, villages_end),
	
        (party_get_slot, ":troop_type", ":center_no", slot_center_npc_volunteer_troop_type),
        (party_get_slot, ":troop_amount", ":center_no", slot_center_npc_volunteer_troop_amount),
        (party_set_slot, ":center_no", slot_center_npc_volunteer_troop_amount, -1),
        (party_add_members, ":led_party", ":troop_type", ":troop_amount"),
    (try_end),
   
    #Courtship
    (try_begin),
		(party_get_slot, ":time_of_last_courtship", ":led_party", slot_party_leader_last_courted),
		(store_sub, ":hours_since_last_courtship", ":current_time", ":time_of_last_courtship"),
		(gt, ":hours_since_last_courtship", 72),

		(troop_slot_eq, ":troop_no", slot_troop_spouse, -1),
		(try_for_range, ":love_interest_slot", slot_troop_love_interest_1, slot_troop_love_interests_end),
			(troop_get_slot, ":love_interest", ":troop_no", ":love_interest_slot"),
			(gt, ":love_interest", 0),
			(troop_get_slot, ":love_interest_town", ":love_interest", slot_troop_cur_center),
			(eq, ":center_no", ":love_interest_town"),
			
			(call_script, "script_courtship_event_troop_court_lady", ":troop_no", ":love_interest"),
			(party_set_slot, ":led_party", slot_party_leader_last_courted, ":current_time"),
		(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", active_npcs_begin, active_npcs_end),
         (troop_slot_eq, ":troop_no", slot_troop_occupation, slto_kingdom_hero),
         (neg|troop_slot_ge, ":troop_no", slot_troop_prisoner_of_party, 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 script_decide_kingdom_party_ais
  #Handles sieges, raids, etc -- does not change the party's basic mission.
  # 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),
      (try_begin),
        (party_is_active, ":party_no"),
        (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),
            (party_slot_eq, ":ai_object", slot_center_is_besieged_by, -1),
            (store_distance_to_party_from_party, ":distance", ":party_no", ":ai_object"),
            (lt, ":distance", 3),
            (try_begin),
              (party_slot_eq, ":party_no", slot_party_ai_state, spai_accompanying_army),
              (party_get_slot, ":commander_party", ":party_no", slot_party_ai_object),
              (party_set_slot, ":ai_object", slot_center_is_besieged_by, ":commander_party"),
            (else_try),
              (party_set_slot, ":ai_object", slot_center_is_besieged_by, ":party_no"),
            (try_end),
            (store_current_hours, ":cur_hours"),
            (party_set_slot, ":ai_object", slot_center_siege_begin_hours, ":cur_hours"),

            (str_store_party_name_link, s1, ":ai_object"),
            (str_store_troop_name_link, s2, ":troop_no"),
            (str_store_faction_name_link, s3, ":faction_no"),
            (display_log_message, "@{s1} has been besieged by {s2} of {s3}."),
            (try_begin),
              (store_faction_of_party, ":ai_object_faction", ":ai_object"),
              (this_or_next|party_slot_eq, ":ai_object", slot_town_lord, "trp_player"),
              (eq, ":ai_object_faction", "fac_player_supporters_faction"),
              (call_script, "script_add_notification_menu", "mnu_notification_center_under_siege", ":ai_object", ":troop_no"),
            (try_end),
            (call_script, "script_village_set_state", ":ai_object", svs_under_siege),
            (assign, "$g_recalculate_ais", 1),
          (try_end),
        (else_try),
          (eq, ":ai_state", spai_raiding_around_center),
          (party_slot_eq, ":party_no", slot_party_ai_substate, 0),
          (assign, ":selected_village", 0),
          (try_for_range, ":enemy_village_no", villages_begin, villages_end),
            (eq, ":selected_village", 0),
            (store_faction_of_party, ":enemy_village_faction", ":enemy_village_no"),
            (try_begin),
              (party_slot_eq, ":enemy_village_no", slot_town_lord, "trp_player"),
              (store_relation, ":reln", "fac_player_supporters_faction", ":faction_no"),
            (else_try),
              (store_relation, ":reln", ":enemy_village_faction", ":faction_no"),
            (try_end),
            (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
            (assign, ":selected_village", ":enemy_village_no"),
          (try_end),
          (try_begin),
            (eq, ":selected_village", 0),
            (is_between, ":ai_object", villages_begin, villages_end),
            (assign, ":selected_village", ":ai_object"),
          (try_end),
          (try_begin),
            (gt, ":selected_village", 0),
            (call_script, "script_party_set_ai_state", ":party_no", spai_raiding_around_center, ":selected_village"),
            (try_begin),
              (faction_slot_eq, ":faction_no", slot_faction_marshall, ":troop_no"),
              (faction_slot_eq, ":faction_no", slot_faction_ai_state, sfai_raiding_village),
              (faction_set_slot, ":faction_no", slot_faction_ai_object, ":selected_village"),
            (try_end),
            (party_get_position, pos1, ":selected_village"),
            (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", ":selected_village"),
            (party_set_slot, ":party_no", slot_party_ai_substate, 1),
          (try_end),
        (else_try),
          (eq, ":ai_state", spai_raiding_around_center),#substate is 1
          (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"),
              (try_begin),
                (store_faction_of_party, ":village_faction", ":ai_object"),
                (this_or_next|party_slot_eq, ":ai_object", slot_town_lord, "trp_player"),
                (eq, ":village_faction", "fac_player_supporters_faction"),
                (store_distance_to_party_from_party, ":dist", "p_main_party", ":ai_object"),
                (this_or_next|lt, ":dist", 30),
                (party_slot_eq, ":ai_object", slot_center_has_messenger_post, 1),
                (call_script, "script_add_notification_menu", "mnu_notification_village_raid_started", ":ai_object", ":troop_no"),
              (try_end),
            (else_try),
              (party_slot_eq, ":ai_object", slot_village_state, svs_being_raided),
            (else_try),
              #if anything other than being_raided leave
              (party_set_slot, ":party_no", slot_party_ai_substate, 0),
            (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_patrolling_around_center),
                    
          (try_begin),
            (party_slot_eq, ":party_no", slot_party_ai_substate, 0),
            (store_distance_to_party_from_party, ":distance", ":party_no", ":ai_object"),
            (lt, ":distance", 6),
            (party_set_slot, ":party_no", slot_party_ai_substate, 1),
                    
	        (party_set_aggressiveness, ":party_no", 8),
	        (party_set_courage, ":party_no", 8),
	        (party_set_ai_initiative, ":party_no", 100),
	                    
            (party_set_ai_behavior, ":party_no", ai_bhvr_patrol_party),
            (party_set_ai_object, ":party_no", ":ai_object"),
          (try_end),
        (else_try),
          (eq, ":ai_state", spai_holding_center),
        (try_end),
      (try_end),	
  ]),
  
  # script_begin_assault_on_center
  # Input: arg1: faction_no
  # Output: none
  #called from triggers
  ("begin_assault_on_center",
   [
     (store_script_param, ":center_no", 1),
	
     (try_for_range, ":troop_no", active_npcs_begin, active_npcs_end),
       (troop_slot_eq, ":troop_no", slot_troop_occupation, slto_kingdom_hero),
       (neg|troop_slot_ge, ":troop_no", slot_troop_prisoner_of_party, 0),
       (troop_get_slot, ":party_no", ":troop_no", slot_troop_leaded_party),
       (gt, ":party_no", 0),
       (party_is_active, ":party_no"),

       (assign, ":continue", 0),
       (try_begin),
         (party_slot_eq, ":party_no", slot_party_ai_state, spai_besieging_center),
         (party_slot_eq, ":party_no", slot_party_ai_object, ":center_no"),
         (party_slot_eq, ":party_no", slot_party_ai_substate, 0),
         (assign, ":continue", 1),
       (else_try),
         (party_slot_eq, ":party_no", slot_party_ai_state, spai_accompanying_army),
         (party_get_slot, ":commander_party", ":party_no", slot_party_ai_object),
         (gt, ":commander_party", 0),
         (party_is_active, ":commander_party"),
         (party_slot_eq, ":commander_party", slot_party_ai_state, spai_besieging_center),
         (party_slot_eq, ":commander_party", slot_party_ai_object, ":center_no"),
         (call_script, "script_party_set_ai_state", ":party_no", spai_besieging_center, ":center_no"),
         (assign, ":continue", 1),
       (try_end),

       (eq, ":continue", 1),

       (party_set_ai_behavior, ":party_no", ai_bhvr_attack_party),
       (party_set_ai_object, ":party_no", ":center_no"),
       (party_set_flags, ":party_no", pf_default_behavior, 1),
       (party_set_slot, ":party_no", slot_party_ai_substate, 1),
     (try_end),
   ]),
  
  #DEPRECATED - Using new political issue system instead
  ("select_faction_marshall",
   [
#     (store_script_param_1, ":faction_no"),
 #    (faction_get_slot, ":faction_leader", ":faction_no", slot_faction_leader),
  #   (faction_get_slot, ":old_faction_marshall", ":faction_no", slot_faction_marshall),
     
   #  (assign, ":old_marshal_is_avaliable", 0),
    # (try_begin),
     #  (gt, ":old_faction_marshall", 0),
      # (troop_get_slot, ":old_marshal_party", ":old_faction_marshall", slot_troop_leaded_party),
     #  (party_is_active, ":old_marshal_party"),
    #   (assign, ":old_marshal_is_avaliable", 1),
   #  (try_end),
     
     #Ozan : I am adding some codes here because sometimes armies demobilize during last seconds of an 
	 #important event like taking a castle, ext because of marshal change. When marshal changes during 
	 #an important event occurs new marshal's followers become 0 and continueing siege attack seems less 
	 #valuable then armies demobilize, faction ai become "do nothing", "I cannot think anything to do" ext.
		
   #  (assign, ":there_is_an_important_situation", 0),
   #  (faction_get_slot, ":current_ai_object", ":faction_no", slot_faction_ai_object),            
     
   #  (try_begin), #do not demobilize during taking a castle/town (fighting in the castle)
   #    (is_between, ":current_ai_object", walled_centers_begin, walled_centers_end),
   #    (party_get_battle_opponent, ":besieger_party", ":current_ai_object"),
   #    (ge, ":besieger_party", 0),
   #    (party_is_active, ":besieger_party"),
   #    (store_faction_of_party, ":besieger_faction", ":besieger_party"),
   #    (this_or_next|eq, ":besieger_faction", ":faction_no"),
   #    (eq, ":besieger_faction", "fac_player_faction"),
   #    (assign, ":there_is_an_important_situation", 1),
   #  (try_end),

   #  (try_begin), #do not demobilize during raiding a village (holding around village)
   #    (is_between, ":current_ai_object", centers_begin, centers_end),
   #    (neg|is_between, ":current_ai_object", walled_centers_begin, walled_centers_end),		  
   #    (party_slot_eq, ":current_ai_object", slot_village_state, svs_being_raided),
   #    (assign, ":there_is_an_important_situation", 1),
   #  (try_end),

   #  (try_begin), #do not demobilize during besigning a siege (holding around castle)
   #    (is_between, ":current_ai_object", walled_centers_begin, walled_centers_end),
   #    #(str_store_party_name, s7, ":current_ai_object"),
   #    (party_get_slot, ":besieger_party", ":current_ai_object", slot_center_is_besieged_by),
   #    (ge, ":besieger_party", 0),
   #    (party_is_active, ":besieger_party"),
   #    #(str_store_party_name, s7, ":besieger_party"),
   #    (store_faction_of_party, ":besieger_faction", ":besieger_party"),
   #    (this_or_next|eq, ":besieger_faction", ":faction_no"),
   #    (eq, ":besieger_faction", "fac_player_faction"),		  
   #    (assign, ":there_is_an_important_situation", 1),
   #  (try_end),
     
   #  (try_begin),   
   #    (this_or_next|eq, ":there_is_an_important_situation", 0),
   #    (eq, ":old_marshal_is_avaliable", 0),
       #end addition ozan
   
   
    #   (assign, ":total_renown", 0),
    #   (try_for_range, ":loop_var", active_npcs_including_player_begin, active_npcs_end),
    #     (assign, ":cur_troop", ":loop_var"),
    #     (assign, ":continue", 0),
    #     (try_begin),
    #       (eq, ":loop_var", "trp_kingdom_heroes_including_player_begin"),
    #       (assign, ":cur_troop", "trp_player"),
    #       (try_begin),
    #         (eq, ":faction_no", "$players_kingdom"),
    #         (assign, ":continue", 1),
    #       (try_end),
    #     (else_try),
    #       (troop_slot_eq, ":cur_troop", slot_troop_occupation, slto_kingdom_hero),
    #       (store_troop_faction, ":cur_faction", ":cur_troop"),
    #       (eq, ":cur_faction", ":faction_no"),
    #       (troop_get_slot, ":cur_party", ":cur_troop", slot_troop_leaded_party),
    #       (gt, ":cur_party", 0),
    #       (party_is_active, ":cur_party"),
    #       (call_script, "script_party_count_fit_for_battle", ":cur_party"),
    #       (assign, ":party_fit_for_battle", reg0),
    #       (call_script, "script_party_get_ideal_size", ":cur_party"),
    #       (assign, ":ideal_size", reg0),
    #       (store_mul, ":relative_strength", ":party_fit_for_battle", 100),
    #       (val_div, ":relative_strength", ":ideal_size"),
    #       (ge, ":relative_strength", 25),
    #       (assign, ":continue", 1),
    #     (try_end),
         
     #    (eq, ":continue", 1),
	   
    #     (troop_get_slot, ":renown", ":cur_troop", slot_troop_renown),
	#     (call_script, "script_troop_get_relation_with_troop", ":cur_troop", ":faction_leader"),
	#     (store_mul, ":relation_modifier", reg0, 15),
	#     (val_add, ":renown", ":relation_modifier"),
	#     (val_max, ":renown", 1),
	#   
    #     (try_begin),
    #       (eq, ":cur_troop", "trp_player"),
    #       (neq, ":old_faction_marshall", "trp_player"),
    #       (assign, ":renown", 0),
   #      (try_end),
    #     (try_begin),
    #       (eq, ":cur_troop", ":faction_leader"),
    #       (val_mul, ":renown", 3),
    #       (val_div, ":renown", 4),
    #     (try_end),
    #     (try_begin),
    #       (eq, ":cur_troop", ":old_faction_marshall"),
    #       (val_mul, ":renown", 1000),
    #     (try_end),
    #     (val_add, ":total_renown", ":renown"),
    #   (try_end),
    #   (assign, ":result", -1),
    #   (try_begin),
    #     (gt, ":total_renown", 0),
    #     (store_random_in_range, ":random_renown", 0, ":total_renown"),
    #     (try_for_range, ":loop_var", active_npcs_including_player_begin, active_npcs_end),
    #       (eq, ":result", -1),
    #       (assign, ":cur_troop", ":loop_var"),
    #       (assign, ":continue", 0),
    #       (try_begin),
    #         (eq, ":loop_var", "trp_kingdom_heroes_including_player_begin"),
    #         (assign, ":cur_troop", "trp_player"),
   #          (try_begin),
   #            (eq, ":faction_no", "$players_kingdom"),
   #            (assign, ":continue", 1),
   #          (try_end),
   #        (else_try),
   #          (troop_slot_eq, ":cur_troop", slot_troop_occupation, slto_kingdom_hero),
   #          (store_troop_faction, ":cur_faction", ":cur_troop"),
   #          (eq, ":cur_faction", ":faction_no"),
   #          (troop_get_slot, ":cur_party", ":cur_troop", slot_troop_leaded_party),
   #          (gt, ":cur_party", 0),
   #          (party_is_active, ":cur_party"),
   #          (call_script, "script_party_count_fit_for_battle", ":cur_party"),
   #          (assign, ":party_fit_for_battle", reg0),
      #       (call_script, "script_party_get_ideal_size", ":cur_party"),
      #       (assign, ":ideal_size", reg0),
      #       (store_mul, ":relative_strength", ":party_fit_for_battle", 100),
      #       (val_div, ":relative_strength", ":ideal_size"),
      #       (ge, ":relative_strength", 25),
      #       (assign, ":continue", 1),
      #     (try_end),
      #     (eq, ":continue", 1),

		#   (troop_get_slot, ":renown", ":cur_troop", slot_troop_renown),
	    #   (call_script, "script_troop_get_relation_with_troop", ":cur_troop", ":faction_leader"),
	    #   (store_mul, ":relation_modifier", reg0, 15),
	    #   (val_add, ":renown", ":relation_modifier"),
	    #   (val_max, ":renown", 1),
		# 
        #   (try_begin),
        #     (eq, ":cur_troop", "trp_player"),
        #     (neq, ":old_faction_marshall", "trp_player"),
        #     (assign, ":renown", 0),
        #   (try_end),
        #   (try_begin),
        #     (eq, ":cur_troop", ":faction_leader"),
        #     (val_mul, ":renown", 3),
         #    (val_div, ":renown", 4),
         #  (try_end),
         #  (try_begin),
       #      (eq, ":cur_troop", ":old_faction_marshall"),
       #      (val_mul, ":renown", 1000),
       #    (try_end),
       #    (val_sub, ":random_renown", ":renown"),
       #    (lt, ":random_renown", 0),
       #    (assign, ":result", ":cur_troop"),
       #  (try_end),
      # (try_end),
      # (try_begin),
         #(eq, "$cheat_mode", 1),
        # (ge, ":result", 0),
       #  (str_store_troop_name, s1, ":result"),
      #   (str_store_faction_name, s2, ":faction_no"),
     #    (display_message, "@{!}{s1} is chosen as the marshall of {s2}."),
    #   (try_end),
   #  (else_try),
   #    (faction_get_slot, ":old_faction_marshall", ":faction_no", slot_faction_marshall),
   #    (assign, ":result", ":old_faction_marshall"),
   #  (try_end),
     
   #  (assign, reg0, ":result"),
     ]),
	 
	 
	 

  # script_get_center_faction_relation_including_player
  # Input: arg1: center_no, arg2: target_faction_no
  # Output: reg0: relation
  #called from triggers
  ("get_center_faction_relation_including_player",
   [
     (store_script_param, ":center_no", 1),
     (store_script_param, ":target_faction_no", 2),
     (store_faction_of_party, ":center_faction", ":center_no"),
     (store_relation, ":relation", ":center_faction", ":target_faction_no"),
     (try_begin),
       (party_slot_eq, ":center_no", slot_town_lord, "trp_player"),
       (store_relation, ":relation", "fac_player_supporters_faction", ":target_faction_no"),
     (try_end),
     (assign, reg0, ":relation"),
     ]),
   
   #script_update_report_to_army_quest_note
   ("update_report_to_army_quest_note",  
   [
     (store_script_param, ":faction_no", 1),
     (store_script_param, ":new_strategy", 2),
     (store_script_param, ":old_faction_ai_state", 3),

     (try_begin),       
     (le, "$number_of_report_to_army_quest_notes", 13),

     (faction_get_slot, ":faction_marshal", ":faction_no", slot_faction_marshall),

     (try_begin), #updating quest notes for only report to army quest
       (eq, ":faction_no", "$players_kingdom"),      
       (neq, ":new_strategy", ":old_faction_ai_state"),
       (check_quest_active, "qst_report_to_army"),
       (ge, ":faction_marshal", 0),
              
       (str_store_troop_name_link, s11, ":faction_marshal"),
       (store_current_hours, ":hours"),
       (call_script, "script_game_get_date_text", 0, ":hours"),
       
       (try_begin),       
         (this_or_next|eq, ":new_strategy", sfai_attacking_enemies_around_center),
         (this_or_next|eq, ":new_strategy", sfai_attacking_center),
         (eq, ":new_strategy", sfai_gathering_army),         
         (faction_get_slot, ":faction_object", ":faction_no", slot_faction_ai_object),       
         (ge, ":faction_object", 0), 
         (str_store_party_name_link, s21, ":faction_object"),
       (try_end),  
                                                        
       (try_begin),
         (eq, ":new_strategy", sfai_gathering_army),
         
         (try_begin),                    
           (ge, "$g_gathering_reason", 0),
           (str_store_party_name_link, s21, "$g_gathering_reason"),
           (str_store_string, s14, "str_we_should_prepare_to_defend_s21_but_we_should_gather_our_forces_until_we_are_strong_enough_to_engage_them"),
         (else_try),
           (str_store_string, s14, "str_it_is_time_to_go_on_the_offensive_and_we_must_first_assemble_the_army"),
         (try_end),
         
         (str_store_string, s14, "@({s1}) {s11}: {s14}"),         
         (add_quest_note_from_sreg, "qst_report_to_army", "$number_of_report_to_army_quest_notes", s14, 0),
         (val_add, "$number_of_report_to_army_quest_notes", 1),
       (else_try),
         (eq, ":new_strategy", sfai_attacking_enemies_around_center),                
        
         (try_begin),
           (is_between, ":faction_object", walled_centers_begin, walled_centers_end),
           (str_store_string, s14, "str_we_should_ride_to_break_the_siege_of_s21"),
           (str_store_string, s14, "@({s1}) {s11}: {s14}"),
           (add_quest_note_from_sreg, "qst_report_to_army", "$number_of_report_to_army_quest_notes", s14, 0),
           (val_add, "$number_of_report_to_army_quest_notes", 1),
         (else_try),  
           (is_between, ":faction_object", villages_begin, villages_end),
           (str_store_string, s14, "str_we_should_ride_to_defeat_the_enemy_gathered_near_s21"),
           (str_store_string, s14, "@({s1}) {s11}: {s14}"),
           (add_quest_note_from_sreg, "qst_report_to_army", "$number_of_report_to_army_quest_notes", s14, 0),
           (val_add, "$number_of_report_to_army_quest_notes", 1),
         (try_end),  
       (else_try),
         (this_or_next|eq, ":new_strategy", sfai_attacking_center),
         (eq, ":new_strategy", sfai_raiding_village),

         (try_begin),
           (is_between, ":faction_object", walled_centers_begin, walled_centers_end),
           (str_store_string, s14, "str_we_believe_the_fortress_will_be_worth_the_effort_to_take_it"),
           (str_store_string, s14, "@{s14} ({s21})"),
           (str_store_string, s14, "@({s1}) {s11}: {s14}"),
           (add_quest_note_from_sreg, "qst_report_to_army", "$number_of_report_to_army_quest_notes", s14, 0),
           (val_add, "$number_of_report_to_army_quest_notes", 1),
         (else_try),  
           (is_between, ":faction_object", villages_begin, villages_end),
           (str_store_string, s14, "str_we_shall_leave_a_fiery_trail_through_the_heart_of_the_enemys_lands_targeting_the_wealthy_settlements_if_we_can"),
           (str_store_string, s14, "@{s14} ({s21})"),
           (str_store_string, s14, "@({s1}) {s11}: {s14}"),
           (add_quest_note_from_sreg, "qst_report_to_army", "$number_of_report_to_army_quest_notes", s14, 0),
           (val_add, "$number_of_report_to_army_quest_notes", 1),
         (try_end),
       (try_end),         
     (try_end),
     (try_end),
   ]),
     
  
  # script_decide_faction_ai
  # Input: arg1: faction_no
  # Output: none
  #called from triggers
  ("decide_faction_ai",
  #This handles political issues and faction issues
   [
    (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_marshal", ":faction_no", slot_faction_marshall),

	 
	#Remove marshal if he has become too controversial,, or he has defected, or has been taken prisoner
	(try_begin),
        (faction_slot_eq, ":faction_no", slot_faction_state, sfs_active),
		(neq, ":faction_no", "fac_player_supporters_faction"),
		(ge, ":faction_marshal", "trp_player"),
		
		(store_faction_of_troop, ":marshal_faction", ":faction_marshal"),
		(try_begin),
			(eq, ":faction_marshal", "trp_player"),
			(assign, ":marshal_faction", "$players_kingdom"),
		(try_end),
		
		
		(assign, ":player_marshal_is_prisoner", 0),
		(try_begin),
			(eq, ":faction_marshal", "trp_player"),
			(eq, "$g_player_is_captive", 1),
			(assign, ":player_marshal_is_prisoner", 1),
		(try_end),
		
		
		#High controversy level, or marshal has defected, or is prisoner
		(this_or_next|neq, ":marshal_faction", ":faction_no"),		
		(this_or_next|troop_slot_ge, ":faction_marshal", slot_troop_controversy, 80),
		(this_or_next|eq, ":player_marshal_is_prisoner", 1),
			(troop_slot_ge, ":faction_marshal", slot_troop_prisoner_of_party, 0),
		
		(assign, ":few_following_player_campaign", 0),
		(try_begin),
			(eq, ":faction_marshal", "trp_player"),
			(assign, ":vassals_following_player_campaign", 0),
			(gt, "$g_player_days_as_marshal", 1),
			(try_for_range, ":vassal", active_npcs_begin, active_npcs_end),
				(troop_slot_eq, ":vassal", slot_troop_occupation, slto_kingdom_hero),
				(store_faction_of_troop, ":vassal_faction", ":vassal"),
				(eq, ":vassal_faction", ":faction_no"),
				(call_script, "script_npc_decision_checklist_troop_follow_or_not", ":vassal"),
				(eq, reg0, 1),
				(val_add, ":vassals_following_player_campaign", 1),
			(try_end),
			(lt, ":vassals_following_player_campaign", 4),
			(assign, ":few_following_player_campaign", 1),
		(try_end),
		
		#Only remove marshal for controversy if offensive campaign in progress
		(this_or_next|eq, ":old_faction_ai_state", sfai_default),
		(this_or_next|eq, ":old_faction_ai_state", sfai_feast),		
		(this_or_next|neq, ":marshal_faction", ":faction_no"),
		(this_or_next|eq, ":few_following_player_campaign", 1),
		(this_or_next|eq, ":player_marshal_is_prisoner", 1),
			(troop_slot_ge, ":faction_marshal", slot_troop_prisoner_of_party, 0),
		
		#No current issue on the agenda
		(this_or_next|faction_slot_eq, ":faction_no", slot_faction_political_issue, 0),
		(this_or_next|eq, ":player_marshal_is_prisoner", 1),
			(troop_slot_ge, ":faction_marshal", slot_troop_prisoner_of_party, 0),
		
		(faction_set_slot, ":faction_no", slot_faction_political_issue, 1), #Appointment of marshal
		(store_current_hours, ":hours"),
		(val_max, ":hours", 0),
		(faction_set_slot, ":faction_no", slot_faction_political_issue_time, ":hours"), #Appointment of marshal
		
        (faction_get_slot, ":old_marshall", ":faction_no", slot_faction_marshall),
        (try_begin),
		  (ge, ":old_marshall", 0),
		  (troop_get_slot, ":old_marshall_party", ":old_marshall", slot_troop_leaded_party),
          (party_is_active, ":old_marshall_party"),
          (call_script, "script_set_icon_for_lord_party", ":old_marshall"),
          (party_set_marshall, ":old_marshall_party", 0),
        (try_end),  

		(try_begin),
			(eq, "$players_kingdom", ":faction_no"),
			(faction_slot_eq, "$players_kingdom", slot_faction_marshall, "trp_player"),
			(call_script, "script_add_notification_menu", "mnu_notification_relieved_as_marshal", 0, 0),
		(else_try),
			(neq, ":old_marshall", "trp_player"),
			(call_script, "script_change_troop_renown", ":old_marshall", 15),
		(try_end),
		(faction_set_slot, ":faction_no", slot_faction_marshall, -1),
		(assign, ":faction_marshal", -1),
		
		
		
		(try_for_range, ":active_npc", active_npcs_begin, active_npcs_end),
			(store_faction_of_troop, ":active_npc_faction", ":active_npc"),
			(eq, ":active_npc_faction", ":faction_no"),
			(troop_set_slot, ":active_npc", slot_troop_stance_on_faction_issue, -1),
		(try_end),		
		(try_begin),
			(eq, "$players_kingdom", ":faction_no"),
			(troop_set_slot, "trp_player", slot_troop_stance_on_faction_issue, -1),
		(try_end),
		
	(else_try),	 #If marshal not present, and not already on agenda, make political issue
		(eq, ":faction_marshal", -1),
		(neg|faction_slot_ge, ":faction_no", slot_faction_political_issue, 1), #This to avoid resetting votes every time
	
        (faction_slot_eq, ":faction_no", slot_faction_state, sfs_active),
		(neq, ":faction_no", "fac_player_supporters_faction"),
		
		(faction_set_slot, ":faction_no", slot_faction_political_issue, 1), #Appointment of marshal
		(store_current_hours, ":hours"),
		(val_max, ":hours", 0),
		(faction_set_slot, ":faction_no", slot_faction_political_issue_time, ":hours"), #Appointment of marshal
		
		(try_for_range, ":active_npc", active_npcs_begin, active_npcs_end),
			(store_faction_of_troop, ":active_npc_faction", ":active_npc"),
			(eq, ":active_npc_faction", ":faction_no"),
			(troop_set_slot, ":active_npc", slot_troop_stance_on_faction_issue, -1),
		(try_end),		
		(try_begin),
			(eq, "$players_kingdom", ":faction_no"),
			(troop_set_slot, "trp_player", slot_troop_stance_on_faction_issue, -1),
		(try_end),
		
		
	(else_try),	#If player is marshal, but not part of faction
		(eq, ":faction_marshal", "trp_player"),
		(neq, "$players_kingdom", ":faction_no"),

		(faction_set_slot, ":faction_no", slot_faction_political_issue, 1), #Appointment of marshal
		(store_current_hours, ":hours"),
		(val_max, ":hours", 0),
		(faction_set_slot, ":faction_no", slot_faction_political_issue_time, ":hours"), #Appointment of marshal

        (faction_get_slot, ":old_marshall", ":faction_no", slot_faction_marshall),
        (try_begin),
		  (ge, ":old_marshall", 0),
		  (troop_get_slot, ":old_marshall_party", ":old_marshall", slot_troop_leaded_party),
          (party_is_active, ":old_marshall_party"),
          (call_script, "script_set_icon_for_lord_party", ":old_marshall"),
          (party_set_marshall, ":old_marshall_party", 0),
        (try_end),  

		(faction_set_slot, ":faction_no", slot_faction_marshall, -1),
		(assign, ":faction_marshal", -1),
		
		(try_for_range, ":active_npc", active_npcs_begin, active_npcs_end),
			(store_faction_of_troop, ":active_npc_faction", ":active_npc"),
			(eq, ":active_npc_faction", ":faction_no"),
			(troop_set_slot, ":active_npc", slot_troop_stance_on_faction_issue, -1),
		(try_end),		
		(try_begin),
			(eq, "$players_kingdom", ":faction_no"),
			(troop_set_slot, "trp_player", slot_troop_stance_on_faction_issue, -1),
		(try_end),
		
	(try_end),
	 
	#If the faction issue is a center no longer under faction control, remove and reset 
	(try_begin), 
		(faction_get_slot, ":faction_political_issue", ":faction_no", slot_faction_political_issue),
		(is_between, ":faction_political_issue", centers_begin, centers_end),
		(store_faction_of_party, ":disputed_center_faction", ":faction_political_issue"),
		(neq, ":disputed_center_faction", ":faction_no"),
		
		(try_begin),
			(eq, "$cheat_mode", 1),
			(str_store_faction_name, s4, ":faction_no"),
			(str_store_party_name, s5, ":disputed_center_faction"),
			(display_message, "@{!}DEBUG -- {s4} drops {s5} as issue as it has changed hands"),
		(try_end),
		
		#Reset political issue
		(faction_set_slot, ":faction_no", slot_faction_political_issue, 0),
		(try_for_range, ":active_npc", active_npcs_begin, active_npcs_end),
			(store_faction_of_troop, ":active_npc_faction", ":active_npc"),
			(eq, ":active_npc_faction", ":faction_no"),
			(troop_set_slot, ":active_npc", slot_troop_stance_on_faction_issue, -1),
		(try_end),		
		(try_begin),
			(eq, "$players_kingdom", ":faction_no"),
			(troop_set_slot, "trp_player", slot_troop_stance_on_faction_issue, -1),
		(try_end),
		
	(try_end),
	
	
	#Resolve the political issue on the agenda
	(try_begin),
		(faction_slot_ge, ":faction_no", slot_faction_political_issue, 1),
		(neq, ":faction_no", "fac_player_supporters_faction"),
		
		#Do not switch marshals during a campaign
		(this_or_next|faction_slot_ge, ":faction_no", slot_faction_political_issue, centers_begin),
		(this_or_next|faction_slot_eq, ":faction_no", slot_faction_ai_state, sfai_default),
			(faction_slot_eq, ":faction_no", slot_faction_ai_state, sfai_feast),
		
		
		(faction_get_slot, ":faction_leader", ":faction_no", slot_faction_leader),
		
		(assign, ":total_lords", 0),
		(assign, ":lords_who_have_voted", 0),
		(assign, ":popular_favorite", -1),
	
		#Reset number of votes
		(troop_set_slot, "trp_player", slot_troop_temp_slot, 0),
		(try_for_range, ":active_npc", active_npcs_begin, active_npcs_end),
			(troop_set_slot, ":active_npc", slot_troop_temp_slot, 0),
		(try_end),

		#Tabulate votes
		(try_for_range, ":voting_lord", active_npcs_begin, active_npcs_end),
			(store_faction_of_troop, ":voting_lord_faction", ":voting_lord"),
			(eq, ":voting_lord_faction", ":faction_no"),
			(val_add, ":total_lords", 1),
			(troop_get_slot, ":lord_chosen_candidate", ":voting_lord", slot_troop_stance_on_faction_issue),								
			(gt, ":lord_chosen_candidate", -1),									
			(val_add, ":lords_who_have_voted", 1),			
			(troop_get_slot, ":total_votes", ":lord_chosen_candidate", slot_troop_temp_slot),
			(val_add, ":total_votes", 1),
			(troop_set_slot, ":lord_chosen_candidate", slot_troop_temp_slot, ":total_votes"),			
			(try_begin),
				(gt, ":popular_favorite", -1),
				(troop_get_slot, ":current_winner_votes", ":popular_favorite", slot_troop_temp_slot),
				(gt, ":total_votes", ":current_winner_votes"),
				(assign, ":popular_favorite", ":lord_chosen_candidate"),
			(else_try),	
				(eq, ":popular_favorite", -1),
				(assign, ":popular_favorite", ":lord_chosen_candidate"),
			(try_end),
		(try_end),	

		#Check to see if enough lords have voted
		(store_mul, ":number_required_for_quorum", ":total_lords", 4),
		(val_div, ":number_required_for_quorum", 5),
		
		
#		(gt, ":lords_who_have_voted", ":number_required_for_quorum"),

		(store_current_hours, ":hours_on_agenda"),
		(faction_get_slot, ":hours_when_put_on_agenda", ":faction_no", slot_faction_political_issue_time), #Appointment of marshal
		(val_sub, ":hours_on_agenda", ":hours_when_put_on_agenda"),
		
		# Lav fix (0.608b6): Dark Knights resolve their issues much faster than other factions
		(try_begin),
			(eq, ":faction_no", "fac_dark_knights"),
			(assign, ":decision_time", 24),
		(else_try),
			(assign, ":decision_time", 120),
		(try_end),
		(this_or_next|gt, ":lords_who_have_voted", ":number_required_for_quorum"),
		(ge, ":hours_on_agenda", ":decision_time"),

		(try_begin),
			(eq, "$cheat_mode", 1),
			(assign, reg4, ":lords_who_have_voted"),
			(assign, reg5, ":number_required_for_quorum"),
			(assign, reg7, ":hours_on_agenda"),
			(str_store_faction_name, s4, ":faction_no"),
			(display_message, "@{!}DEBUG -- Issue resolution for {s4}: {reg4} votes for a quorum of {reg5}, {reg7} hours on agenda"),
		(try_end),


		(try_begin),
		  (eq, "$cheat_mode", 1),
		  (display_message, "@{!}DEBUG -- Faction resolves political issue"),
		(try_end),

	
		#Resolve faction political issue
		(assign, ":winning_candidate", -1),
		(try_begin),
			(call_script, "script_troop_get_relation_with_troop", ":faction_leader", ":popular_favorite"),
			
			(this_or_next|ge, reg0, 10),
			(this_or_next|troop_slot_eq, ":faction_leader", slot_troop_stance_on_faction_issue, ":popular_favorite"),
				(troop_slot_eq, ":faction_leader", slot_troop_stance_on_faction_issue, -1),
						
			(assign, ":winning_candidate", ":popular_favorite"),
		(else_try),#Lord overrules lords' opinion		
			(gt, ":faction_leader", -1), #not sure why this is necessary
			(troop_get_slot, ":liege_choice", ":faction_leader", slot_troop_stance_on_faction_issue),
			(ge, ":liege_choice", -1),
							
			(assign, ":winning_candidate", ":liege_choice"),
		(try_end),

		#Carry out faction decision
		(try_begin), #Nothing happens
			(eq, ":winning_candidate", -1),
			
		(else_try), #For player, create a menu to accept or refuse
			(eq, ":winning_candidate", "trp_player"),
			(eq, "$players_kingdom", ":faction_no"),
			(call_script, "script_add_notification_menu", "mnu_notification_player_faction_political_issue_resolved_for_player", 0, 0),
		(else_try),
			(eq, ":winning_candidate", "trp_player"),
			(neq, "$players_kingdom", ":faction_no"),

			(try_begin),
				(eq, "$cheat_mode", 1),
				(str_store_faction_name, s4, ":faction_no"),
				(str_store_party_name, s5, ":winning_candidate"),
				(display_message, "@{!}DEBUG -- {s4} drops {s5} as winner, for having changed sides"),
			(try_end),
			
			(try_for_range, ":active_npc", active_npcs_begin, active_npcs_end),
				(store_faction_of_troop, ":active_npc_faction", ":active_npc"),
				(eq, ":active_npc_faction", ":faction_no"),
				(troop_set_slot, ":active_npc", slot_troop_stance_on_faction_issue, -1),
			(try_end),		
			(try_begin),
				(eq, "$players_kingdom", ":faction_no"),
				(troop_set_slot, "trp_player", slot_troop_stance_on_faction_issue, -1),
			(try_end),
			
		(else_try),	#If candidate is not of winning faction, reset lrod votes
			(store_faction_of_troop, ":winning_candidate_faction", ":winning_candidate"),
			(neq, ":winning_candidate_faction", ":faction_no"),
			
			(try_begin),
				(eq, "$cheat_mode", 1),
				(str_store_faction_name, s4, ":faction_no"),
				(str_store_party_name, s5, ":winning_candidate"),
				(display_message, "@{!}DEBUG -- {s4} drops {s5} as winner, for having changed sides"),
			(try_end),
			
			(try_for_range, ":active_npc", active_npcs_begin, active_npcs_end),
				(store_faction_of_troop, ":active_npc_faction", ":active_npc"),
				(eq, ":active_npc_faction", ":faction_no"),
				(troop_set_slot, ":active_npc", slot_troop_stance_on_faction_issue, -1),
			(try_end),		
			(try_begin),
				(eq, "$players_kingdom", ":faction_no"),
				(troop_set_slot, "trp_player", slot_troop_stance_on_faction_issue, -1),
			(try_end),
			
		(else_try), #Honor awarded to another
			(faction_get_slot, ":issue_on_table", ":faction_no", slot_faction_political_issue),
			(try_begin), #A marshalship awarded to another
				(eq, ":issue_on_table", 1),
				(is_between, ":winning_candidate", active_npcs_begin, active_npcs_end),
				
				(this_or_next|is_between, ":winning_candidate", active_npcs_begin, active_npcs_end), #Prevents bug in which player given marshaldom of kingdom of which he/she is not a member
					(eq, "$players_kingdom", ":faction_no"),
				
				(assign, ":faction_marshal", ":winning_candidate"),
			(else_try), #A fief awarded to another
				(is_between, ":issue_on_table", centers_begin, centers_end),
				
				#If given to the player, resolved above
				(call_script, "script_give_center_to_lord", ":issue_on_table", ":winning_candidate", 0), #Zero means don't add garrison
				
				#If the player had requested a captured castle
				(try_begin),
					(eq, ":issue_on_table", "$g_castle_requested_by_player"),
					(party_slot_ge, ":issue_on_table", slot_town_lord, active_npcs_begin),
					(store_faction_of_party, ":faction_of_issue", ":issue_on_table"),
					(eq, ":faction_of_issue", "$players_kingdom"),
					(assign, "$g_center_to_give_to_player", ":issue_on_table"),
					(try_begin),
						(troop_get_slot, ":husband", "trp_player", slot_troop_spouse),
						(is_between, ":husband", active_npcs_begin, active_npcs_end),
						(eq, "$g_castle_requested_for_troop", ":husband"),
						(neq, ":winning_candidate", ":husband"),
						(jump_to_menu, "mnu_requested_castle_granted_to_another_female"),
					(else_try),
						(jump_to_menu, "mnu_requested_castle_granted_to_another"),
					(try_end),	
				(try_end),
				
			(try_end),
		
			(try_begin),
				(eq, ":faction_no", "$players_kingdom"),
				(call_script, "script_add_notification_menu", "mnu_notification_player_faction_political_issue_resolved", ":issue_on_table", ":winning_candidate"),
			(try_end),
		
		#Reset political issue
			(faction_set_slot, ":faction_no", slot_faction_political_issue, 0),
			(try_for_range, ":active_npc", active_npcs_begin, active_npcs_end),
				(store_faction_of_troop, ":active_npc_faction", ":active_npc"),
				(eq, ":active_npc_faction", ":faction_no"),
				(troop_set_slot, ":active_npc", slot_troop_stance_on_faction_issue, -1),
			(try_end),
			(try_begin),
				(eq, "$players_kingdom", ":faction_no"),
				(troop_set_slot, "trp_player", slot_troop_stance_on_faction_issue, -1),
			(try_end),			
		(try_end),
	(try_end),

	#Add fief to faction issues
	(try_begin),
		(faction_get_slot, ":faction_issue", ":faction_no", slot_faction_political_issue),
		(le, ":faction_issue", 0),
		
		(assign, ":landless_lords", 0),
		(assign, ":unassigned_centers", 0),
		(assign, ":first_unassigned_center_found", 0),
		
		(troop_set_slot, "trp_player", slot_troop_temp_slot, 0),
		(try_for_range, ":active_npc", active_npcs_begin, active_npcs_end),
			(troop_set_slot, ":active_npc", slot_troop_temp_slot, 0),
		(try_end),
		
		(try_for_range, ":center", centers_begin, centers_end),
			(store_faction_of_party, ":center_faction", ":center"),
			(eq, ":center_faction", ":faction_no"),
			
			(party_get_slot, ":town_lord", ":center", slot_town_lord),
			
			(try_begin),
				(lt, ":town_lord", 0),
				(val_add, ":unassigned_centers", 1),
				(try_begin),
					(eq, ":first_unassigned_center_found", 0),
					(assign, ":first_unassigned_center_found", ":center"),
				(try_end),
			(else_try),
				(troop_set_slot, ":town_lord", slot_troop_temp_slot, 1),			
			(try_end),
		(try_end),
		
		(store_add, ":landless_lords_plus_unassigned_centers", ":landless_lords", ":unassigned_centers"),
		(ge, ":landless_lords_plus_unassigned_centers", 2),		
			
		(faction_set_slot, ":faction_no", slot_faction_political_issue, ":first_unassigned_center_found"),	
		(store_current_hours, ":hours"),
		(faction_set_slot, ":faction_no", slot_faction_political_issue_time, ":hours"), #Fief put on agenda
		
		(try_for_range, ":active_npc", active_npcs_begin, active_npcs_end),
			(store_faction_of_troop, ":active_npc_faction", ":active_npc"),
			(eq, ":active_npc_faction", ":faction_no"),
			(troop_set_slot, ":active_npc", slot_troop_stance_on_faction_issue, -1),
		(try_end),
		(try_begin),
			(eq, "$players_kingdom", ":faction_no"),
			(troop_set_slot, "trp_player", slot_troop_stance_on_faction_issue, -1),
		(try_end),				
	(try_end),
	 
	 
    (try_begin), #If the marshal is changed
       (neg|faction_slot_eq, ":faction_no", slot_faction_marshall, ":faction_marshal"),
       #(assign, ":marshall_changed", 1),
       (eq, "$players_kingdom", ":faction_no"),
       (str_store_troop_name_link, s1, ":faction_marshal"),
       (str_store_faction_name_link, s2, ":faction_no"),
       (display_message, "@{s1} is the new marshal of {s2}."),
       (call_script, "script_check_and_finish_active_army_quests_for_faction", ":faction_no"),       
    (try_end),	 
	 
    (try_begin), #If the marshal is changed
       (neg|faction_slot_eq, ":faction_no", slot_faction_marshall, ":faction_marshal"),
	   (gt, ":faction_marshal", -1),
       (call_script, "script_appoint_faction_marshall", ":faction_no", ":faction_marshal"),   
    (try_end),	 
		 
	#DO FACTION AI HERE
	(try_begin),
		(eq, ":faction_no", "$players_kingdom"),
		(eq, ":faction_marshal", "trp_player"),
	    (assign, ":faction_ai_decider", "trp_player"),
	(else_try),
		(is_between, ":faction_marshal", active_npcs_begin, active_npcs_end),
		(assign, ":faction_ai_decider", ":faction_marshal"),
	(else_try),
		(faction_get_slot, ":faction_ai_decider", ":faction_no", slot_faction_leader),
	(try_end),
	 
    (call_script, "script_npc_decision_checklist_faction_ai_alt",  ":faction_ai_decider"),
    (assign, ":new_strategy", reg0),
    (assign, ":new_object", reg1),
    	     
    ###new ozan
    (try_begin),
       (neq, ":new_strategy", ":old_faction_ai_state"),
       (eq, ":new_strategy", sfai_gathering_army),
       (faction_get_slot, ":faction_marshal", ":faction_no", slot_faction_marshall),
       (troop_get_slot, ":marshal_party", ":faction_marshal", slot_troop_leaded_party),
       (party_set_slot, ":marshal_party", slot_party_ai_object, -1),
       (assign, "$g_gathering_new_started", 1),
       (call_script, "script_npc_decision_checklist_party_ai", ":faction_marshal"), #This handles AI for both marshal and other parties		
       (call_script, "script_party_set_ai_state", ":marshal_party", reg0, reg1),
       (assign, "$g_gathering_new_started", 0),
    (else_try),      
       #check if marshal arrived his target city during active gathering
       
       #for now i disabled below lines because after always/active gathering armies become very large.
       #in current style marshal makes active gathering only at first, it travels to a city and waits there.
       
       (eq, ":new_strategy", ":old_faction_ai_state"),
       (eq, ":new_strategy", sfai_gathering_army),
       (faction_get_slot, ":faction_marshal", ":faction_no", slot_faction_marshall),
       (troop_get_slot, ":marshal_party", ":faction_marshal", slot_troop_leaded_party),
       (party_get_slot, ":party_ai_object", ":marshal_party", slot_party_ai_object),
       (ge, ":party_ai_object", 0),
       (store_distance_to_party_from_party, ":dist", ":marshal_party", ":party_ai_object"),
       (le, ":dist", 5),
       (party_set_slot, ":marshal_party", slot_party_ai_object, -1),
    (try_end),
     ##end ozan
	   	   	   
     #The following logic is mostly transplanted to the new decision_checklist 
     #Decision_checklist is used because I want to be able to reproduce the logic for strings
     #(call_script, "script_old_faction_ai"), 
     #ozan - I collected all comment-out lines in here (faction ai script) and placed most bottom of scripts.py to avoid confusing.	   		 	
     
    (faction_set_slot, ":faction_no", slot_faction_ai_state, ":new_strategy"),
    (faction_set_slot, ":faction_no", slot_faction_ai_object, ":new_object"),

    (call_script, "script_update_report_to_army_quest_note", ":faction_no", ":new_strategy", ":old_faction_ai_state"),

    (try_begin),
       (eq, ":new_strategy", sfai_feast),
       
       (store_current_hours, ":hours"),
       (faction_set_slot, ":faction_no", slot_faction_last_feast_start_time, ":hours"), #new
       
       (try_begin),
         (eq, "$g_player_eligible_feast_center_no", ":new_object"),
         (assign, "$g_player_eligible_feast_center_no", -1), #reset needed
       (try_end),
       (try_begin),
         (is_between, ":new_object", towns_begin, towns_end),
         (party_set_slot, ":new_object", slot_town_has_tournament, 2),
       (try_end),
    (try_end),	
	
     #Change of strategy
    (try_begin),
       (neq, ":new_strategy", ":old_faction_ai_state"),
		
       (try_begin),
         (ge, "$cheat_mode", 1),
         (str_store_faction_name, s5, ":faction_no"),
         (display_message, "str_s5_decides_s14"),
       (try_end),
		
       (store_current_hours, ":hours"),
       (faction_set_slot, ":faction_no", slot_faction_ai_current_state_started, ":hours"),

       #Feast ends
       (try_begin),
         (eq, ":old_faction_ai_state", sfai_feast),
         (call_script, "script_faction_conclude_feast", ":faction_no", ":old_faction_ai_object"),
       (try_end),

	   
       #Feast begins
       (try_begin),
         (eq, ":new_strategy", sfai_feast),
         (faction_get_slot, ":faction_object", ":faction_no", slot_faction_ai_object),
		 
##         (str_store_faction_name, s1, ":faction_no"),
##         (str_store_party_name, s2, ":faction_object"),
##         (display_message, "str_lords_of_the_s1_gather_for_a_feast_at_s2"),
		
         (party_get_slot, ":feast_host", ":faction_object", slot_town_lord),

         (try_begin),
           (check_quest_active, "qst_wed_betrothed"),
		   
           (quest_slot_eq, "qst_wed_betrothed", slot_quest_giver_troop, ":feast_host"),
           (neg|quest_slot_ge, "qst_wed_betrothed", slot_quest_expiration_days, 362),
           (call_script, "script_add_notification_menu", "mnu_notification_player_wedding_day", ":feast_host", ":faction_object"),
		 (else_try),
           (check_quest_active, "qst_wed_betrothed_female"),
		   
           (quest_get_slot, ":player_betrothed", "qst_wed_betrothed", slot_quest_giver_troop),
		   (store_faction_of_troop, ":player_betrothed_faction", ":player_betrothed"),
		   (eq, ":player_betrothed_faction", ":faction_no"),
           (neg|quest_slot_ge, "qst_wed_betrothed", slot_quest_expiration_days, 362),
           (call_script, "script_add_notification_menu", "mnu_notification_player_kingdom_holds_feast", ":feast_host", ":faction_object"),
         (else_try),
           (eq, "$players_kingdom", ":faction_no"),
           (troop_slot_ge, "trp_player", slot_troop_renown, 150),
		   
		   
           (party_get_slot, ":feast_host", ":faction_object", slot_town_lord),
           (call_script, "script_add_notification_menu", "mnu_notification_player_kingdom_holds_feast", ":feast_host", ":faction_object"),
         (try_end),
       (try_end),
		

       #Offensive begins
       (try_begin),
         (eq, ":old_faction_ai_state", sfai_gathering_army),
         (is_between, ":new_strategy", sfai_attacking_center, sfai_feast),
		 (try_begin),
			(eq, "$cheat_mode", 1),
			(str_store_faction_name, s5, ":faction_no"),
			(display_message, "str_s5_begins_offensive"),
		 (try_end),
			
         #Appoint screening party
         (try_begin),
           (assign, ":total_lords_participating", 0),
           (assign, ":best_screening_party", -1),
           (assign, ":score_to_beat", 30), #closest in size to 50
           (troop_get_slot, ":faction_marshal_party", ":faction_marshal", slot_troop_leaded_party),
           (party_is_active, ":faction_marshal_party"),							

           (try_for_range, ":screen_leader", active_npcs_begin, active_npcs_end),
             (store_faction_of_troop, ":screen_leader_faction", ":screen_leader"),
             (eq, ":screen_leader_faction", ":faction_no"),
			 
             (troop_get_slot, ":screening_party", ":screen_leader", slot_troop_leaded_party),
             (party_is_active, ":screening_party"),			
             (party_slot_eq, ":screening_party", slot_party_ai_state, spai_accompanying_army),
             (party_slot_eq, ":screening_party", slot_party_ai_object, ":faction_marshal_party"),
             (val_add, ":total_lords_participating", 1),

		     (try_begin),
			  (ge, "$cheat_mode", 1),
		      (str_store_party_name, s4, ":screening_party"),
			  (display_message, "@{!}DEBUG -- {s4} participates in offensive"),
		     (try_end),

			 
             (store_party_size_wo_prisoners, ":screening_party_score", ":screening_party"),
             (val_sub, ":screening_party_score", 50),
			 (val_abs, ":screening_party_score"),
			 
			 
			 (lt, ":screening_party_score", ":score_to_beat"),

             #set party and score
             (assign, ":best_screening_party", ":screening_party"),
             (assign, ":score_to_beat", ":screening_party_score"),
           (try_end),			

           (gt, ":total_lords_participating", 2),
           (party_is_active, ":best_screening_party"),
           (party_is_active, ":faction_marshal_party"),
           (call_script, "script_party_set_ai_state", ":best_screening_party", spai_screening_army, ":faction_marshal_party"),
		   (try_begin),
			(ge, "$cheat_mode", 1),
		    (str_store_party_name, s4, ":best_screening_party"),
			(display_message, "@{!}DEBUG -- {s4} chosen as screen"),
		   (try_end),
           #after this - dialogs on what doing, npc_decision_checklist
         (try_end),	
		 
       #Offensive concludes
       (else_try),
	     (store_current_hours, ":hours"),
         (this_or_next|eq, ":old_faction_ai_state", sfai_gathering_army),
         (this_or_next|eq, ":old_faction_ai_state", sfai_attacking_center),
         (this_or_next|eq, ":old_faction_ai_state", sfai_raiding_village),
		 #(this_or_next|eq, ":old_faction_ai_state", sfai_attacking_enemies_around_center),
			(eq, ":old_faction_ai_state", sfai_attacking_enemy_army),
		 
         (this_or_next|eq, ":new_strategy", sfai_default),
			(eq, ":new_strategy", sfai_feast),				
						
         (call_script, "script_check_and_finish_active_army_quests_for_faction", ":faction_no"),       		 
         (faction_set_slot, ":faction_no", slot_faction_last_offensive_concluded, ":hours"),
        (try_end),
    (try_end),
	
    (try_begin),
       (eq, "$players_kingdom", ":faction_no"),
       (neg|faction_slot_eq, ":faction_no", slot_faction_ai_state, sfai_attacking_center),
       (check_quest_active, "qst_join_siege_with_army"),
       (call_script, "script_abort_quest", "qst_join_siege_with_army", 0),
    (try_end),

    (try_begin),
       #old condition to rest, I changed below part - ozan, to rest (a faction's old strategy should be feast or default) and (a faction's new strategy should be feast or default)
       #(this_or_next|eq, ":new_strategy", sfai_default),
       #(this_or_next|eq, ":new_strategy", sfai_feast),
       #(this_or_next|eq, ":old_faction_ai_state", sfai_default),
       #(eq, ":old_faction_ai_state", sfai_feast),
       
       #new condition to rest, (a faction's new strategy should be feast or default) and (":hours_at_current_state" > 20)
       (this_or_next|eq, ":new_strategy", sfai_default),
		(eq, ":new_strategy", sfai_feast),                            
              
       (store_current_hours, ":hours_at_current_state"),
       (faction_get_slot, ":current_state_started", ":faction_no", slot_faction_ai_current_state_started), 
       (val_sub, ":hours_at_current_state", ":current_state_started"),
       (ge, ":hours_at_current_state", 18), #Must have at least 18 hours to reset
              
       (store_current_hours, ":hours"),       
       (faction_set_slot, ":faction_no", slot_faction_ai_last_rest_time, ":hours"),		
    (try_end),     
  ]),

  # script_check_and_finish_active_army_quests_for_faction
  # Input: faction_no
  # Output: none
  ("check_and_finish_active_army_quests_for_faction",
   [
     (store_script_param_1, ":faction_no"),
     (try_begin),
       (eq, "$players_kingdom", ":faction_no"),
       (try_begin),
         (check_quest_active, "qst_report_to_army"),
         (call_script, "script_cancel_quest", "qst_report_to_army"),
       (try_end),
       (assign, ":one_active", 0),
       (try_for_range, ":quest_no", army_quests_begin, army_quests_end),
         (check_quest_active, ":quest_no"),
         (call_script, "script_cancel_quest", ":quest_no"),
		 (troop_get_slot, ":army_quest_giver_troop", ":quest_no", slot_quest_giver_troop),
         (assign, ":one_active", 1),
       (try_end),
       (try_begin),
         (check_quest_active, "qst_follow_army"),
         (assign, ":one_active", 1),
		 (troop_get_slot, ":army_quest_giver_troop", "qst_follow_army", slot_quest_giver_troop),
         (call_script, "script_end_quest", "qst_follow_army"),
       (try_end),
       (eq, ":one_active", 1),
       (faction_get_slot, ":last_offensive_time", ":faction_no", slot_faction_last_offensive_concluded),
       (store_current_hours, ":cur_hours"),
       (store_sub, ":total_time_served", ":cur_hours", ":last_offensive_time"),
       (store_mul, ":xp_reward", ":total_time_served", 5),
       (val_div, ":xp_reward", 50),
       (val_mul, ":xp_reward", 50),
       (val_add, ":xp_reward", 50),
       (add_xp_as_reward, ":xp_reward"),
	   (call_script, "script_troop_change_relation_with_troop", "trp_player", ":army_quest_giver_troop", 2),
     (try_end),
    ]),
  
    # script_troop_get_player_relation
    # Input: arg1 = troop_no
    # Output: reg0 = effective relation (modified by troop reputation, honor, etc.)
    ("troop_get_player_relation",
      [
        (store_script_param_1, ":troop_no"),
        (troop_get_slot, ":reputation", ":troop_no", slot_lord_reputation_type),
        (troop_get_slot, ":effective_relation", ":troop_no", slot_troop_player_relation),
        (assign, ":honor_bonus", 0),
        (try_begin),
          (eq,  ":reputation", lrep_quarrelsome),
          (val_add, ":effective_relation", -3),
        (try_end),
        (try_begin),
          (ge, "$player_honor", 0),
          (try_begin),
            (this_or_next|eq,  ":reputation", lrep_upstanding),
            (             eq,  ":reputation", lrep_goodnatured),
            (store_div, ":honor_bonus", "$player_honor", 3),
          (try_end),
        (try_end),
        (try_begin),
          (lt, "$player_honor", 0),
          (try_begin),
            (this_or_next|eq,  ":reputation", lrep_upstanding),
            (             eq,  ":reputation", lrep_goodnatured),
            (store_div, ":honor_bonus", "$player_honor", 3),
          (else_try),
            (eq,  ":reputation", lrep_martial),
            (store_div, ":honor_bonus", "$player_honor", 5),
          (try_end),
        (try_end),
        (val_add, ":effective_relation", ":honor_bonus"),
        (val_clamp, ":effective_relation", -100, 101),
        (assign, reg0, ":effective_relation"),
    ]),
  
  # 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),

	  (try_begin),
		(gt, ":renown_change", 0),
		(assign, reg4, ":renown_change"),
		
		(store_div, ":subtraction", ":old_renown", 200), 
	    (val_sub, ":renown_change", ":subtraction"),
	    (val_max, ":renown_change", 0),
		
	    (eq, ":troop_no", "trp_player"), 
	    (assign, reg5, ":renown_change"),
		
		(eq, "$cheat_mode", 1),
	    (display_message, "str_renown_change_of_reg4_reduced_to_reg5_because_of_high_existing_renown"),
	  (try_end),

      (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 lose {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"),

      (try_begin),
        (neq, ":troop_no", "trp_player"),
        (neg|is_between, ":troop_no", soldiers_begin, soldiers_end),
		(neq, ":troop_no", -1),
        (neq, ":difference", 0),
        (call_script, "script_troop_get_player_relation", ":troop_no"),
        (assign, ":old_effective_relation", reg0),
        (troop_get_slot, ":player_relation", ":troop_no", slot_troop_player_relation),
        (val_add, ":player_relation", ":difference"),
        (val_clamp, ":player_relation", -100, 101),
        (try_begin),
          (troop_set_slot, ":troop_no", slot_troop_player_relation, ":player_relation"),
          
          (try_begin),
            (le, ":player_relation", -50),
            (unlock_achievement, ACHIEVEMENT_OLD_DIRTY_SCOUNDREL),
          (try_end),
          
          (str_store_troop_name_link, s1, ":troop_no"),
          (call_script, "script_troop_get_player_relation", ":troop_no"),
          (assign, ":new_effective_relation", reg0),
          (neq, ":old_effective_relation", ":new_effective_relation"),
          (assign, reg1, ":old_effective_relation"),
          (assign, reg2, ":new_effective_relation"),
          (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", ":new_effective_relation"),
            (call_script, "script_setup_talk_info"),
          (try_end),
          (call_script, "script_update_troop_notes", ":troop_no"),
        (try_end),
      (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"),

      (try_begin),
        (le, ":player_relation", -50),
        (unlock_achievement, ACHIEVEMENT_OLD_DIRTY_SCOUNDREL),
      (try_end),

      
      (str_store_party_name_link, 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),
	  # ne noble
	  (try_begin),
        (party_slot_eq, ":center_no", slot_party_type, spt_town),
        (call_script, "script_update_volunteer_troops_in_town", ":center_no"),
      (try_end),
      # ne end noble
	  
      (try_begin),
        (this_or_next|is_between, "$g_talk_troop", village_elders_begin, village_elders_end),
        (is_between, "$g_talk_troop", mayors_begin, mayors_end),
        (assign, "$g_talk_troop_relation", ":player_relation"),
        (call_script, "script_setup_talk_info"),
      (try_end),
  ]),
  
  
  # 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_supporters_faction"),
      (assign, reg1, ":player_relation"),
      (val_add, ":player_relation", ":difference"),
      (assign, reg2, ":player_relation"),
      (set_relation, ":faction_no", "fac_player_faction", ":player_relation"),
      (set_relation, ":faction_no", "fac_player_supporters_faction", ":player_relation"),
      
      (try_begin),
        (le, ":player_relation", -50),
        (unlock_achievement, ACHIEVEMENT_OLD_DIRTY_SCOUNDREL),
      (try_end),

      
      (str_store_faction_name_link, 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),
      (call_script, "script_update_all_notes"),
      ]),

  # script_set_player_relation_with_faction
  # Input: arg1 = faction_no, arg2 = relation
  # Output: none
  ("set_player_relation_with_faction",
    [
      (store_script_param_1, ":faction_no"),
      (store_script_param_2, ":relation"),
      
      (store_relation, ":player_relation", ":faction_no", "fac_player_supporters_faction"),
      (store_sub, ":reln_dif", ":relation", ":player_relation"),
      (call_script, "script_change_player_relation_with_faction", ":faction_no", ":reln_dif"),
      ]),

  
  
  # 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_supporters_faction"),
      (assign, reg1, ":player_relation"),
      (val_add, ":player_relation", ":difference"),
      (assign, reg2, ":player_relation"),
      (set_relation, ":faction_no", "fac_player_faction", ":player_relation"),
      (set_relation, ":faction_no", "fac_player_supporters_faction", ":player_relation"),
      
      (str_store_faction_name_link, 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),
        (faction_slot_eq, ":other_faction", slot_faction_state, sfs_active),
        (neq, ":faction_no", ":other_faction"),
        (store_relation, ":other_faction_relation", ":faction_no", ":other_faction"),
        (store_relation, ":player_relation", ":other_faction", "fac_player_supporters_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"),
        (set_relation, ":other_faction", "fac_player_supporters_faction", ":player_relation"),
      (try_end),
      (try_begin),
        (faction_slot_eq, "fac_player_supporters_faction", slot_faction_state, sfs_active),
        (try_for_range, ":kingdom_no", kingdoms_begin, kingdoms_end),
          (faction_slot_eq, ":kingdom_no", slot_faction_state, sfs_active),
          (call_script, "script_update_faction_notes", ":kingdom_no"),
        (try_end),
      (try_end),
  ]),

  # script_cf_get_random_active_faction_except_player_faction_and_faction
  # Input: arg1 = except_faction_no
  # Output: reg0 = random_faction
  ("cf_get_random_active_faction_except_player_faction_and_faction",
    [
      (store_script_param_1, ":except_faction_no"),
      (assign, ":num_factions", 0),
      (try_for_range, ":faction_no", kingdoms_begin, kingdoms_end),
        (neq, ":faction_no", "fac_player_supporters_faction"),
        (neq, ":faction_no", ":except_faction_no"),
        (faction_slot_eq, ":faction_no", slot_faction_state, sfs_active),
        (val_add, ":num_factions", 1),
      (try_end),
      (gt, ":num_factions", 0),
      (assign, ":selected_faction", -1),
      (store_random_in_range, ":random_faction", 0, ":num_factions"),
      (try_for_range, ":faction_no", kingdoms_begin, kingdoms_end),
        (ge, ":random_faction", 0),
        (neq, ":faction_no", "fac_player_supporters_faction"),
        (neq, ":faction_no", ":except_faction_no"),
        (faction_slot_eq, ":faction_no", slot_faction_state, sfs_active),
        (val_sub, ":random_faction", 1),
        (lt, ":random_faction", 0),
        (assign, ":selected_faction", ":faction_no"),
      (try_end),
      (assign, reg0, ":selected_faction"),
  ]),

 # NE lords
## Begin player kingdom support script - Jinnai
  # script_cf_get_random_active_faction_except_faction
  # Input: arg1 = except_faction_no
  # Output: reg0 = random_faction
  ("cf_get_random_active_faction_except_faction",
    [
      (store_script_param_1, ":except_faction_no"),
      (assign, ":num_factions", 0),
      (try_for_range, ":faction_no", kingdoms_begin, kingdoms_end),
        (neq, ":faction_no", ":except_faction_no"),
        (faction_slot_eq, ":faction_no", slot_faction_state, sfs_active),
        (val_add, ":num_factions", 1),
      (try_end),
      (gt, ":num_factions", 0),
      (assign, ":selected_faction", -1),
      (store_random_in_range, ":random_faction", 0, ":num_factions"),
      (try_for_range, ":faction_no", kingdoms_begin, kingdoms_end),
        (ge, ":random_faction", 0),
        (neq, ":faction_no", ":except_faction_no"),
        (faction_slot_eq, ":faction_no", slot_faction_state, sfs_active),
        (val_sub, ":random_faction", 1),
        (lt, ":random_faction", 0),
        (assign, ":selected_faction", ":faction_no"),
      (try_end),
      (assign, reg0, ":selected_faction"),
  ]),
## End player kingdom support script
# NE end lords 
  
  
  # script_make_kingdom_hostile_to_player
  # Input: arg1 = faction_no, arg2 = relation difference
  # Output: none
  ("make_kingdom_hostile_to_player",
    [
      (store_script_param_1, ":kingdom_no"),
      (store_script_param_2, ":difference"),

      (try_begin),
        (lt, ":difference", 0),
        (store_relation, ":player_relation", ":kingdom_no", "fac_player_supporters_faction"),
        (val_min, ":player_relation", 0),
        (val_add, ":player_relation", ":difference"),
        (call_script, "script_set_player_relation_with_faction", ":kingdom_no", ":player_relation"),
      (try_end),
  ]),
  
  # script_change_player_honor
  # Input: arg1 = honor difference
  # Output: none
  ("change_player_honor",
    [
      (store_script_param_1, ":honor_dif"),
      (val_add, "$player_honor", ":honor_dif"),
      (try_begin),
        (gt, ":honor_dif", 0),
        (display_message, "@You gain honour."),
      (else_try),
        (lt, ":honor_dif", 0),
        (display_message, "@You lose honour."),
      (try_end),

##      (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"),
##      (else_try),
##        (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"),
      (val_clamp, ":cur_morale", 0, 100),
            
      (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_cf_player_has_item_without_modifier
  # Input: arg1 = item_id, arg2 = modifier
  # Output: reg0 = item_modifier if found (can_fail)
  ("cf_player_has_item_without_modifier",
    [
      (store_script_param, ":item_id", 1),
      (store_script_param, ":modifier", 2),
      (player_has_item, ":item_id"),
      #checking if any of the meat is not rotten
      (assign, ":has_without_modifier", 0),
      (troop_get_inventory_capacity, ":inv_size", "trp_player"),
      (try_for_range, ":i_slot", 0, ":inv_size"),
        (troop_get_inventory_slot, ":cur_item", "trp_player", ":i_slot"),
        (eq, ":cur_item", ":item_id"),
        (troop_get_inventory_slot_modifier, ":cur_modifier", "trp_player", ":i_slot"),
        (neq, ":cur_modifier", ":modifier"),
        (assign, ":has_without_modifier", 1),
########################################################################################################################
# LAV MODIFICATIONS START (TRADE GOODS MOD)
########################################################################################################################
        (assign, reg0, ":cur_modifier"),
########################################################################################################################
# LAV MODIFICATIONS END (TRADE GOODS MOD)
########################################################################################################################
        (assign, ":inv_size", 0), #break
      (try_end),
      (eq, ":has_without_modifier", 1),
  ]),

  # 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", 1, ":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", 1), #it was 3 in "Mount&Blade", now it is 1 in Warband
        (else_try),
          (party_stack_get_size, ":stack_size","p_main_party",":i_stack"),
          (val_add, ":num_men", ":stack_size"),
        (try_end),
      (try_end),
# NE kingdom	  
     (val_mul,":num_men",3), #Due to the higher leadership party size, making the morale penalty for large parties smaller - Jinnai
      (val_div,":num_men",4),
      (try_begin), #Give the player 50 slots for free if they're a monarch - Jinnai
        (faction_slot_eq, "fac_player_supporters_faction", slot_faction_state, sfs_active),
        (faction_slot_eq, "fac_player_supporters_faction", slot_faction_leader, "trp_player"),
        (val_sub,":num_men",50),
        (val_max,":num_men",0),
      (try_end),	  
	  
# NE end kingdom	  
      (assign, "$g_player_party_morale_modifier_party_size", ":num_men"),
    
      (store_skill_level, ":player_leadership", "skl_leadership", "trp_player"),
      
      (try_begin),
        (eq, "$players_kingdom", "fac_player_supporters_faction"),
        (faction_get_slot, ":cur_faction_king", "$players_kingdom", slot_faction_leader),
        (eq, ":cur_faction_king", "trp_player"),
        (store_mul, "$g_player_party_morale_modifier_leadership", ":player_leadership", 15),
      (else_try),  
        (store_mul, "$g_player_party_morale_modifier_leadership", ":player_leadership", 12),
      (try_end),  
      
      (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, "$g_player_party_morale_modifier_food", 0),
      (try_for_range, ":cur_edible", food_begin, food_end),      
        (call_script, "script_cf_player_has_item_without_modifier", ":cur_edible", imod_rotten),
        (item_get_slot, ":food_bonus", ":cur_edible", slot_item_food_bonus),
########################################################################################################################
# LAV MODIFICATIONS START (TRADE GOODS MOD)
########################################################################################################################
          (try_begin),
            (eq, reg0, imod_fine),
            (val_add, ":food_bonus", 1),
          (else_try),
            (eq, reg0, imod_well_made),
            (val_add, ":food_bonus", 2),
          (else_try),
            (eq, reg0, imod_lordly),
            (val_add, ":food_bonus", 5),
          (else_try),
            (eq, reg0, imod_exquisite),
            (val_add, ":food_bonus", 6),
          (try_end),
########################################################################################################################
# LAV MODIFICATIONS END (TRADE GOODS MOD)
########################################################################################################################
        
        (val_mul, ":food_bonus", 3),
        (val_div, ":food_bonus", 2),
        
        (val_add, "$g_player_party_morale_modifier_food", ":food_bonus"),
      (try_end),
      (val_add, ":new_morale", "$g_player_party_morale_modifier_food"),
	 
# NE food	 
      (call_script, "script_get_troop_item_amount", "trp_player", "itm_hardtack"), #Food morale bug fix - Jinnai
      (assign, ":hardtack", reg0),
      (try_begin),
        (eq, "$g_player_party_morale_modifier_food", 0),
        (le, ":hardtack", 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),	  

      # (try_begin),
        # (eq, "$g_player_party_morale_modifier_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),
# NE end food

      (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_max, ":total_wages", 1),
        (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),

# NE food
	  #v585 Josef whiskey	  
      (assign, "$g_player_party_morale_modifier_booze", 0),
       (try_begin),
	  (call_script, "script_get_troop_item_amount", "trp_player", "itm_whiskey"),
	  (assign, ":whiskey", reg0),
	  (try_begin),
       (ge, ":whiskey", 1),
	  (assign, "$g_player_party_morale_modifier_booze", 30),
	  (try_end),
      (val_add, ":new_morale", "$g_player_party_morale_modifier_booze"),
	  (try_end), 
	 # NE end food
	  
      (val_clamp, ":new_morale", 0, 100),
      (assign, reg0, ":new_morale"),
      ]),
  
  # script_diplomacy_start_war_between_kingdoms
  # Input: arg1 = kingdom_1, arg2 = kingdom_2, arg3 = initializing_war_peace_cond
  # Output: none
  ("diplomacy_start_war_between_kingdoms", #sets relations between two kingdoms and their vassals.
    [
      (store_script_param, ":kingdom_a", 1),
      (store_script_param, ":kingdom_b", 2),
      (store_script_param, ":initializing_war_peace_cond", 3), #1 = after start of game

	  (call_script, "script_npc_decision_checklist_peace_or_war", ":kingdom_a", ":kingdom_b", -1),
	  (assign, ":explainer_string", reg1),
	  
	  #
	  (try_begin),
	    (eq, ":kingdom_a", "fac_player_supporters_faction"),
		(assign, ":war_event", logent_player_faction_declares_war),
	  (else_try),	
		(eq, ":explainer_string", "str_s12s15_declared_war_to_control_calradia"),
		(assign, ":war_event", logent_player_faction_declares_war), #for savegame compatibility, this event stands in for the attempt to declare war on all of calradia
	  (else_try),
		(eq, ":explainer_string", "str_s12s15_considers_s16_to_be_dangerous_and_untrustworthy_and_shehe_wants_to_bring_s16_down"),
		(assign, ":war_event", logent_faction_declares_war_out_of_personal_enmity),
	  (else_try),	
		(eq, ":explainer_string", "str_s12s15_is_anxious_to_reclaim_old_lands_such_as_s18_now_held_by_s16"),
		(assign, ":war_event", logent_faction_declares_war_to_regain_territory),
	  (else_try),	
		(eq, ":explainer_string", "str_s12s15_faces_too_much_internal_discontent_to_feel_comfortable_ignoring_recent_provocations_by_s16s_subjects"),
		(assign, ":war_event", logent_faction_declares_war_to_respond_to_provocation),
	  (else_try),	
		(eq, ":explainer_string", "str_s12s15_is_alarmed_by_the_growing_power_of_s16"),
		(assign, ":war_event", logent_faction_declares_war_to_curb_power),
	  (try_end),
	  (call_script, "script_add_log_entry", ":war_event", ":kingdom_a", 0, 0, ":kingdom_b"),
	  
	  
	  
	  (call_script, "script_diplomacy_faction_get_diplomatic_status_with_faction", ":kingdom_a", ":kingdom_b"),
	  (assign, ":current_diplomatic_status", reg0),
	  (try_begin), #effects of policy only after the start of the game
	    (eq, ":initializing_war_peace_cond", 1),
		(eq, ":current_diplomatic_status", -1),
		(call_script, "script_faction_follows_controversial_policy", ":kingdom_a", logent_policy_ruler_declares_war_with_justification),
	  (else_try),
	    (eq, ":initializing_war_peace_cond", 1),	  
		(eq, ":current_diplomatic_status", 0),
		(call_script, "script_faction_follows_controversial_policy", ":kingdom_a", logent_policy_ruler_attacks_without_provocation),
	  (else_try),
		(eq, ":current_diplomatic_status", 1),
		(call_script, "script_faction_follows_controversial_policy", ":kingdom_a", logent_policy_ruler_breaks_truce),
	  (try_end),
      
      (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_supporters_faction", ":kingdom_b"),
        (val_min, ":relation", -30),
        (call_script, "script_set_player_relation_with_faction", ":kingdom_b", ":relation"),
      (else_try),
        (eq, "$players_kingdom", ":kingdom_b"),
        (store_relation, ":relation", "fac_player_supporters_faction", ":kingdom_a"),
        (val_min, ":relation", -30),
        (call_script, "script_set_player_relation_with_faction", ":kingdom_a", ":relation"),
      (try_end),

      (try_begin),
        (eq, ":initializing_war_peace_cond", 1),
		
		#Remove this -- this scrambles who declares war on whom
#        (try_begin),
 #         (store_random_in_range, ":random_no", 0, 2),
  #        (this_or_next|eq, ":kingdom_a", "fac_player_supporters_faction"),
	#		(eq, ":random_no", 0),
     #     (assign, ":local_temp", ":kingdom_a"),
      #    (assign, ":kingdom_a", ":kingdom_b"),
       #   (assign, ":kingdom_b", ":local_temp"),
        #(try_end),
		
        (str_store_faction_name_link, s1, ":kingdom_a"),
        (str_store_faction_name_link, s2, ":kingdom_b"),
        (display_log_message, "@{s1} has declared war against {s2}."),

		(store_current_hours, ":hours"),
		(faction_set_slot, ":kingdom_a", slot_faction_ai_last_decisive_event, ":hours"),
		(faction_set_slot, ":kingdom_b", slot_faction_ai_last_decisive_event, ":hours"),
		
		#set provocation and truce days
		(store_add, ":truce_slot", ":kingdom_b", slot_faction_truce_days_with_factions_begin),
		(store_add, ":provocation_slot", ":kingdom_b", slot_faction_provocation_days_with_factions_begin),
		(val_sub, ":truce_slot", kingdoms_begin),
		(val_sub, ":provocation_slot", kingdoms_begin),
		(faction_set_slot, ":kingdom_a", ":truce_slot", 0),
		(faction_set_slot, ":kingdom_a", ":provocation_slot", 0),

		(store_add, ":truce_slot", ":kingdom_a", slot_faction_truce_days_with_factions_begin),
		(store_add, ":provocation_slot", ":kingdom_a", slot_faction_provocation_days_with_factions_begin),
		(val_sub, ":truce_slot", kingdoms_begin),
		(val_sub, ":provocation_slot", kingdoms_begin),
		(faction_set_slot, ":kingdom_b", ":truce_slot", 0),
		(faction_set_slot, ":kingdom_b", ":provocation_slot", 0),
		
        (call_script, "script_add_notification_menu", "mnu_notification_war_declared", ":kingdom_a", ":kingdom_b"),
		
        (call_script, "script_update_faction_notes", ":kingdom_a"),
        (call_script, "script_update_faction_notes", ":kingdom_b"),
        (assign, "$g_recalculate_ais", 1),
      (try_end),
	  
	  (try_begin),
		(check_quest_active, "qst_cause_provocation"),
	    (neg|check_quest_succeeded, "qst_cause_provocation"),
		(this_or_next|eq, "$players_kingdom", ":kingdom_a"),
			(eq, "$players_kingdom", ":kingdom_b"),
		(call_script, "script_abort_quest", "qst_cause_provocation", 0),
	  (try_end),
  ]),

  
  ("diplomacy_party_attacks_neutral", #called from game_menus (plundering a village, raiding a village),  from dialogs: surprise attacking a neutral lord, any attack on caravan or villagers
#Has no effect if factions are already at war  
    [
      (store_script_param, ":attacker_party", 1),
      (store_script_param, ":defender_party", 2),
	  
	  (store_faction_of_party, ":attacker_faction", ":attacker_party"),
	  (store_faction_of_party, ":defender_faction", ":defender_party"),
	  
	  (party_stack_get_troop_id, ":attacker_leader", ":attacker_party", 0),
	  
	  (try_begin),
		(eq, ":attacker_party", "p_main_party"),
		(neq, ":attacker_faction", "fac_player_supporters_faction"),
		(assign, ":attacker_faction", "$players_kingdom"),
	  (else_try),	
		(eq, ":attacker_party", "p_main_party"),
		(eq, ":attacker_faction", "fac_player_supporters_faction"),
	  (try_end),
	  
	  (try_begin),
	    (eq, ":attacker_party", "p_main_party"),
		(store_relation, ":relation", ":attacker_faction", ":defender_faction"),
	    (ge, ":relation", 0),
		(call_script, "script_change_player_honor", -2),
	  (try_end),
	  
	  
	  (try_begin),
		(check_quest_active, "qst_cause_provocation"),
		(quest_slot_eq, "qst_cause_provocation", slot_quest_target_faction, ":defender_faction"),
		(quest_get_slot, ":giver_troop", "qst_cause_provocation", slot_quest_giver_troop),
		(store_faction_of_troop, ":attacker_faction", ":giver_troop"),
		(call_script, "script_succeed_quest", "qst_cause_provocation"),		
	  (try_end),
	  
	  (call_script, "script_diplomacy_faction_get_diplomatic_status_with_faction", ":attacker_faction", ":defender_faction"),
	  (assign, ":diplomatic_status", reg0),
	  
	  (try_begin),
              (eq, ":attacker_faction", "fac_player_supporters_faction"),
		(neg|faction_slot_eq, "fac_player_supporters_faction", slot_faction_state, sfs_active),
		#player faction inactive, no effect
	  (else_try),
		(eq, ":diplomatic_status", -2),
	    #war, no effect
          (else_try),     
               (eq, ":attacker_faction", "fac_player_supporters_faction"),
		(faction_slot_eq, ":attacker_faction", slot_faction_leader, "trp_player"),
		(call_script, "script_faction_follows_controversial_policy", "fac_player_supporters_faction",logent_policy_ruler_attacks_without_provocation),
	  (else_try),	
		(eq, ":diplomatic_status", 1),
		#truce
		(party_stack_get_troop_id, ":defender_party_leader", ":defender_party", 0),
		(try_begin),
			(neg|is_between, ":defender_party_leader", active_npcs_begin, active_npcs_end),
			(store_faction_of_party, ":defender_party_faction", ":defender_party"),
			(faction_get_slot, ":defender_party_leader", ":defender_party_faction", slot_faction_leader),
		(try_end),
		
		(call_script, "script_add_log_entry", logent_border_incident_troop_breaks_truce, ":attacker_leader", -1, ":defender_party_leader", ":attacker_faction"),
	  (else_try),	
		#truce
		(call_script, "script_add_log_entry", logent_border_incident_troop_attacks_neutral, ":attacker_leader", -1, ":defender_party_leader", ":attacker_faction"),
	  (try_end),
	  	  
	  (try_begin),
	    (is_between, ":defender_party", villages_begin, villages_end),
	    (call_script, "script_add_log_entry", logent_village_raided, ":attacker_leader",  ":defender_party", -1, ":defender_faction"),
	  (else_try),
	    (party_get_template_id, ":template", ":defender_party"),
	    (neq, ":template", "pt_kingdom_hero_party"),
		(try_begin),
			(ge, "$cheat_mode", 1),
			(str_store_faction_name, s5, ":defender_faction"),
			(display_message, "@{!}DEbug - {s5} caravan attacked"),
		(try_end),
		
	    (call_script, "script_add_log_entry", logent_caravan_accosted, ":attacker_leader",  -1, -1, ":defender_faction"),
	  (try_end),

	  (store_add, ":slot_truce_days", ":attacker_faction", slot_faction_provocation_days_with_factions_begin),
	  (val_sub, ":slot_truce_days", kingdoms_begin),
	  (faction_set_slot, ":defender_faction", ":slot_truce_days", 0),
	  
	  (store_add, ":slot_provocation_days", ":attacker_faction", slot_faction_provocation_days_with_factions_begin),
	  (val_sub, ":slot_provocation_days", kingdoms_begin),
	  (try_begin),
	    (neq, ":diplomatic_status", -2),
		(faction_slot_eq, ":defender_faction", ":slot_provocation_days", 0),
		(faction_set_slot, ":defender_faction", ":slot_provocation_days", 30),
	  (try_end),	  
	]),
	
  # script_party_calculate_and_set_nearby_friend_enemy_follower_strengths
  # Input: party_no
  # Output: none
  ("party_calculate_and_set_nearby_friend_enemy_follower_strengths",
    [
      (store_script_param, ":party_no", 1),
      (assign, ":follower_strength", 0),
      (assign, ":friend_strength", 0),
      (assign, ":enemy_strength", 0),
      (store_faction_of_party, ":party_faction", ":party_no"),

      (store_add, ":end_cond", active_npcs_end, 1),      
      (try_for_range, ":iteration", active_npcs_begin, ":end_cond"),
        (try_begin),
          (eq, ":iteration", active_npcs_end),
          (assign, ":cur_troop", "trp_player"),
        (else_try),
          (assign, ":cur_troop", ":iteration"),
        (try_end),

        (troop_slot_eq, ":cur_troop", slot_troop_occupation, slto_kingdom_hero),
        (troop_get_slot, ":cur_troop_party", ":cur_troop", slot_troop_leaded_party),
        (ge, ":cur_troop_party", 0),
        (party_is_active, ":cur_troop_party"),

         
        #I moved these lines here from (*1) to faster process, ozan.
        (store_troop_faction, ":army_faction", ":cur_troop"),
        (store_relation, ":relation", ":army_faction", ":party_faction"),        
        (this_or_next|neq, ":relation", 0),
        (eq, ":army_faction", ":party_faction"),
        #ozan end


        (neq, ":party_no", ":cur_troop_party"),
        (party_get_slot, ":str", ":cur_troop_party", slot_party_cached_strength),
        (try_begin),
          (neg|is_between, ":party_no", centers_begin, centers_end),
          (party_slot_eq, ":cur_troop_party", slot_party_ai_state, spai_accompanying_army),
          (party_get_slot, ":commander_party", ":cur_troop_party", slot_party_ai_object),
          (eq, ":commander_party", ":party_no"),
          (val_add, ":follower_strength", ":str"),
        (else_try),
          (store_distance_to_party_from_party, ":distance", ":cur_troop_party", ":party_no"),
          (lt, ":distance", 20),
        
          #(*1)
          
          (try_begin),
            (lt, ":distance", 5),
            (assign, ":str_divided", ":str"),
          (else_try),
            (lt, ":distance", 10),
            (store_div, ":str_divided", ":str", 2),
          (else_try),
            (lt, ":distance", 15),
            (store_div, ":str_divided", ":str", 4),
          (else_try),
            (store_div, ":str_divided", ":str", 8),
          (try_end),
        
          (try_begin),
            (this_or_next|eq, ":army_faction", ":party_faction"),
            (gt, ":relation", 0),
            (val_add, ":friend_strength", ":str_divided"),
          (else_try),
            (lt, ":relation", 0),
            (val_add, ":enemy_strength", ":str_divided"),
          (try_end),
        (try_end),
      (try_end),
      
      (party_set_slot, ":party_no", slot_party_follower_strength, ":follower_strength"),
      (party_set_slot, ":party_no", slot_party_nearby_friend_strength, ":friend_strength"),
      (party_set_slot, ":party_no", slot_party_nearby_enemy_strength, ":enemy_strength"),
      ]),
  
  # script_init_ai_calculation
  # Input: none
  # Output: none
  ("init_ai_calculation",
    [
      (try_for_range, ":cur_troop", heroes_begin, heroes_end),
        (troop_slot_eq, ":cur_troop", slot_troop_occupation, slto_kingdom_hero),
        (troop_get_slot, ":cur_party", ":cur_troop", slot_troop_leaded_party),
        (party_is_active, ":cur_party"),
        (call_script, "script_party_calculate_strength", ":cur_party", 0), #will update slot_party_cached_strength
      (try_end),
      (call_script, "script_party_calculate_strength", "p_main_party", 0), #will update slot_party_cached_strength
      (try_for_range, ":cur_center", walled_centers_begin, walled_centers_end),
        (call_script, "script_party_calculate_strength", ":cur_center", 0), #will update slot_party_cached_strength
      (try_end),

      (try_for_range, ":cur_center", walled_centers_begin, walled_centers_end),
        (call_script, "script_party_calculate_and_set_nearby_friend_enemy_follower_strengths", ":cur_center"),
      (try_end),

      (try_for_range, ":cur_troop", heroes_begin, heroes_end),
        (troop_get_slot, ":cur_troop_party", ":cur_troop", slot_troop_leaded_party),
        (gt, ":cur_troop_party", 0),
        (party_is_active, ":cur_troop_party"),
        (call_script, "script_party_calculate_and_set_nearby_friend_enemy_follower_strengths", ":cur_troop_party"),
      (try_end),
      (call_script, "script_party_calculate_and_set_nearby_friend_enemy_follower_strengths", "p_main_party"),
      ]),


  # script_recalculate_ais
  # Input: none
  # Output: none
  
  #When a lord changes factions
  #When a center changes factions
  #When a center is captured
  #When a marshal is defeated
  #Every 23 hours
    ("recalculate_ais",
    [
      (call_script, "script_init_ai_calculation"),
            
      (try_for_range, ":faction_no", kingdoms_begin, kingdoms_end),
      (assign, reg8, ":faction_no"),
        (faction_slot_eq, ":faction_no", slot_faction_state, sfs_active),
        #(neg|faction_slot_eq, ":faction_no",  slot_faction_marshall, "trp_player"),
		#(try_begin), 
		# NE dk
		(try_begin), 
		(neq, ":faction_no", "fac_dark_knights"),
		(call_script, "script_decide_faction_ai", ":faction_no"),
		 # (display_message, "@{!}Call normal script_decide_faction_ai"),
		
		(else_try),
	    (call_script, "script_decide_faction_ai_dk2", ":faction_no"),
		
		 # (display_message, "@{!}Call dk script_decide_faction_ai"),
		(try_end),
		# NE end dk
		# (try_end),
      (try_end),
      
      (try_for_range, ":troop_no", active_npcs_begin, active_npcs_end),
        (store_troop_faction, ":faction_no", ":troop_no"),        
        (troop_slot_eq, ":troop_no", slot_troop_occupation, slto_kingdom_hero),
        (call_script, "script_calculate_troop_ai", ":troop_no"),
      (try_end),	  
    ]),

  # script_calculate_troop_ai
  # Input: troop_no
  # Output: none
  #Now called directly from scripts
  ("calculate_troop_ai",
    [
      (store_script_param, ":troop_no", 1),

      (try_begin),
        (troop_slot_eq, ":troop_no", slot_troop_occupation, slto_kingdom_hero),
        (neg|troop_slot_ge, ":troop_no", slot_troop_prisoner_of_party, 0),
        (troop_get_slot, ":party_no", ":troop_no", slot_troop_leaded_party),
        (gt, ":party_no", 0),
		(party_is_active, ":party_no"),

		(call_script, "script_npc_decision_checklist_party_ai", ":troop_no"), #This handles AI for both marshal and other parties		
		(call_script, "script_party_set_ai_state", ":party_no", reg0, reg1),
      (try_end),			
    ]),
  
  # script_diplomacy_start_peace_between_kingdoms
  # Input: arg1 = kingdom_1, arg2 = kingdom_2, arg3 = initializing_war_peace_cond
  # Output: none
  ("diplomacy_start_peace_between_kingdoms", #sets relations between two kingdoms
    [
      (store_script_param, ":kingdom_a", 1),
      (store_script_param, ":kingdom_b", 2),
      (store_script_param, ":initializing_war_peace_cond", 3), #set to 1 if not the start of the game

      (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_supporters_faction", ":kingdom_b"),
        (val_max, ":relation", 0),
        (call_script, "script_set_player_relation_with_faction", ":kingdom_b", ":relation"),
        (call_script, "script_event_kingdom_make_peace_with_kingdom", ":kingdom_b", "fac_player_supporters_faction"), #event cancels certain quests
      (else_try),
        (eq, "$players_kingdom", ":kingdom_b"),
        (store_relation, ":relation", "fac_player_supporters_faction", ":kingdom_a"),
        (val_max, ":relation", 0),
        (call_script, "script_set_player_relation_with_faction", ":kingdom_a", ":relation"),
        (call_script, "script_event_kingdom_make_peace_with_kingdom", ":kingdom_a", "fac_player_supporters_faction"), #event cancels certain quests
      (try_end),
      
      (try_for_range, ":cur_center", centers_begin, centers_end),
        (store_faction_of_party, ":faction_no", ":cur_center"),
        (this_or_next|eq, ":faction_no", ":kingdom_a"),
        (eq, ":faction_no", ":kingdom_b"),        
        (party_get_slot, ":besieger_party", ":cur_center", slot_center_is_besieged_by),
        (ge, ":besieger_party", 0), #town is under siege
        (party_is_active, ":besieger_party"),        
        (store_faction_of_party, ":besieger_party_faction_no", ":besieger_party"),
        (this_or_next|eq, ":besieger_party_faction_no", ":kingdom_a"),
        (eq, ":besieger_party_faction_no", ":kingdom_b"),
        (call_script, "script_lift_siege", ":cur_center", 0),
      (try_end),
      
      (try_begin),
        (this_or_next|eq, "$players_kingdom", ":kingdom_a"),
        (eq, "$players_kingdom", ":kingdom_b"),

        (ge, "$g_player_besiege_town", 0),
        (party_is_active, "$g_player_besiege_town"),        
        
        (store_faction_of_party, ":besieged_center_faction_no", "$g_player_besiege_town"),
        
        (this_or_next|eq, ":besieged_center_faction_no", ":kingdom_a"),
        (eq, ":besieged_center_faction_no", ":kingdom_b"),

        (call_script, "script_lift_siege", "$g_player_besiege_town", 0),
        (assign, "$g_player_besiege_town", -1),
      (try_end),

      (try_begin),
        (eq, ":initializing_war_peace_cond", 1),
        (str_store_faction_name_link, s1, ":kingdom_a"),
        (str_store_faction_name_link, s2, ":kingdom_b"),
        (display_log_message, "@{s1} and {s2} have made peace with each other."),
        (call_script, "script_add_notification_menu", "mnu_notification_peace_declared", ":kingdom_a", ":kingdom_b"), #stability penalty for early peace is in the menu		
        (call_script, "script_event_kingdom_make_peace_with_kingdom", ":kingdom_a", ":kingdom_b"), #cancels quests
        (call_script, "script_event_kingdom_make_peace_with_kingdom", ":kingdom_b", ":kingdom_a"), #cancels quests
        (assign, "$g_recalculate_ais", 1),				
      (try_end),
	  
	  (try_begin), #add truce
		(store_add, ":truce_slot", ":kingdom_a", slot_faction_truce_days_with_factions_begin),
		(val_sub, ":truce_slot", kingdoms_begin),
	    (faction_set_slot, ":kingdom_b", ":truce_slot", 40),		
		(store_add, ":truce_slot", ":kingdom_b", slot_faction_truce_days_with_factions_begin),
		(val_sub, ":truce_slot", kingdoms_begin),
	    (faction_set_slot, ":kingdom_a", ":truce_slot", 40),
		(store_add, ":slot_war_damage_inflicted_on_b", ":kingdom_b", slot_faction_war_damage_inflicted_on_factions_begin),
		(val_sub, ":slot_war_damage_inflicted_on_b", kingdoms_begin),
		#(faction_get_slot, ":damage_inflicted_by_a", ":kingdom_a", ":slot_war_damage_inflicted_on_b"),
		(faction_set_slot, ":kingdom_a", ":slot_war_damage_inflicted_on_b", 0),		
		(store_add, ":slot_war_damage_inflicted_on_a", ":kingdom_a", slot_faction_war_damage_inflicted_on_factions_begin),
		(val_sub, ":slot_war_damage_inflicted_on_a", kingdoms_begin),
		#(faction_get_slot, ":damage_inflicted_by_b", ":kingdom_b", ":slot_war_damage_inflicted_on_a"),
		(faction_set_slot, ":kingdom_b", ":slot_war_damage_inflicted_on_a", 0),		
	  (try_end),
  ]),

  
  
  ("event_kingdom_make_peace_with_kingdom",
    [
      (store_script_param_1, ":source_kingdom"),
      (store_script_param_2, ":target_kingdom"),
      (try_begin),
        (check_quest_active, "qst_capture_prisoners"),
        (try_begin),
          (eq, "$players_kingdom", ":source_kingdom"),
          (quest_slot_eq, "qst_capture_prisoners", slot_quest_target_faction, ":target_kingdom"),
          (call_script, "script_cancel_quest", "qst_capture_prisoners"),
        (else_try),
          (eq, "$players_kingdom", ":target_kingdom"),
          (quest_slot_eq, "qst_capture_prisoners", slot_quest_target_faction, ":source_kingdom"),
          (call_script, "script_cancel_quest", "qst_capture_prisoners"),
        (try_end),
      (try_end),
	  
      (try_begin),
        (check_quest_active, "qst_capture_enemy_hero"),
        (try_begin),
          (eq, "$players_kingdom", ":source_kingdom"),
          (quest_slot_eq, "qst_capture_enemy_hero", slot_quest_target_faction, ":target_kingdom"),
          (call_script, "script_cancel_quest", "qst_capture_enemy_hero"),
        (else_try),
          (eq, "$players_kingdom", ":target_kingdom"),
          (quest_slot_eq, "qst_capture_enemy_hero", slot_quest_target_faction, ":source_kingdom"),
          (call_script, "script_cancel_quest", "qst_capture_enemy_hero"),
        (try_end),
      (try_end),
	  
	  
	  
      (try_begin),
        (check_quest_active, "qst_persuade_lords_to_make_peace"),
	    (quest_get_slot, ":lord_1", "qst_persuade_lords_to_make_peace", slot_quest_target_troop),
	    (quest_get_slot, ":lord_2", "qst_persuade_lords_to_make_peace", slot_quest_object_troop),
		
		(try_begin),
			(lt, ":lord_1", 0),
			(val_mul, ":lord_1", -1),
		(try_end),
		(try_begin),
			(lt, ":lord_2", 0),
			(val_mul, ":lord_2", -1),
		(try_end),
		
		
	    (store_faction_of_troop, ":lord_1_faction", ":lord_1"),
	    (store_faction_of_troop, ":lord_2_faction", ":lord_2"),	  
	  
	    (this_or_next|eq, ":lord_1_faction", ":source_kingdom"),
			(eq, ":lord_2_faction", ":source_kingdom"),

	    (this_or_next|eq, ":lord_1_faction", ":target_kingdom"),
			(eq, ":lord_2_faction", ":target_kingdom"),

        (call_script, "script_cancel_quest", "qst_persuade_lords_to_make_peace"),
			
	  (try_end),
	  
	  #Rescue prisoners cancelled in simple_triggers
	  
	  (try_begin),
		(this_or_next|faction_slot_eq, ":target_kingdom", slot_faction_leader, "trp_player"),
		(faction_slot_eq, ":source_kingdom", slot_faction_leader, "trp_player"),
	    
		# NE - don't want player receiving right to rule for small peace events as it is easy to attack patrols, then sue for peace. 
		(try_begin), 
		(eq, "$small_peace", 1), 
		(assign, "$small_peace", 0),
		(else_try),
	    (call_script, "script_change_player_right_to_rule", 3),
		(try_end), 
	  (try_end),
	  
  ]),

  # script_randomly_start_war_peace
  # Input: arg1 = initializing_war_peace_cond (1 = true, 0 = false)
  # Output: none
  
  #Aims to introduce a slightly simpler system in which the AI kings' reasoning could be made more  transparent to the player. At the start of the game, this may lead to less variation in outcomes, though
  ("randomly_start_war_peace_new",
    [
    (store_script_param_1, ":initializing_war_peace_cond"),
	
	(assign, ":players_kingdom_at_peace", 0), #if the player kingdom is at peace, then create an enmity
	(try_begin),
		(is_between, "$players_kingdom", "fac_kingdom_1", kingdoms_end),
		(assign, ":players_kingdom_at_peace", 1),
	(try_end),
	
    (try_for_range, ":cur_kingdom", "fac_kingdom_1", kingdoms_end),
	# NE dk
	(neq,":cur_kingdom","fac_dark_knights"),
	# NE end dk
        (faction_slot_eq, ":cur_kingdom", slot_faction_state, sfs_active),
	  
		(try_for_range, ":cur_kingdom_2", kingdoms_begin, kingdoms_end),
			# NE dk
	        (neq,":cur_kingdom_2","fac_dark_knights"),
	        # NE end dk
			(neq, ":cur_kingdom", ":cur_kingdom_2"),
			(faction_slot_eq, ":cur_kingdom_2", slot_faction_state, sfs_active),
		
			(call_script, "script_npc_decision_checklist_peace_or_war", ":cur_kingdom", ":cur_kingdom_2", -1),
			(assign, ":kingdom_1_to_kingdom_2", reg0),
			
			(store_relation, ":cur_relation", ":cur_kingdom", ":cur_kingdom_2"),
			(try_begin),
				(lt, ":cur_relation", 0), #AT WAR
				
				(try_begin),
					(eq, ":cur_kingdom", "$players_kingdom"),
					(assign, ":players_kingdom_at_peace", 0),
				(try_end),
				
				(ge, ":kingdom_1_to_kingdom_2", 1),
								
	            (try_begin),
	                (eq, ":cur_kingdom_2", "fac_player_supporters_faction"),
					
					(store_mul, ":goodwill_level", ":kingdom_1_to_kingdom_2", 2),
					(store_random_in_range, ":random", 0, 20),
					(try_begin),
					(lt, ":random", ":goodwill_level"),
	                (call_script, "script_add_notification_menu", "mnu_question_peace_offer", ":cur_kingdom", 0),
					(try_end),
	            (else_try),
					(call_script, "script_npc_decision_checklist_peace_or_war", ":cur_kingdom_2", ":cur_kingdom", -1),
					(assign, ":kingdom_2_to_kingdom_1", reg0),
					(ge, ":kingdom_2_to_kingdom_1", 1),

					(store_mul, ":goodwill_level", ":kingdom_1_to_kingdom_2", ":kingdom_2_to_kingdom_1"),
					(store_random_in_range, ":random", 0, 20),
					(lt, ":random", ":goodwill_level"),

					(try_begin),
						(eq, "$g_include_diplo_explanation", 0),
						(assign, "$g_include_diplo_explanation", ":cur_kingdom"),
						(str_store_string, s57, "str_s14"),
					(try_end),	

	                (call_script, "script_diplomacy_start_peace_between_kingdoms", ":cur_kingdom", ":cur_kingdom_2", ":initializing_war_peace_cond"),
	            (try_end),
			(else_try),
				(ge, ":cur_relation", 0), #AT PEACE
			
			    (call_script, "script_npc_decision_checklist_peace_or_war", ":cur_kingdom", ":cur_kingdom_2", -1),
				
				#negative, leans towards war/positive, leans towards peace
				(le, reg0, 0), #still no chance of war unless provocation, or at start of game
			 
			    (assign, ":hostility", reg0),

			    (call_script, "script_diplomacy_faction_get_diplomatic_status_with_faction", ":cur_kingdom", ":cur_kingdom_2"),
			    (le, reg0, 0), #no truce

				(val_add, ":hostility", reg0), #increase hostility if there is a provocation

				(val_sub, ":hostility", 1), #greater chance at start of game
				(val_add, ":hostility", ":initializing_war_peace_cond"), #this variable = 1 after the start
				
				(store_mul, ":hostility_squared", ":hostility", ":hostility"),
				(store_random_in_range, ":random", 0, 50),
			    (lt, ":random", ":hostility_squared"),
				
				(try_begin),
					(eq, "$g_include_diplo_explanation", 0),
					(assign, "$g_include_diplo_explanation", ":cur_kingdom"),
					(str_store_string, s57, "str_s14"),
				(try_end),	
				
					# NE kingdom
				(assign, ":continue", 1),
				
                (try_begin), ## If the player's faction is chosen, insert a chance to avoid by giving a town - Jinnai
                (eq, ":cur_kingdom", "fac_player_supporters_faction"),
                (faction_slot_eq,"fac_player_supporters_faction",slot_faction_leader,"trp_player"),
                (faction_get_slot, ":cur_king", ":cur_kingdom_2", slot_faction_leader),
                (call_script, "script_troop_get_player_relation", ":cur_king"),
                (ge,reg0,-20), #If the monarch hates the player, they're not going to bother threatening
                (assign,":centers",0),
					(try_for_range,":center_no",towns_begin,towns_end),
					(store_faction_of_party, ":faction", ":center_no"),
					(eq,":faction","fac_player_supporters_faction"),
					(party_slot_eq, ":center_no", slot_center_is_besieged_by, -1),
					(val_add,":centers",1),
					(try_end),
                (val_add,":centers",1),
                (store_random_in_range,":rand",1,":centers"),
                (assign,":centers",0),
                (assign,":town",-1),
					(try_for_range,":center_no",towns_begin,towns_end),
					(store_faction_of_party, ":faction", ":center_no"),
					(eq,":faction","fac_player_supporters_faction"),
					(party_slot_eq, ":center_no", slot_center_is_besieged_by, -1),
					(val_add,":centers",1),
					(eq,":centers",":rand"),
					(assign,":town",":center_no"),
					(try_end),
                (ge,":town",0), # Can only threaten if the player has a town to threaten for.  Otherwise just declare war
                (call_script, "script_add_notification_menu", "mnu_threaten_war", ":cur_kingdom_2", ":town"),
                (assign,":continue",0),
              (else_try),
                (eq, ":cur_kingdom_2", "fac_player_supporters_faction"),
                (faction_slot_eq,"fac_player_supporters_faction",slot_faction_leader,"trp_player"),
                (faction_get_slot, ":cur_king", ":cur_kingdom", slot_faction_leader),
                (call_script, "script_troop_get_player_relation", ":cur_king"),
                (ge,reg0,-20),
                (assign,":centers",0),
					(try_for_range,":center_no",towns_begin,towns_end),
					(store_faction_of_party, ":faction", ":center_no"),
					(eq,":faction","fac_player_supporters_faction"),
					(party_slot_eq, ":center_no", slot_center_is_besieged_by, -1),
					(val_add,":centers",1),
					(try_end),
                (val_add,":centers",1),
                (store_random_in_range,":rand",1,":centers"),
                (assign,":centers",0),
                (assign,":town",-1),
					(try_for_range,":center_no",towns_begin,towns_end),
					(store_faction_of_party, ":faction", ":center_no"),
					(eq,":faction","fac_player_supporters_faction"),
					(party_slot_eq, ":center_no", slot_center_is_besieged_by, -1),
					(val_add,":centers",1),
					(eq,":centers",":rand"),
					(assign,":town",":center_no"),
					(try_end),
                (ge,":town",0),
                (call_script, "script_add_notification_menu", "mnu_threaten_war", ":cur_kingdom", ":town"),
                (assign,":continue",0),
              (try_end),


                (eq, ":continue", 1),			
					# NE end kingdom				
				
                (call_script, "script_diplomacy_start_war_between_kingdoms", ":cur_kingdom", ":cur_kingdom_2", ":initializing_war_peace_cond"),
				
				(try_begin), #do some war damage for 
					(eq, ":initializing_war_peace_cond", 0),
					(store_random_in_range, ":war_damage_inflicted", 10, 120),			
					(store_add, ":slot_war_damage_inflicted", ":cur_kingdom", slot_faction_war_damage_inflicted_on_factions_begin),
					(val_sub, ":slot_war_damage_inflicted", kingdoms_begin),
					(faction_set_slot, ":cur_kingdom_2",  ":slot_war_damage_inflicted", ":war_damage_inflicted"),
			
					(store_add, ":slot_war_damage_inflicted", ":cur_kingdom_2", slot_faction_war_damage_inflicted_on_factions_begin),
					(val_sub, ":slot_war_damage_inflicted", kingdoms_begin),
					(faction_set_slot, ":cur_kingdom", ":slot_war_damage_inflicted", ":war_damage_inflicted"),
				(try_end),
            (try_end),
		(try_end),
	(try_end),	
	
	(try_begin),
		(eq, ":players_kingdom_at_peace", 1),
		(val_add, "$players_kingdom_days_at_peace", 1),
		(try_begin),
			(eq, "$cheat_mode", 1),
			(assign, reg3, "$players_kingdom_days_at_peace"),
			(display_message, "@{!}DEBUG -- Player's kingdom has had {reg3} days of peace"),
		(try_end),
	(else_try),	
		(assign, "$players_kingdom_days_at_peace", 0),
	(try_end),
	
     ]),
	 
	 
  # script_randomly_start_war_peace
  # Input: arg1 = initializing_war_peace_cond (1 = true, 0 = false)
  # Output: none
#  ("randomly_start_war_peace",
#    [
#      (store_script_param_1, ":initializing_war_peace_cond"),
#      (assign, ":total_resources", 0),
#      (assign, ":total_active_kingdoms", 0),
#      (try_for_range, ":cur_kingdom", kingdoms_begin, kingdoms_end),
#        (faction_slot_eq, ":cur_kingdom", slot_faction_state, sfs_active),
#        (val_add, ":total_active_kingdoms", 1),
#        (faction_get_slot, ":num_towns", ":cur_kingdom", slot_faction_num_towns),
#        (store_mul, ":kingdom_resources_value", ":num_towns", 2),
#        (faction_get_slot, ":num_castles", ":cur_kingdom", slot_faction_num_castles),
#        (val_add, ":kingdom_resources_value", ":num_castles"),
#        (val_mul, ":kingdom_resources_value", 10),
#        (val_max, ":kingdom_resources_value", 1),
#        (val_mul, ":kingdom_resources_value", 1000),
#        (faction_get_slot, ":num_armies", ":cur_kingdom", slot_faction_num_armies),
#        (val_max, ":num_armies", 1),
#        (val_div, ":kingdom_resources_value", ":num_armies"),
#        (val_add, ":total_resources", ":kingdom_resources_value"),
#      (try_end),
#      (val_max, ":total_active_kingdoms", 1),
#      (store_div, ":average_resources", ":total_resources", ":total_active_kingdoms"),

#      (try_for_range, ":cur_kingdom", kingdoms_begin, kingdoms_end),
 ##       (neq, ":cur_kingdom", "fac_player_supporters_faction"),
#        (faction_slot_eq, ":cur_kingdom", slot_faction_state, sfs_active),
#        (assign, ":num_ongoing_wars", 0),
#        (try_for_range, ":other_kingdom", kingdoms_begin, kingdoms_end),
#          (faction_slot_eq, ":other_kingdom", slot_faction_state, sfs_active),
#          (store_relation, ":other_relation", ":cur_kingdom", ":other_kingdom"),
#          (lt, ":other_relation", 0),
#          (val_add, ":num_ongoing_wars", 1),
#        (try_end),

#        (faction_get_slot, ":num_towns", ":cur_kingdom", slot_faction_num_towns),
#        (store_mul, ":kingdom_1_resources_value", ":num_towns", 2),
#        (faction_get_slot, ":num_castles", ":cur_kingdom", slot_faction_num_castles),
#        (val_add, ":kingdom_1_resources_value", ":num_castles"),
#        (val_mul, ":kingdom_1_resources_value", 10),
#        (val_max, ":kingdom_1_resources_value", 1),
#        (val_mul, ":kingdom_1_resources_value", 1000),
#        (faction_get_slot, ":num_armies", ":cur_kingdom", slot_faction_num_armies),
#        (val_max, ":num_armies", 1),
#        (val_div, ":kingdom_1_resources_value", ":num_armies"),

#        (store_add, ":start_cond", ":cur_kingdom", 1),
#        (try_for_range, ":cur_kingdom_2", ":start_cond", kingdoms_end),
 ##         (neq, ":cur_kingdom", "fac_player_supporters_faction"),
#          (faction_slot_eq, ":cur_kingdom_2", slot_faction_state, sfs_active),

#          (assign, ":num_ongoing_wars_2", 0),
#          (try_for_range, ":other_kingdom", kingdoms_begin, kingdoms_end),
#            (faction_slot_eq, ":other_kingdom", slot_faction_state, sfs_active),
#            (store_relation, ":other_relation", ":cur_kingdom_2", ":other_kingdom"),
#            (lt, ":other_relation", 0),
#            (val_add, ":num_ongoing_wars_2", 1),
#          (try_end),

#          (store_add, ":total_ongoing_wars", ":num_ongoing_wars", ":num_ongoing_wars_2"),

#          (faction_get_slot, ":num_towns", ":cur_kingdom_2", slot_faction_num_towns),
#          (store_mul, ":kingdom_2_resources_value", ":num_towns", 2),
#          (faction_get_slot, ":num_castles", ":cur_kingdom_2", slot_faction_num_castles),
#          (val_add, ":kingdom_2_resources_value", ":num_castles"),
#          (val_mul, ":kingdom_2_resources_value", 10),
#          (val_max, ":kingdom_2_resources_value", 1),
#          (val_mul, ":kingdom_2_resources_value", 1000),
#          (faction_get_slot, ":num_armies", ":cur_kingdom_2", slot_faction_num_armies),
#          (val_max, ":num_armies", 1),
#          (val_div, ":kingdom_2_resources_value", ":num_armies"),

#          (assign, ":max_resources_value", ":kingdom_1_resources_value"),
#          (val_max, ":max_resources_value", ":kingdom_2_resources_value"),
#          (val_mul, ":max_resources_value", 100),
#          (val_div, ":max_resources_value", ":average_resources"),

#          (assign, ":cur_king", -1),
#          (try_begin),
#            (eq, ":cur_kingdom", "fac_player_supporters_faction"),
#            (faction_get_slot, ":cur_king", ":cur_kingdom_2", slot_faction_leader),
#            (assign, ":cur_relation", reg0),
#            (store_sub, ":relation_effect", 200, ":cur_relation"),
#            (val_mul, ":kingdom_1_resources_value", ":relation_effect"),
#            (val_div, ":kingdom_1_resources_value", 200),
#          (else_try),
#            (eq, ":cur_kingdom_2", "fac_player_supporters_faction"),
#            (faction_get_slot, ":cur_king", ":cur_kingdom", slot_faction_leader),
#          (try_end),

#          (try_begin),
#            (ge, ":cur_king", 0),
#            (call_script, "script_troop_get_player_relation", ":cur_king"),
#            (assign, ":cur_relation", reg0),
#            (store_sub, ":relation_effect", 200, ":cur_relation"),
#            (val_mul, ":max_resources_value", ":relation_effect"),
#            (val_div, ":max_resources_value", 200),
#          (try_end),

          #max_resources_value is the obtained value that gives us how tempting the kingdom's values are
          #average is 100
 #         (val_clamp, ":max_resources_value", 20, 500),
          #not letting more than 5 times higher chance of declaring war or peace

  #        (store_random_in_range, ":random_no", 0, 10000),
 #         (store_relation, ":cur_relation", ":cur_kingdom", ":cur_kingdom_2"),
 #         (try_begin),
 #           (lt, ":cur_relation", 0), #AT WAR
 #           (store_mul, ":chance_to_make_peace", ":total_ongoing_wars", 50),
 #           (val_mul, ":chance_to_make_peace", 100),
 #           (val_div, ":chance_to_make_peace", ":max_resources_value"),
 #           (try_begin),
              #disable random peace for special conditions
 #             (this_or_next|eq, ":cur_kingdom", "fac_player_supporters_faction"),
 #             (eq, ":cur_kingdom_2", "fac_player_supporters_faction"),
 #             (assign, ":continue", 0),
          #    (try_begin),
           #     (gt, "$supported_pretender", 0),
            #    (this_or_next|eq, ":cur_kingdom", "$supported_pretender_old_faction"),
           #     (eq, ":cur_kingdom_2", "$supported_pretender_old_faction"),
          #      (assign, ":continue", 1),
         #     (else_try),
       #         (is_between, "$players_oath_renounced_against_kingdom", kingdoms_begin, kingdoms_end),
      #          (this_or_next|eq, ":cur_kingdom", "$players_oath_renounced_against_kingdom"),
     #           (eq, ":cur_kingdom_2", "$players_oath_renounced_against_kingdom"),
    #            (assign, ":continue", 1),
   #           (try_end),
         #     (eq, ":continue", 1),
        #      (assign, ":chance_to_make_peace", 0),
       #     (try_end),
      #      (try_begin),
     #         (lt, ":random_no", ":chance_to_make_peace"),
    #          (assign, ":continue", 1),
   #           (try_begin),
  #              (check_quest_active, "qst_persuade_lords_to_make_peace"),
              #  (quest_get_slot, ":quest_target_faction", "qst_persuade_lords_to_make_peace", slot_quest_target_faction),
             #   (quest_get_slot, ":quest_object_faction", "qst_persuade_lords_to_make_peace", slot_quest_object_faction),
            #    (this_or_next|eq, ":cur_kingdom", ":quest_target_faction"),
           #     (eq, ":cur_kingdom", ":quest_object_faction"),
          #      (this_or_next|eq, ":cur_kingdom_2", ":quest_target_faction"),
         #       (eq, ":cur_kingdom_2", ":quest_object_faction"),
        #        (assign, ":continue", 0), #Do not declare war if the quest is active for the specific kingdoms
       #       (try_end),
      #        (eq, ":continue", 1),
     #         (try_begin),
    #            (eq, ":cur_kingdom", "fac_player_supporters_faction"),
   #             (call_script, "script_add_notification_menu", "mnu_question_peace_offer", ":cur_kingdom_2", 0),
  #            (else_try),
            #    (eq, ":cur_kingdom_2", "fac_player_supporters_faction"),
           #     (call_script, "script_add_notification_menu", "mnu_question_peace_offer", ":cur_kingdom", 0),
          #    (else_try),
         #       (call_script, "script_diplomacy_start_peace_between_kingdoms", ":cur_kingdom", ":cur_kingdom_2", ":initializing_war_peace_cond"),
        #      (try_end),
       #     (try_end),
      #    (else_try), # AT PEACE
     #       (assign, ":chance_to_declare_war", 6),
    #        (val_sub, ":chance_to_declare_war", ":total_ongoing_wars"),
   #         (val_mul, ":chance_to_declare_war", 50),
          #  (val_mul, ":chance_to_declare_war", ":max_resources_value"),
         #   (val_div, ":chance_to_declare_war", 100),
        #    (try_begin),
       #       (lt, ":random_no", ":chance_to_declare_war"),
      #        (assign, ":continue", 1),
     #         (try_begin),
    #            (check_quest_active, "qst_raid_caravan_to_start_war"),
               # (quest_get_slot, ":quest_target_faction", "qst_raid_caravan_to_start_war", slot_quest_target_faction),
              #  (quest_get_slot, ":quest_object_faction", "qst_raid_caravan_to_start_war", slot_quest_object_faction),
             #   (this_or_next|eq, ":cur_kingdom", ":quest_target_faction"),
            #    (eq, ":cur_kingdom", ":quest_object_faction"),
           #     (this_or_next|eq, ":cur_kingdom_2", ":quest_target_faction"),
          #      (eq, ":cur_kingdom_2", ":quest_object_faction"),
         #       (assign, ":continue", 0), #Do not declare war if the quest is active for the specific kingdoms
        #      (try_end),
       #       (eq, ":continue", 1),
      #        (call_script, "script_diplomacy_start_war_between_kingdoms", ":cur_kingdom", ":cur_kingdom_2", ":initializing_war_peace_cond"),
     #       (try_end),
    #      (try_end),
   #     (try_end),
  #    (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"),
       (assign, ":faction_no_3", -1),
       (assign, ":faction_no_4", -1),
       (assign, ":free_companions_too", 0),
       (try_begin),
         (this_or_next|eq, "$players_kingdom", ":faction_no_1"),
         (eq, "$players_kingdom", ":faction_no_2"),
         (assign, ":faction_no_3", "fac_player_faction"),
         (assign, ":faction_no_4", "fac_player_supporters_faction"),
         (assign, ":free_companions_too", 1),
       (try_end),
	   
       (try_for_parties, ":party_no"),
         (store_faction_of_party, ":party_faction", ":party_no"),
         (this_or_next|eq, ":party_faction", ":faction_no_1"),
         (this_or_next|eq, ":party_faction", ":faction_no_2"),
         (this_or_next|eq, ":party_faction", ":faction_no_3"),
         (eq, ":party_faction", ":faction_no_4"),
         (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"),                                                                             
           
           (assign, ":continue", 0),
           (try_begin),
             (is_between, ":cur_troop_id", companions_begin, companions_end),
             (eq, ":free_companions_too", 1),
             (assign, ":continue", 1),
           (else_try),                        
             (neg|is_between, ":cur_troop_id", companions_begin, companions_end),             
             (store_troop_faction, ":cur_faction", ":cur_troop_id"),
             (this_or_next|eq, ":cur_faction", ":faction_no_1"),
             (this_or_next|eq, ":cur_faction", ":faction_no_2"),
             (this_or_next|eq, ":cur_faction", ":faction_no_3"),
             (eq, ":cur_faction", ":faction_no_4"),
             (assign, ":continue", 1),
           (try_end),                        
           (eq, ":continue", 1),
           
           (try_begin),
             (troop_is_hero, ":cur_troop_id"),
             (call_script, "script_remove_troop_from_prison", ":cur_troop_id"),
           (try_end),
           (party_prisoner_stack_get_size, ":stack_size", ":party_no", ":troop_iterator"),
           (party_remove_prisoners, ":party_no", ":cur_troop_id", ":stack_size"),
         (try_end),
       (try_end),
	   
    ]),

  # script_add_notification_menu
  # Input: arg1 = menu_no, arg2 = menu_var_1, arg3 = menu_var_2
  # Output: none
  ("add_notification_menu",
    [
      (try_begin),        
        (eq, "$g_infinite_camping", 0),
        (store_script_param, ":menu_no", 1),
        (store_script_param, ":menu_var_1", 2),
        (store_script_param, ":menu_var_2", 3),
        (assign, ":end_cond", 1),      
        (try_for_range, ":cur_slot", 0, ":end_cond"),
          (try_begin),
            (troop_slot_ge, "trp_notification_menu_types", ":cur_slot", 1),
            (val_add, ":end_cond", 1),
          (else_try),
            (troop_set_slot, "trp_notification_menu_types", ":cur_slot", ":menu_no"),
            (troop_set_slot, "trp_notification_menu_var1", ":cur_slot", ":menu_var_1"),
            (troop_set_slot, "trp_notification_menu_var2", ":cur_slot", ":menu_var_2"),
          (try_end),
        (try_end),
      (try_end),
      ]),
  
  # 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"),
      (call_script, "script_troop_add_gold", "trp_player", ":quest_gold_reward"),
	  # NE finances
	  (call_script, "script_adjust_finances", slot_finance_quest_rewards, ":quest_gold_reward"),
	  # NE end finances
      (call_script, "script_end_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, s2, ":troop_no"),

      (troop_set_slot, ":troop_no", slot_troop_location_status, tls_unknown),
      (store_current_hours, ":hours"), 
      (troop_set_slot, ":troop_no", slot_troop_location_hours, ":hours"),

      (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}."),
        (troop_set_slot, ":troop_no", slot_troop_location_center, ":center_no"),
        (troop_set_slot, ":troop_no", slot_troop_location_status, tls_garrisoned),
        (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}."),
          (troop_set_slot, ":troop_no", slot_troop_location_center, ":center_no"),
          (troop_set_slot, ":troop_no", slot_troop_location_status, tls_garrisoned),
          (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}."),
          (troop_set_slot, ":troop_no", slot_troop_location_center, reg0),
          (troop_set_slot, ":troop_no", slot_troop_location_status, tls_nearby),
          (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 the field and {reg4?she:he} {reg3?was:should be} close to {s3}{reg3?: at the moment}."),
          (troop_set_slot, ":troop_no", slot_troop_location_center, reg0),
          (troop_set_slot, ":troop_no", slot_troop_location_status, tls_nearby),
          (assign, ":found", 1),
        (try_end),
      (else_try),
        #(troop_slot_ge, ":troop_no", slot_troop_is_prisoner, 1),
        (troop_slot_ge, ":troop_no", slot_troop_prisoner_of_party, 0),
        (try_for_range, ":center_no", walled_centers_begin, walled_centers_end),
          (party_count_prisoners_of_type, ":num_prisoners", ":center_no", ":troop_no"),
          (gt, ":num_prisoners", 0),
          (assign, ":found", 1),
          (str_store_party_name_link, s3, ":center_no"),
          (str_store_string, s1, "@{s2} {reg3?was:is} being held captive at {s3}."),
          (troop_set_slot, ":troop_no", slot_troop_location_center, ":center_no"),
          (troop_set_slot, ":troop_no", slot_troop_location_status, tls_imprisoned),
        (try_end),
        (try_begin),
          (eq, ":found", 0),
          (str_store_string, s1, "@{s2} {reg3?was:has been} taken captive by {reg4?her:his} enemies."),
          (troop_set_slot, ":troop_no", slot_troop_location_center, 0),
          (troop_set_slot, ":troop_no", slot_troop_location_status, tls_imprisoned),
          (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_slot, ":troop_no", slot_troop_cur_center, -1),
      (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."),
	  (troop_set_note_available, ":troop_no", 1),	
	  
	  (try_begin),  
	    (is_between, ":troop_no", companions_begin, companions_end),
	    (store_sub, ":companion_number", ":troop_no", companions_begin),
	    	    
	    (set_achievement_stat, ACHIEVEMENT_KNIGHTS_OF_THE_ROUND, ":companion_number", 1),
	    
	    (assign, ":number_of_companions_hired", 0),
	    (try_for_range, ":cur_companion", 0, 16),	      
	      (get_achievement_stat, ":is_hired", ACHIEVEMENT_KNIGHTS_OF_THE_ROUND, ":cur_companion"),
	      (eq, ":is_hired", 1),
	      (val_add, ":number_of_companions_hired", 1),
	    (try_end),
	    
	    (try_begin),
	      (ge, ":number_of_companions_hired", 6),
	      (unlock_achievement, ACHIEVEMENT_KNIGHTS_OF_THE_ROUND),
	    (try_end),
	  (try_end),
  ]),
  

  # 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"),
      (else_try),
        (eq, ":terrain_type", rt_plain),
        (assign, ":scene_to_use", "scn_random_scene_plain"),
      (else_try),
        (eq, ":terrain_type", rt_snow),
        (assign, ":scene_to_use", "scn_random_scene_snow"),
      (else_try),
        (eq, ":terrain_type", rt_desert),
        (assign, ":scene_to_use", "scn_random_scene_desert"),
      (else_try),
        (eq, ":terrain_type", rt_steppe_forest),
        (assign, ":scene_to_use", "scn_random_scene_steppe_forest"),
      (else_try),
        (eq, ":terrain_type", rt_forest),
        (assign, ":scene_to_use", "scn_random_scene_plain_forest"),
      (else_try),
        (eq, ":terrain_type", rt_snow_forest),
        (assign, ":scene_to_use", "scn_random_scene_snow_forest"),
      (else_try),
        (eq, ":terrain_type", rt_desert_forest),
        (assign, ":scene_to_use", "scn_random_scene_desert_forest"),
      (else_try),
        (eq, ":terrain_type", rt_water),
        (assign, ":scene_to_use", "scn_water"),
      (else_try),
        (eq, ":terrain_type", rt_bridge),
        (assign, ":scene_to_use", "scn_random_scene_plain"),
      (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"),
      #new added...
      (mission_tpl_entry_set_override_flags, ":mission_template_no", 0, af_override_horse),
      (try_begin),
        (eq, "$sneaked_into_town", 1),
        (mission_tpl_entry_set_override_flags, ":mission_template_no", 0, af_override_all),                
        
        (mission_tpl_entry_clear_override_items, ":mission_template_no", 0),
        (mission_tpl_entry_add_override_item, ":mission_template_no", 0, "itm_pilgrim_hood"),
        (mission_tpl_entry_add_override_item, ":mission_template_no", 0, "itm_pilgrim_disguise"),
        (mission_tpl_entry_add_override_item, ":mission_template_no", 0, "itm_practice_staff"),
        (mission_tpl_entry_add_override_item, ":mission_template_no", 0, "itm_throwing_daggers"),
      (try_end),   
      #new added end              

      (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"),

		(assign, ":prisoner_offered_parole", 0),
		(try_begin),
			(party_slot_eq, ":center_no", slot_town_lord, "trp_player"),
		(else_try),
			(call_script, "script_cf_prisoner_offered_parole", ":stack_troop"),
			(assign, ":prisoner_offered_parole", 1),
		(else_try),
			(assign, ":prisoner_offered_parole", 0),
		(try_end),
		(eq, ":prisoner_offered_parole", 0),
		
        (lt, ":cur_pos", 32), # spawn up to entry point 32
        (set_visitor, ":cur_pos", ":stack_troop"),
        (val_add,":cur_pos", 1),
      (try_end),
      	 
#	  (set_visitor, ":cur_pos", "trp_npc3"),
#	  (troop_set_slot, "trp_npc3", slot_troop_prisoner_of_party, "$g_encountered_party"),	  
	  
      (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
  #other search term: setup_court
  ("enter_court",
    [
      (store_script_param_1, ":center_no"),
      
      (assign, "$talk_context", tc_court_talk),

      (set_jump_mission,"mt_visit_town_castle"),
         
      (mission_tpl_entry_clear_override_items, "mt_visit_town_castle", 0),
      #(mission_tpl_entry_set_override_flags, "mt_visit_town_castle", 0, af_override_all),
      
      (party_get_slot, ":castle_scene", ":center_no", slot_town_castle),
      (modify_visitors_at_site,":castle_scene"),
      (reset_visitors),
      #Adding guards
      (store_faction_of_party, ":center_faction", ":center_no"),
      (faction_get_slot, ":guard_troop", ":center_faction", slot_faction_guard_troop),
      (try_begin),
        (le, ":guard_troop", 0),
        (assign, ":guard_troop", "trp_swadian_sergeant"),
      (try_end),
      (set_visitor, 6, ":guard_troop"),
      (set_visitor, 7, ":guard_troop"),

      (assign, ":cur_pos", 16),

	  (try_begin),
		(troop_get_slot, ":player_spouse", "trp_player", slot_troop_spouse),
	    (gt, ":player_spouse", 0),
		(troop_slot_eq, ":player_spouse", slot_troop_cur_center, ":center_no"),
        (set_visitor, ":cur_pos", ":player_spouse"),
        (val_add,":cur_pos", 1),
	  (else_try),	
		(troop_get_slot, ":player_betrothed", "trp_player", slot_troop_betrothed),
	    (gt, ":player_betrothed", 0),
		(troop_slot_eq, ":player_betrothed", slot_troop_cur_center, ":center_no"),
        (set_visitor, ":cur_pos", ":player_betrothed"),
        (val_add,":cur_pos", 1),
	  (try_end),
	  
	  (try_begin),
		(eq, "$g_player_court", ":center_no"),
		(gt, "$g_player_minister", 0),
		(neg|troop_slot_eq, "trp_player", slot_troop_spouse, "$g_player_minister"),
        (set_visitor, ":cur_pos", "$g_player_minister"),
        (val_add,":cur_pos", 1),
	  (try_end),	  
	  
	  # NE kingdom
#Add advisors if at the player's capital - Jinnai
      (try_begin),
        (party_slot_eq, "$current_town", slot_town_lord, "trp_player"),
        (faction_slot_eq,"fac_player_supporters_faction",slot_faction_capital,"$g_encountered_party"),
        (try_begin),
          (faction_slot_eq,"fac_player_supporters_faction",slot_faction_financial_adviser,1),
          (set_visitor, ":cur_pos", "trp_financial_adviser"),
          (val_add,":cur_pos", 1),
        (try_end),
        (try_begin),
          (faction_slot_eq,"fac_player_supporters_faction",slot_faction_civil_adviser,1),
          (set_visitor, ":cur_pos", "trp_civil_adviser"),
          (val_add,":cur_pos", 1),
        (try_end),
        (try_begin),
          (faction_slot_eq,"fac_player_supporters_faction",slot_faction_logistics_adviser,1),
          (set_visitor, ":cur_pos", "trp_logistics_adviser"),
          (val_add,":cur_pos", 1),
        (try_end),
        (try_begin),
          (faction_slot_eq,"fac_player_supporters_faction",slot_faction_intel_adviser,1),
          (set_visitor, ":cur_pos", "trp_intel_adviser"),
          (val_add,":cur_pos", 1),
        (try_end),
      (try_end),
	  # NE end kingdom
	  
	  
	  
	  #Lords wishing to pledge allegiance - inactive, but part of player faction
	  (try_begin),
		(eq, "$g_player_court", ":center_no"),
	    (faction_slot_eq, ":center_faction", slot_faction_leader, "trp_player"),
	    (try_for_range, ":active_npc", active_npcs_begin, active_npcs_end),
	      (store_faction_of_troop, ":active_npc_faction", ":active_npc"),
	      (eq, ":active_npc_faction", "fac_player_supporters_faction"),
	      (troop_slot_eq, ":active_npc", slot_troop_occupation, slto_inactive),
	      (neg|troop_slot_ge, ":active_npc", slot_troop_prisoner_of_party, 0), #if he/she is not prisoner in any center.
	      (neq, ":active_npc", "$g_player_minister"),
	      (set_visitor, ":cur_pos", ":active_npc"),	      
	      (val_add,":cur_pos", 1),
		(try_end),
	  (try_end),	  
	  
      (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 - is it possible to add another 10 spots?
        (set_visitor, ":cur_pos", ":stack_troop"),
        (val_add,":cur_pos", 1),
      (try_end),
      (try_for_range, ":cur_troop", kingdom_ladies_begin, kingdom_ladies_end),
	    (neq, ":cur_troop", "trp_knight_1_1_wife"), #The one who should not appear in game
        #(troop_slot_eq, ":cur_troop", slot_troop_occupation, slto_kingdom_lady),
        (troop_slot_eq, ":cur_troop", slot_troop_cur_center, ":center_no"),
		
		(assign, ":lady_meets_visitors", 0),
		(try_begin),
			(this_or_next|troop_slot_eq, "trp_player", slot_troop_spouse, ":cur_troop"), #player spouse goes in position of honor
			(this_or_next|troop_slot_eq, "trp_player", slot_troop_betrothed, ":cur_troop"), #player spouse goes in position of honor
			(this_or_next|troop_slot_eq, ":cur_troop", slot_troop_spouse, "trp_player"), #player spouse goes in position of honor
				(troop_slot_eq, ":cur_troop", slot_troop_betrothed, "trp_player"),
				
			(assign, ":lady_meets_visitors", 0), #She is already in the place of honor
		
			(try_begin),
				(eq, "$cheat_mode", 1),
				(str_store_troop_name, s4, ":cur_troop"),
				(display_message, "str_s4_is_present_at_the_center_and_in_place_of_honor"),
			(try_end),
		
		(else_try), #lady is troop
			(store_faction_of_troop, ":lady_faction", ":cur_troop"),
			(neq, ":lady_faction", ":center_faction"),
			
			(assign, ":lady_meets_visitors", 1),
			
			
			(try_begin),
				(eq, "$cheat_mode", 1),
				(str_store_troop_name, s4, ":cur_troop"),
				(display_message, "str_s4_is_present_at_the_center_as_a_refugee"),
			(try_end),
# NE lady is target of love letter quest 
		(else_try),
            (check_quest_active,"qst_deliver_love_letter"),
            (quest_get_slot, ":quest_target_troop", "qst_deliver_love_letter", slot_quest_target_troop),
            (eq,":cur_troop",":quest_target_troop"),
            (assign, ":lady_meets_visitors", 1),
				(try_begin),
					(eq, "$cheat_mode", 1),
					(str_store_troop_name, s4, ":cur_troop"),
					(display_message, "str_s4_is_present_at_the_center_and_not_attending_the_feast"),
				(try_end),	
# end 
		(else_try),
			(troop_slot_ge, ":cur_troop", slot_troop_spouse, 1),
			
			(try_begin),
			 #married ladies at a feast will not mingle - this is ahistorical, as married women and widows probably had much more freedom than unmarried ones, at least in the West, but the game needs to leave slots for them to show off their unmarried daughters
				(faction_slot_eq, ":center_faction", slot_faction_ai_state, sfai_feast),
				(faction_slot_eq, ":center_faction", slot_faction_ai_object, ":center_no"),
				(assign, ":lady_meets_visitors", 0),
				
				(try_begin),
					(eq, "$cheat_mode", 1),
					(str_store_troop_name, s4, ":cur_troop"),
					(display_message, "str_s4_is_present_at_the_center_and_not_attending_the_feast"),
				(try_end),				
			(else_try),
				(assign, ":lady_meets_visitors", 1),
				
				(try_begin),
					(eq, "$cheat_mode", 1),
					(str_store_troop_name, s4, ":cur_troop"),
					(display_message, "str_s4_is_present_at_the_center_and_is_married"),
				(try_end),				
			(try_end),
			
		(else_try), #feast is in progress			
			(faction_slot_eq, ":center_faction", slot_faction_ai_state, sfai_feast),
			(faction_slot_eq, ":center_faction", slot_faction_ai_object, ":center_no"),
			(assign, ":lady_meets_visitors", 1),
			
			(try_begin),
				(eq, "$cheat_mode", 1),
				(str_store_troop_name, s4, ":cur_troop"),
				(display_message, "@{!}DEBUG -- {s4} is present at the center and is attending the feast"),
			(try_end),
						
		(else_try), #already met - awaits in private
			(troop_slot_ge, ":cur_troop", slot_troop_met, 2),
			(assign, ":lady_meets_visitors", 0),
			
			(try_begin),
				(eq, "$cheat_mode", 1),
				(str_store_troop_name, s4, ":cur_troop"),
				(display_message, "@{!}DEBUG -- {s4} is present at the center and is awaiting the player in private"),
			(try_end),
			
		(else_try),	
			(call_script, "script_get_kingdom_lady_social_determinants", ":cur_troop"),
			(call_script, "script_npc_decision_checklist_male_guardian_assess_suitor", reg0, "trp_player"),
			(gt, reg0, 0),
			(assign, ":lady_meets_visitors", 1),
			
			(try_begin),
				(eq, "$cheat_mode", 1),
				(str_store_troop_name, s4, ":cur_troop"),
				(display_message, "@{!}DEBUG -- {s4} is_present_at_the_center_and_is_allowed_to_meet_the_player"),
			(try_end),
			
		(else_try),	
			(try_begin),
				(eq, "$cheat_mode", 1),
				(str_store_troop_name, s4, ":cur_troop"),
				(display_message, "@{!}DEBUG -- {s4}is_present_at_the_center_and_is_not_allowed_to_meet_the_player"),
			(try_end),
		
		(try_end),				

		(eq, ":lady_meets_visitors", 1),
		
        (lt, ":cur_pos", 32), # spawn up to entry point 32
        (set_visitor, ":cur_pos", ":cur_troop"),
        (val_add,":cur_pos", 1),
      (try_end),
      
      (set_jump_entry, 0),
      
      (jump_to_scene,":castle_scene"),
      (scene_set_slot, ":castle_scene", slot_scene_visited, 1),
      (change_screen_mission),
  ]),


   ("setup_meet_lady",
    [
      (store_script_param_1, ":lady_no"), 
      (store_script_param_2, ":center_no"), 
    
      #(mission_tpl_entry_set_override_flags, "mt_visit_town_castle", 0, af_override_horse),
      (troop_set_slot, ":lady_no", slot_lady_last_suitor, "trp_player"),
	  
      (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),

	  (troop_set_age, "trp_nurse_for_lady", 100),
      (set_visitor, 7, "trp_nurse_for_lady"),

      (assign, ":cur_pos", 16),
	  (set_visitor, ":cur_pos", ":lady_no"),

      (assign, "$talk_context", tc_garden),
	  
      (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: team_no
  #        arg2: 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, ":team_no", 1),
      (store_script_param, ":search_radius", 2),
      (val_mul, ":search_radius", 100),
      (get_scene_boundaries, pos10,pos11),
      (team_get_leader, ":ai_leader", ":team_no"),
      (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),
      #do not find positions close to borders (20 m)
      (val_add, ":scene_min_x", 2000),
      (val_sub, ":scene_max_x", 2000),
      (val_add, ":scene_min_y", 2000),
      (val_sub, ":scene_max_y", 2000),
      (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_team_1_battle_tactic", 0),
      (get_player_agent_no, ":player_agent"),
      (agent_get_team, ":player_team", ":player_agent"),
      (try_begin),
        (num_active_teams_le, 2),
        (try_begin),
          (eq, ":player_team", 0),
          (assign, "$ai_team_1", 1),
        (else_try),
          (assign, "$ai_team_1", 0),
        (try_end),
        (assign, "$ai_team_2", -1),
      (else_try),
        (try_begin),
          (eq, ":player_team", 0),
          (assign, "$ai_team_1", 1),
        (else_try),
          (assign, "$ai_team_1", 0),
        (try_end),
        (store_add, "$ai_team_2", ":player_team", 2),
      (try_end),
      (call_script, "script_select_battle_tactic_aux", "$ai_team_1", 0),
      (assign, "$ai_team_1_battle_tactic", reg0),
      (try_begin),
        (ge, "$ai_team_2", 0),
        (assign, ":defense_not_an_option", 0),
        (try_begin),
          (eq, "$ai_team_1_battle_tactic", btactic_hold),
          (assign, ":defense_not_an_option", 1), #don't let two AI defend at the same time
        (try_end),
        (call_script, "script_select_battle_tactic_aux", "$ai_team_2", ":defense_not_an_option"),
        (assign, "$ai_team_2_battle_tactic", reg0),
      (try_end),
  ]),

  # script_select_battle_tactic_aux
  # Input: team_no
  # Output: battle_tactic
  ("select_battle_tactic_aux",
    [
      (store_script_param, ":team_no", 1),
      (store_script_param, ":defense_not_an_option", 2),
      (assign, ":battle_tactic", 0),
      (get_player_agent_no, ":player_agent"),
      (agent_get_team, ":player_team", ":player_agent"),
      (try_begin),
        (eq, "$cant_leave_encounter", 1),
        (teams_are_enemies, ":team_no", ":player_team"),
        (assign, ":defense_not_an_option", 1),
      (try_end),
      (call_script, "script_team_get_class_percentages", ":team_no", 0),
      #      (assign, ":ai_perc_infantry", reg0),
      (assign, ":ai_perc_archers",  reg1),
      (assign, ":ai_perc_cavalry",  reg2),
      (call_script, "script_team_get_class_percentages", ":team_no", 1),#enemies of the ai_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),
        (assign, ":continue", 0),
        (try_begin),
          (teams_are_enemies, ":team_no", ":player_team"),
          (party_slot_eq, "$g_enemy_party", slot_party_type, spt_kingdom_hero_party),
          (assign, ":continue", 1),
        (else_try),
          (neg|teams_are_enemies, ":team_no", ":player_team"),
          (gt, "$g_ally_party", 0),
          (party_slot_eq, "$g_ally_party", slot_party_type, spt_kingdom_hero_party),
          (assign, ":continue", 1),
        (try_end),
        #(this_or_next|lt, ":rand", 20),
        (eq, ":continue", 1),
		(store_faction_of_party, ":enemy_faction_no", "$g_enemy_party"),
		(neq, ":enemy_faction_no", "fac_kingdom_3"), #don't let khergits use battle tactics
        (try_begin),
          (eq, ":defense_not_an_option", 0),
          (gt, ":ai_perc_archers", 50),
          (lt, ":ai_perc_cavalry", 35),
          (assign, ":battle_tactic", btactic_hold),
        (else_try),
          (lt, ":rand", 80),
          (assign, ":battle_tactic", btactic_follow_leader),
        (try_end),
      (try_end),
      (assign, reg0, ":battle_tactic"),
  ]),
  
  # script_battle_calculate_initial_powers
  # Input: none
  # Output: none
  #("battle_calculate_initial_powers",
  #  [        
  #    (try_for_agents, ":agent_no"),
  #      (agent_is_human, ":agent_no"),
  #      
  #      (call_script, "script_calculate_team_powers", ":agent_no"),
  #      (assign, ":ally_power", reg0),
  #      (assign, ":enemy_power", reg1),
  #      
  #      (agent_set_slot, ":agent_no", slot_agent_initial_ally_power, ":ally_power"),
  #      (agent_set_slot, ":agent_no", slot_agent_initial_enemy_power, ":enemy_power"),
  #    (try_end),
  #]),

  # script_battle_tactic_init
  # Input: none
  # Output: none
  ("battle_tactic_init",
    [
      (call_script, "script_battle_tactic_init_aux", "$ai_team_1", "$ai_team_1_battle_tactic"),
      (try_begin),
        (ge, "$ai_team_2", 0),
        (call_script, "script_battle_tactic_init_aux", "$ai_team_2", "$ai_team_2_battle_tactic"),
      (try_end),

      (try_for_agents, ":cur_agent"),
        (agent_set_slot, ":cur_agent",  slot_agent_is_running_away, 0), #initially nobody is running away.
      (try_end),
  ]),

  # script_battle_tactic_init_aux
  # Input: team_no, battle_tactic
  # Output: none
  ("battle_tactic_init_aux",
    [
      (store_script_param, ":team_no", 1),
      (store_script_param, ":battle_tactic", 2),
      (team_get_leader, ":ai_leader", ":team_no"),
      (try_begin),
        (eq, ":battle_tactic", btactic_hold),
        (agent_get_position, pos1, ":ai_leader"),
        (call_script, "script_find_high_ground_around_pos1", ":team_no", 30),
        (copy_position, pos1, pos52),
        (call_script, "script_find_high_ground_around_pos1", ":team_no", 30), # call again just in case we are not at peak point.
        (copy_position, pos1, pos52),
        (call_script, "script_find_high_ground_around_pos1", ":team_no", 30), # call again just in case we are not at peak point.
        (team_give_order, ":team_no", grc_everyone, mordr_hold),
        (team_set_order_position, ":team_no", grc_everyone, pos52),
        (team_give_order, ":team_no", grc_archers, mordr_advance),
        (team_give_order, ":team_no", grc_archers, mordr_advance),
      (else_try),
        (eq, ":battle_tactic", btactic_follow_leader),
        (team_get_leader, ":ai_leader", ":team_no"),
        (ge, ":ai_leader", 0),
        (agent_set_speed_limit, ":ai_leader", 8),
        (agent_get_position, pos60, ":ai_leader"),
        (team_give_order, ":team_no", grc_everyone, mordr_hold),
        (team_set_order_position, ":team_no", grc_everyone, pos60),
      (try_end),
  ]),

  # script_calculate_team_powers
  # Input: none
  # Output: ally_power, enemy_power
  ("calculate_team_powers",
     [
       (store_script_param, ":agent_no", 1),

       (try_begin),
         (assign, ":agent_side", 0),
         (agent_is_ally, ":agent_no"),
         (assign, ":agent_side", 1),
       (try_end),

       (assign, ":ally_power", 0),
       (assign, ":enemy_power", 0),
       
       (try_for_agents, ":cur_agent"),
         (agent_is_human, ":cur_agent"),
         (agent_is_alive, ":cur_agent"),
       
         (try_begin),
           (assign, ":agent_side_cur", 0),
           (agent_is_ally, ":cur_agent"),
           (assign, ":agent_side_cur", 1),
         (try_end),

         (try_begin),
           (agent_get_horse, ":agent_horse_id", ":cur_agent"),
           (neq, ":agent_horse_id", -1),
           (assign, ":agent_power", 2), #if this agent is horseman then his power effect is 2
         (else_try),
           (assign, ":agent_power", 1), #if this agent is walker then his power effect is 1
         (try_end),
       
         (try_begin),
           (eq, ":agent_side", ":agent_side_cur"),
           (val_add, ":ally_power", ":agent_power"),
         (else_try),
           (val_add, ":enemy_power", ":agent_power"),       
         (try_end),
       (try_end),
          
       (assign, reg0, ":ally_power"),         
       (assign, reg1, ":enemy_power"),         
  ]), #ozan

  # script_apply_effect_of_other_people_on_courage_scores
  # Input: none
  # Output: none
  ("apply_effect_of_other_people_on_courage_scores",
    [
      (get_player_agent_no, ":player_agent"),

      (try_for_agents, ":centered_agent_no"),
        (agent_is_human, ":centered_agent_no"),
        (agent_is_alive, ":centered_agent_no"),
        (neq, ":centered_agent_no", ":player_agent"),
        (agent_get_position, pos0, ":centered_agent_no"),
        (try_begin),
          (agent_is_ally, ":centered_agent_no"),
          (assign, ":is_centered_agent_ally", 1),
        (else_try),
          (assign, ":is_centered_agent_ally", 0),
        (try_end),
       
        (try_for_agents, ":agent_no"),
          (agent_is_human, ":agent_no"),
          (agent_is_alive, ":agent_no"),
          (neq, ":centered_agent_no", ":agent_no"),      

          (try_begin),
            (agent_is_ally, ":agent_no"),
            (assign, ":is_agent_ally", 1),
          (else_try),
            (assign, ":is_agent_ally", 0),
          (try_end),

          (eq, ":is_centered_agent_ally", ":is_agent_ally"), #if centered agent and other agent is at same team then continue.
          (agent_get_slot, ":agent_is_running_away_or_not", ":agent_no", slot_agent_is_running_away),

          (try_begin),
            (eq, ":agent_no", ":player_agent"),
            (assign, ":agent_delta_courage_score", 6),
          (else_try),
            (agent_get_troop_id, ":troop_id", ":agent_no"),
            (troop_is_hero, ":troop_id"),
      
            #Hero Agent : if near agent (hero, agent_no) is not running away his positive effect on centered agent (centered_agent_no) fighting at his side is effected by his hit points.
            (try_begin),      
              (neq, ":agent_is_running_away_or_not", 1), #if agent is not running away
              (store_agent_hit_points, ":agent_hit_points", ":agent_no"),
              (try_begin),
                (eq, ":agent_hit_points", 100),
                (assign, ":agent_delta_courage_score", 6),
              (else_try),
                (ge, ":agent_hit_points", 75),
                (assign, ":agent_delta_courage_score", 5),
              (else_try),
                (ge, ":agent_hit_points", 60),
                (assign, ":agent_delta_courage_score", 4),
              (else_try),
                (ge, ":agent_hit_points", 45),
                (assign, ":agent_delta_courage_score", 3),
              (else_try),
                (ge, ":agent_hit_points", 30),
                (assign, ":agent_delta_courage_score", 2),
              (else_try),
                (ge, ":agent_hit_points", 15),
                (assign, ":agent_delta_courage_score", 1),
              (end_try),
            (else_try),
              (assign, ":agent_delta_courage_score", 4),
            (end_try),
          (else_try),
            #Normal Agent : if near agent (agent_no) is not running away his positive effect on centered agent (centered_agent_no) fighting at his side is effected by his hit points.
            (try_begin),      
              (neq, ":agent_is_running_away_or_not", 1), # if agent is not running away
              (store_agent_hit_points, ":agent_hit_points", ":agent_no"),
              (try_begin),
                (eq, ":agent_hit_points", 100),
                (assign, ":agent_delta_courage_score", 4),
              (else_try),
                (ge, ":agent_hit_points", 75),
                (assign, ":agent_delta_courage_score", 3),
              (else_try),
                (ge, ":agent_hit_points", 50),
                (assign, ":agent_delta_courage_score", 2),
              (else_try),
                (ge, ":agent_hit_points", 25),
                (assign, ":agent_delta_courage_score", 1),
              (end_try),
              (try_begin), # to make our warrior run away easier we decrease one, because they have player_agent (+6) advantage.
                (agent_is_ally, ":agent_no"),
                (val_sub, ":agent_delta_courage_score", 1),
              (end_try),
            (else_try),
              (assign, ":agent_delta_courage_score", 2),
            (end_try),
          (try_end),
      
          (try_begin),
            (neq, ":agent_is_running_away_or_not", 1),
            (val_mul, ":agent_delta_courage_score", 1),
            (try_begin), # centered agent not running away cannot take positive courage score from one another agent not running away.
              (agent_get_slot, ":agent_is_running_away_or_not", ":centered_agent_no", slot_agent_is_running_away),
              (eq, ":agent_is_running_away_or_not", 0),
              (val_mul, ":agent_delta_courage_score", 0),
            (try_end),
          (else_try),
            (try_begin), 
              (agent_get_slot, ":agent_is_running_away_or_not", ":agent_no", slot_agent_is_running_away),
              (eq, ":agent_is_running_away_or_not", 0),
              (val_mul, ":agent_delta_courage_score", -2), # running away agent fears not running away agent more.
            (else_try),
              (val_mul, ":agent_delta_courage_score", -1),
            (try_end),
          (try_end),

          (neq, ":agent_delta_courage_score", 0),

          (agent_get_position, pos1, ":agent_no"),
          (get_distance_between_positions, ":dist", pos0, pos1),

          (try_begin),
            (ge, ":agent_delta_courage_score", 0),
            (try_begin),
              (lt, ":dist", 2000), #0-20 meter
              (agent_get_slot, ":agent_courage_score", ":centered_agent_no", slot_agent_courage_score),
              (val_mul, ":agent_delta_courage_score", 50),
              (val_add, ":agent_courage_score", ":agent_delta_courage_score"),
              (agent_set_slot, ":centered_agent_no", slot_agent_courage_score, ":agent_courage_score"),           
            (try_begin),
              (lt, ":dist", 4000), #21-40 meter
              (agent_get_slot, ":agent_courage_score", ":centered_agent_no", slot_agent_courage_score),
              (val_mul, ":agent_delta_courage_score", 40),
              (val_add, ":agent_courage_score", ":agent_delta_courage_score"),
              (agent_set_slot, ":centered_agent_no", slot_agent_courage_score, ":agent_courage_score"),           
            (try_begin),
              (lt, ":dist", 7000), #41-70 meter
              (agent_get_slot, ":agent_courage_score", ":centered_agent_no", slot_agent_courage_score),
              (val_mul, ":agent_delta_courage_score", 30),
              (val_add, ":agent_courage_score", ":agent_delta_courage_score"),
              (agent_set_slot, ":centered_agent_no", slot_agent_courage_score, ":agent_courage_score"),           
            (else_try),
              (lt, ":dist", 11000), #71-110 meter
              (agent_get_slot, ":agent_courage_score", ":centered_agent_no", slot_agent_courage_score),
              (val_mul, ":agent_delta_courage_score", 20),
              (val_add, ":agent_courage_score", ":agent_delta_courage_score"),
              (agent_set_slot, ":centered_agent_no", slot_agent_courage_score, ":agent_courage_score"),           
            (else_try),      
              (lt, ":dist", 16000), # 111-160 meter, assumed that eye can see agents friendly at most 160 meters far while fighting. 
                                    # this is more than below limit (108 meters) because we hear that allies come from further.
              (agent_get_slot, ":agent_courage_score", ":centered_agent_no", slot_agent_courage_score),
              (val_mul, ":agent_delta_courage_score", 10),
              (val_add, ":agent_courage_score", ":agent_delta_courage_score"),
              (agent_set_slot, ":centered_agent_no", slot_agent_courage_score, ":agent_courage_score"),           
            (try_end),      
          (else_try),                                               # negative effect of running agent on other ally agents are lower then positive effects above, to avoid starting  
            (try_begin),                                            # run away of all agents at a moment. I want to see agents running away one by one during battle, not all together.
              (lt, ":dist", 200), #1-2 meter,                       # this would create better game play.
              (agent_get_slot, ":agent_courage_score", ":centered_agent_no", slot_agent_courage_score),
              (val_mul, ":agent_delta_courage_score", 15),
              (val_add, ":agent_courage_score", ":agent_delta_courage_score"),
              (agent_set_slot, ":centered_agent_no", slot_agent_courage_score, ":agent_courage_score"),           
            (else_try),
              (lt, ":dist", 400), #3-4 meter, 
              (agent_get_slot, ":agent_courage_score", ":centered_agent_no", slot_agent_courage_score),
              (val_mul, ":agent_delta_courage_score", 13),
              (val_add, ":agent_courage_score", ":agent_delta_courage_score"),
              (agent_set_slot, ":centered_agent_no", slot_agent_courage_score, ":agent_courage_score"),           
            (else_try),
              (lt, ":dist", 600), #5-6 meter
              (agent_get_slot, ":agent_courage_score", ":centered_agent_no", slot_agent_courage_score),
              (val_mul, ":agent_delta_courage_score", 11),
              (val_add, ":agent_courage_score", ":agent_delta_courage_score"),
              (agent_set_slot, ":centered_agent_no", slot_agent_courage_score, ":agent_courage_score"),           
            (else_try),
              (lt, ":dist", 800), #7-8 meter
              (agent_get_slot, ":agent_courage_score", ":centered_agent_no", slot_agent_courage_score),
              (val_mul, ":agent_delta_courage_score", 9),
              (val_add, ":agent_courage_score", ":agent_delta_courage_score"),
              (agent_set_slot, ":centered_agent_no", slot_agent_courage_score, ":agent_courage_score"),           
            (else_try),
              (lt, ":dist", 1200), #9-12 meters
              (agent_get_slot, ":agent_courage_score", ":centered_agent_no", slot_agent_courage_score),
              (val_mul, ":agent_delta_courage_score", 7),
              (val_add, ":agent_courage_score", ":agent_delta_courage_score"),
              (agent_set_slot, ":centered_agent_no", slot_agent_courage_score, ":agent_courage_score"),           
            (else_try),
              (lt, ":dist", 2400), #13-24 meters
              (agent_get_slot, ":agent_courage_score", ":centered_agent_no", slot_agent_courage_score),
              (val_mul, ":agent_delta_courage_score", 5),
              (val_add, ":agent_courage_score", ":agent_delta_courage_score"),
              (agent_set_slot, ":centered_agent_no", slot_agent_courage_score, ":agent_courage_score"),           
            (else_try),
              (lt, ":dist", 4800), #25-48 meters
              (agent_get_slot, ":agent_courage_score", ":centered_agent_no", slot_agent_courage_score),
              (val_mul, ":agent_delta_courage_score", 3),
              (val_add, ":agent_courage_score", ":agent_delta_courage_score"),
              (agent_set_slot, ":centered_agent_no", slot_agent_courage_score, ":agent_courage_score"),           
            (else_try),
              (lt, ":dist", 9600), #49-98 meters, assumed that eye can see agents running away at most 98 meters far while fighting.
              (agent_get_slot, ":agent_courage_score", ":centered_agent_no", slot_agent_courage_score),
              (val_mul, ":agent_delta_courage_score", 1),
              (val_add, ":agent_courage_score", ":agent_delta_courage_score"),
              (agent_set_slot, ":centered_agent_no", slot_agent_courage_score, ":agent_courage_score"),           
            (try_end),      
          (try_end),
        (try_end),            
      (try_end),
  ]), #ozan

  
  # script_apply_death_effect_on_courage_scores
  # Input: dead agent id, killer agent id
  # Output: none
  ("apply_death_effect_on_courage_scores",
    [
      (store_script_param, ":dead_agent_no", 1),
      (store_script_param, ":killer_agent_no", 2),
      
      (try_begin),
        (agent_is_human, ":dead_agent_no"),

        (try_begin),
          (agent_is_ally, ":dead_agent_no"),
          (assign, ":is_dead_agent_ally", 1),
        (else_try),
          (assign, ":is_dead_agent_ally", 0),
        (try_end),

        (agent_get_position, pos0, ":dead_agent_no"),
        (assign, ":number_of_near_allies_to_dead_agent", 0),

        (try_for_agents, ":agent_no"),
          (agent_is_human, ":agent_no"),
          (agent_is_alive, ":agent_no"),

          (agent_get_position, pos1, ":agent_no"), 
          (get_distance_between_positions, ":dist", pos0, pos1),

          (le, ":dist", 1300), # to count number of allies within 13 meters to dead agent.

          (try_begin),
            (agent_is_ally, ":agent_no"),
            (assign, ":is_agent_ally", 1),
          (else_try),
            (assign, ":is_agent_ally", 0),
          (try_end),

          (try_begin), 
            (eq, ":is_dead_agent_ally", ":is_agent_ally"),
            (val_add, ":number_of_near_allies_to_dead_agent", 1), # (number_of_near_allies_to_dead_agent) is counted because if there are 
          (try_end),                                              # many allies of dead agent around him, negative courage effect become less.
        (try_end),
                
        (try_for_agents, ":agent_no"),
          (agent_is_human, ":agent_no"),
          (agent_is_alive, ":agent_no"),
           
          (try_begin),
            (agent_is_ally, ":agent_no"),
            (assign, ":is_agent_ally", 1),
          (else_try),
            (assign, ":is_agent_ally", 0),
          (try_end),
   
          (try_begin), # each agent is effected by a killed agent positively if he is rival or negatively if he is ally.
            (neq, ":is_dead_agent_ally", ":is_agent_ally"), 
            (assign, ":agent_delta_courage_score", 10),  # if killed agent is agent of rival side, add points to fear score
          (else_try),          
            (assign, ":agent_delta_courage_score", -15), # if killed agent is agent of our side, decrease points from fear score
            (val_add, ":agent_delta_courage_score", ":number_of_near_allies_to_dead_agent"), # ":number_of_near_allies_to_dead_agent" is added because if there are many
            (try_begin),                                                                     # allies of dead agent around him, negative courage effect become less.
              (gt, ":agent_delta_courage_score", -5),
              (assign, ":agent_delta_courage_score", -5),
            (try_end),

            (agent_get_slot, ":dead_agent_was_running_away_or_not", ":dead_agent_no",  slot_agent_is_running_away), #look dead agent was running away or not. 
            (try_begin),
              (eq, ":dead_agent_was_running_away_or_not", 1),      
              (val_div, ":agent_delta_courage_score", 3),  # if killed agent was running away his negative effect on ally courage scores become very less. This added because
            (try_end),                                     # running away agents are easily killed and courage scores become very in a running away group after a time, and
          (try_end),                                       # they do not stop running away althought they pass near a new powerfull ally party.                 
          (agent_get_position, pos1, ":agent_no"), 
          (get_distance_between_positions, ":dist", pos0, pos1),

          (try_begin),
            (eq, ":killer_agent_no", ":agent_no"),
            (agent_get_slot, ":agent_courage_score", ":agent_no", slot_agent_courage_score),
            (val_mul, ":agent_delta_courage_score", 20),
            (val_add, ":agent_courage_score", ":agent_delta_courage_score"),
            (agent_set_slot, ":agent_no", slot_agent_courage_score, ":agent_courage_score"),           
          (try_end),
        
          (try_begin),
            (lt, ":dist", 100), #0-1 meters
            (agent_get_slot, ":agent_courage_score", ":agent_no", slot_agent_courage_score),
            (val_mul, ":agent_delta_courage_score", 150),
            (val_add, ":agent_courage_score", ":agent_delta_courage_score"),
            (agent_set_slot, ":agent_no", slot_agent_courage_score, ":agent_courage_score"),           
          (else_try),
            (lt, ":dist", 200), #2 meters
            (agent_get_slot, ":agent_courage_score", ":agent_no", slot_agent_courage_score),
            (val_mul, ":agent_delta_courage_score", 120),
            (val_add, ":agent_courage_score", ":agent_delta_courage_score"),
            (agent_set_slot, ":agent_no", slot_agent_courage_score, ":agent_courage_score"),           
          (else_try),
            (lt, ":dist", 300), #3 meter
            (agent_get_slot, ":agent_courage_score", ":agent_no", slot_agent_courage_score),
            (val_mul, ":agent_delta_courage_score", 100),
            (val_add, ":agent_courage_score", ":agent_delta_courage_score"),
            (agent_set_slot, ":agent_no", slot_agent_courage_score, ":agent_courage_score"),           
          (else_try),
            (lt, ":dist", 400), #4 meters
            (agent_get_slot, ":agent_courage_score", ":agent_no", slot_agent_courage_score),
            (val_mul, ":agent_delta_courage_score", 90),
            (val_add, ":agent_courage_score", ":agent_delta_courage_score"),
            (agent_set_slot, ":agent_no", slot_agent_courage_score, ":agent_courage_score"),           
          (else_try),
            (lt, ":dist", 600), #5-6 meters
            (agent_get_slot, ":agent_courage_score", ":agent_no", slot_agent_courage_score),
            (val_mul, ":agent_delta_courage_score", 80),
            (val_add, ":agent_courage_score", ":agent_delta_courage_score"),
            (agent_set_slot, ":agent_no", slot_agent_courage_score, ":agent_courage_score"),           
          (else_try),
            (lt, ":dist", 800), #7-8 meters
            (agent_get_slot, ":agent_courage_score", ":agent_no", slot_agent_courage_score),
            (val_mul, ":agent_delta_courage_score", 70),
            (val_add, ":agent_courage_score", ":agent_delta_courage_score"),
            (agent_set_slot, ":agent_no", slot_agent_courage_score, ":agent_courage_score"),           
          (else_try),
            (lt, ":dist", 1000), #9-10 meters
            (agent_get_slot, ":agent_courage_score", ":agent_no", slot_agent_courage_score),
            (val_mul, ":agent_delta_courage_score", 60),
            (val_add, ":agent_courage_score", ":agent_delta_courage_score"),
            (agent_set_slot, ":agent_no", slot_agent_courage_score, ":agent_courage_score"),           
          (else_try),
            (lt, ":dist", 1500), #11-15 meter
            (agent_get_slot, ":agent_courage_score", ":agent_no", slot_agent_courage_score),
            (val_mul, ":agent_delta_courage_score", 50),
            (val_add, ":agent_courage_score", ":agent_delta_courage_score"),
            (agent_set_slot, ":agent_no", slot_agent_courage_score, ":agent_courage_score"),           
          (else_try),
            (lt, ":dist", 2500), #16-25 meters
            (agent_get_slot, ":agent_courage_score", ":agent_no", slot_agent_courage_score),
            (val_mul, ":agent_delta_courage_score", 40),
            (val_add, ":agent_courage_score", ":agent_delta_courage_score"),
            (agent_set_slot, ":agent_no", slot_agent_courage_score, ":agent_courage_score"),           
          (else_try),
            (lt, ":dist", 4000), #26-40 meters
            (agent_get_slot, ":agent_courage_score", ":agent_no", slot_agent_courage_score),
            (val_mul, ":agent_delta_courage_score", 30),
            (val_add, ":agent_courage_score", ":agent_delta_courage_score"),
            (agent_set_slot, ":agent_no", slot_agent_courage_score, ":agent_courage_score"),           
          (else_try),
            (lt, ":dist", 6500), #41-65 meters
            (agent_get_slot, ":agent_courage_score", ":agent_no", slot_agent_courage_score),
            (val_mul, ":agent_delta_courage_score", 20),
            (val_add, ":agent_courage_score", ":agent_delta_courage_score"),
            (agent_set_slot, ":agent_no", slot_agent_courage_score, ":agent_courage_score"),           
          (else_try),
            (lt, ":dist", 10000), #61-100 meters
            (agent_get_slot, ":agent_courage_score", ":agent_no", slot_agent_courage_score),
            (val_mul, ":agent_delta_courage_score", 10),
            (val_add, ":agent_courage_score", ":agent_delta_courage_score"),
            (agent_set_slot, ":agent_no", slot_agent_courage_score, ":agent_courage_score"),           
          (try_end),
        (try_end),
      (try_end),
      ]), #ozan

  # script_decide_run_away_or_not
  # Input: none
  # Output: none
  ("decide_run_away_or_not",
    [
      (store_script_param, ":cur_agent", 1),
      (store_script_param, ":mission_time", 2),
      
      (assign, ":force_retreat", 0),
      (agent_get_team, ":agent_team", ":cur_agent"),
      (agent_get_division, ":agent_division", ":cur_agent"),
      (try_begin),
        (lt, ":agent_division", 9), #static classes
        (team_get_movement_order, ":agent_movement_order", ":agent_team", ":agent_division"),
        (eq, ":agent_movement_order", mordr_retreat),
        (assign, ":force_retreat", 1),
      (try_end),

      (agent_get_slot, ":is_cur_agent_running_away", ":cur_agent", slot_agent_is_running_away),
      (try_begin),
        (eq, ":is_cur_agent_running_away", 0),
        (try_begin),
          (eq, ":force_retreat", 1),
          (agent_start_running_away, ":cur_agent"),
          (agent_set_slot, ":cur_agent",  slot_agent_is_running_away, 1),
        (else_try),
          (ge, ":mission_time", 45), #first 45 seconds anyone does not run away whatever happens.
          (agent_get_slot, ":agent_courage_score", ":cur_agent",  slot_agent_courage_score),
          (store_agent_hit_points, ":agent_hit_points", ":cur_agent"),
          (val_mul, ":agent_hit_points", 4),
          (try_begin),
            (agent_is_ally, ":cur_agent"),
            (val_sub, ":agent_hit_points", 100), #ally agents will be more tend to run away, to make game more funnier/harder
          (try_end),
          (val_mul, ":agent_hit_points", 10),
          (store_sub, ":start_running_away_courage_score_limit", 3500, ":agent_hit_points"), 
          (lt, ":agent_courage_score", ":start_running_away_courage_score_limit"), #if (courage score < 3500 - (agent hit points * 40)) and (agent is not running away) then start running away, average hit points : 50, average running away limit = 1500

          (agent_get_troop_id, ":troop_id", ":cur_agent"), #for now do not let heroes to run away from battle
          (neg|troop_is_hero, ":troop_id"),
                                
          (agent_start_running_away, ":cur_agent"),
          (agent_set_slot, ":cur_agent",  slot_agent_is_running_away, 1),
        (try_end),
      (else_try),
        (neq, ":force_retreat", 1),
        (agent_get_slot, ":agent_courage_score", ":cur_agent",  slot_agent_courage_score),
        (store_agent_hit_points, ":agent_hit_points", ":cur_agent"),      
        (val_mul, ":agent_hit_points", 4),
        (try_begin),
          (agent_is_ally, ":cur_agent"),
          (val_sub, ":agent_hit_points", 100), #ally agents will be more tend to run away, to make game more funnier/harder
        (try_end),
        (val_mul, ":agent_hit_points", 10),
        (store_sub, ":stop_running_away_courage_score_limit", 3700, ":agent_hit_points"), 
        (ge, ":agent_courage_score", ":stop_running_away_courage_score_limit"), #if (courage score > 3700 - agent hit points) and (agent is running away) then stop running away, average hit points : 50, average running away limit = 1700
        (agent_stop_running_away, ":cur_agent"),
        (agent_set_slot, ":cur_agent",  slot_agent_is_running_away, 0),
      (try_end),      
  ]), #ozan

  # script_battle_tactic_apply
  # Input: none
  # Output: none
  ("battle_tactic_apply",
    [
      (call_script, "script_battle_tactic_apply_aux", "$ai_team_1", "$ai_team_1_battle_tactic"),
      (assign, "$ai_team_1_battle_tactic", reg0),
      (try_begin),
        (ge, "$ai_team_2", 0),
        (call_script, "script_battle_tactic_apply_aux", "$ai_team_2", "$ai_team_2_battle_tactic"),
        (assign, "$ai_team_2_battle_tactic", reg0),
      (try_end),
  ]),

  # script_battle_tactic_apply_aux
  # Input: team_no, battle_tactic
  # Output: battle_tactic
  ("battle_tactic_apply_aux",
    [
      (store_script_param, ":team_no", 1),
      (store_script_param, ":battle_tactic", 2),
      (store_mission_timer_a, ":mission_time"),
      (try_begin),
        (eq, ":battle_tactic", btactic_hold),
        (copy_position, pos1, pos52),
        (call_script, "script_get_closest3_distance_of_enemies_at_pos1", ":team_no", 1),
        (assign, ":avg_dist", reg0),
        (assign, ":min_dist", reg1),
        (try_begin),
          (this_or_next|lt, ":min_dist", 1000),
          (lt, ":avg_dist", 4000),
          (assign, ":battle_tactic", 0),
          (team_give_order, ":team_no", grc_everyone, mordr_charge),
        (try_end),
      (else_try),
        (eq, ":battle_tactic", btactic_follow_leader),
        (team_get_leader, ":ai_leader", ":team_no"),
        (try_begin),
          (ge, ":ai_leader", 0),
          (agent_is_alive, ":ai_leader"),
          (agent_set_speed_limit, ":ai_leader", 9),
          (call_script, "script_team_get_average_position_of_enemies", ":team_no"),
          (copy_position, pos60, pos0),
          (agent_get_position, pos61, ":ai_leader"),
          (position_transform_position_to_local, pos62, pos61, pos60), #pos62 = vector to enemy w.r.t leader
          (position_normalize_origin, ":distance_to_enemy", pos62),
          (convert_from_fixed_point, ":distance_to_enemy"),
          (assign, reg17, ":distance_to_enemy"),
          (position_get_x, ":dir_x", pos62),
          (position_get_y, ":dir_y", pos62),
          (val_mul, ":dir_x", 23),
          (val_mul, ":dir_y", 23), #move 23 meters
          (position_set_x, pos62, ":dir_x"),
          (position_set_y, pos62, ":dir_y"),
        
          (position_transform_position_to_parent, pos63, pos61, pos62), #pos63 is 23m away from leader in the direction of the enemy.
          (position_set_z_to_ground_level, pos63),
        
          (team_give_order, ":team_no", grc_everyone, mordr_hold),
          (team_set_order_position, ":team_no", grc_everyone, pos63),
          (agent_get_position, pos1, ":ai_leader"),
          (try_begin),
            (lt, ":distance_to_enemy", 50),
            (ge, ":mission_time", 30),
            (assign, ":battle_tactic", 0),
            (team_give_order, ":team_no", grc_everyone, mordr_charge),
            (agent_set_speed_limit, ":ai_leader", 60),
          (try_end),
        (else_try),
          (assign, ":battle_tactic", 0),
          (team_give_order, ":team_no", grc_everyone, mordr_charge),
        (try_end),
      (try_end),
      
      (try_begin), # charge everyone after a while
        (neq, ":battle_tactic", 0),
        (ge, ":mission_time", 300),
        (assign, ":battle_tactic", 0),
        (team_give_order, ":team_no", grc_everyone, mordr_charge),
        (team_get_leader, ":ai_leader", ":team_no"),
        (agent_set_speed_limit, ":ai_leader", 60),
      (try_end),
      (assign, reg0, ":battle_tactic"),
  ]),

  
##  # 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, arg2: try for team's enemies
  # 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, ":team_no", 1),
      (store_script_param, ":negate", 2),
      (try_for_agents,":cur_agent"),
        (agent_is_alive, ":cur_agent"),
        (agent_is_human, ":cur_agent"),
        (agent_get_team, ":agent_team", ":cur_agent"),
        (assign, ":continue", 0),
        (try_begin),
          (eq, ":negate", 1),
          (teams_are_enemies, ":agent_team", ":team_no"),
          (assign, ":continue", 1),
        (else_try),
          (eq, ":agent_team", ":team_no"),
          (assign, ":continue", 1),
        (try_end),
        (eq, ":continue", 1),
        (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_enemies_at_pos1
  # Input: arg1: team_no, pos1
  # Output: reg0: distance in cms.
  ("get_closest3_distance_of_enemies_at_pos1",
    [
      (assign, ":min_distance_1", 100000),
      (assign, ":min_distance_2", 100000),
      (assign, ":min_distance_3", 100000),
      
      (store_script_param, ":team_no", 1),
      (try_for_agents,":cur_agent"),
        (agent_is_alive, ":cur_agent"),
        (agent_is_human, ":cur_agent"),
        (agent_get_team, ":agent_team", ":cur_agent"),
        (teams_are_enemies, ":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),
      
        (val_add, ":accum_x", ":x"),
        (val_add, ":accum_y", ":y"),
        (val_add, ":accum_z", ":z"),
        (val_add, ":num_enemies", 1),
      (try_end),
      
      (try_begin), #to avoid division by zeros at below division part.
        (le, ":num_enemies", 0),
        (assign, ":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"),

      (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_link, s1, ":troop_no"),
      (display_message, "@You now owe {reg2} denars to {s1}."),
  ]),
  
  
  
  
  # 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),
        (this_or_next|eq, ":quest_no", "qst_deliver_message"),
        (eq, ":quest_no", "qst_deliver_message_to_enemy_lord"),
        (assign, ":quest_return_penalty", -2),
        (assign, ":quest_expire_penalty", -3),
		
		# NE quests
				# v585 Josef lord love letter 
	  (else_try),
        (eq, ":quest_no",  "qst_deliver_love_letter"),
        (assign, ":quest_return_penalty", -2),
        (assign, ":quest_expire_penalty", -3),		
      # NE end quests
	  
      (else_try),
        (eq, ":quest_no", "qst_kidnapped_girl"),
        (party_remove_members, "p_main_party", "trp_kidnapped_girl", 1),
        (quest_get_slot, ":quest_target_party", "qst_kidnapped_girl", slot_quest_target_party),
        (try_begin),
          (party_is_active, ":quest_target_party"),
          (remove_party, ":quest_target_party"),
        (try_end),
      (else_try),
        (eq, ":quest_no", "qst_escort_lady"),
        (quest_get_slot, ":quest_object_troop", "qst_escort_lady", slot_quest_object_troop),
        (party_remove_members, "p_main_party", ":quest_object_troop", 1),
        (assign, ":quest_return_penalty", -2),
        (assign, ":quest_expire_penalty", -3),
##      (else_try),
##        (eq, ":quest_no", "qst_rescue_lady_under_siege"),
##        (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_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_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),
		
	# NE quests
	# v585 Josef peasant
		(else_try),
        (eq, ":quest_no", "qst_raise_peasants"),
        (quest_get_slot, ":quest_giver_troop", ":quest_no", slot_quest_giver_troop),
        (call_script, "script_change_debt_to_troop", ":quest_giver_troop", 250),
        (assign, ":quest_return_penalty", -4),
        (assign, ":quest_expire_penalty", -5),
# v585 Josef get wine for lord
      (else_try),
        (eq, ":quest_no", "qst_party"),
        (assign, ":quest_return_penalty", -6),
        (assign, ":quest_expire_penalty", -7),
# v585 Josef elites
		(else_try),
        (eq, ":quest_no", "qst_kill_elites"),
        (quest_get_slot, ":quest_giver_troop", ":quest_no", slot_quest_giver_troop),
        (assign, ":quest_return_penalty", -4),
        (assign, ":quest_expire_penalty", -5),

# end v585 Josef	
	
	# NE end quests
      (else_try),
        (eq, ":quest_no", "qst_deal_with_looters"),
        (try_for_parties, ":cur_party_no"),
          (party_get_template_id, ":cur_party_template", ":cur_party_no"),
          (eq, ":cur_party_template", "pt_looters"),
          (party_set_flags, ":cur_party_no", pf_quest_party, 0),
        (try_end),
        (assign, ":quest_return_penalty", -4),
        (assign, ":quest_expire_penalty", -5),
      (else_try),
        (eq, ":quest_no", "qst_deal_with_bandits_at_lords_village"),
        (quest_get_slot, ":quest_giver_troop", ":quest_no", slot_quest_giver_troop),
        (call_script, "script_change_debt_to_troop", ":quest_giver_troop", 200),
        (assign, ":quest_return_penalty", -5),
        (assign, ":quest_expire_penalty", -6),
      (else_try),
        (eq, ":quest_no", "qst_collect_taxes"),
        (quest_get_slot, ":gold_reward", ":quest_no", slot_quest_gold_reward),
        (quest_set_slot, ":quest_no", slot_quest_gold_reward, 0),
        (quest_get_slot, ":quest_giver_troop", ":quest_no", slot_quest_giver_troop),
        (call_script, "script_change_debt_to_troop", ":quest_giver_troop", ":gold_reward"),
        (assign, ":quest_return_penalty", -4),
        (assign, ":quest_expire_penalty", -6),
##      (else_try),
##        (eq, ":quest_no", "qst_capture_messenger"),
##      (else_try),
##        (eq, ":quest_no", "qst_bring_back_deserters"),
      (else_try),
        (eq, ":quest_no", "qst_hunt_down_fugitive"),
        (assign, ":quest_return_penalty", -3),
        (assign, ":quest_expire_penalty", -4),
		# NE quests
	#v585 Josef girl		
		      (else_try),
        (eq, ":quest_no", "qst_hunt_down_girl"),
        (assign, ":quest_return_penalty", -3),
        (assign, ":quest_expire_penalty", -4),
		(quest_get_slot, ":quest_target_center", "qst_hunt_down_girl", slot_quest_target_center),
		(party_set_slot, ":quest_target_center", slot_village_infested_by_wedding, 0),		
# v585 Josef smugglers		
		      (else_try),
        (eq, ":quest_no", "qst_hunt_down_smugglers"),
        (assign, ":quest_return_penalty", -1),
        (assign, ":quest_expire_penalty", -1),
		
# dunno significance of this
	  (else_try),
        (eq, ":quest_no", "qst_bar_brawl"),
#end v585 Josef			
		
		# NE end quests

      (else_try),
        (eq, ":quest_no", "qst_kill_local_merchant"),
      (else_try),
        (eq, ":quest_no", "qst_bring_back_runaway_serfs"),
        (assign, ":quest_return_penalty", -1),
        (assign, ":quest_expire_penalty", -1),
      (else_try),
        (eq, ":quest_no", "qst_lend_companion"),
      (else_try),
        (eq, ":quest_no", "qst_collect_debt"),
        (try_begin),
          (quest_slot_eq, "qst_collect_debt", slot_quest_current_state, 1), #debt collected but not delivered
          (quest_get_slot, ":debt", "qst_collect_debt", slot_quest_target_amount),
          (quest_get_slot, ":quest_giver", "qst_collect_debt", slot_quest_giver_troop),
          (call_script, "script_change_debt_to_troop", ":quest_giver", ":debt"),
          (assign, ":quest_return_penalty", -3),
          (assign, ":quest_expire_penalty", -6),
        (else_try),
          (assign, ":quest_return_penalty", -3),
          (assign, ":quest_expire_penalty", -4),
        (try_end),
      (else_try),
        (eq, ":quest_no", "qst_deal_with_bandits_at_lords_village"),
        (assign, ":quest_return_penalty", -6),
        (assign, ":quest_expire_penalty", -6),
      (else_try),
        (eq, ":quest_no", "qst_cause_provocation"),
        (assign, ":quest_return_penalty", -10),
        (assign, ":quest_expire_penalty", -13),
      (else_try),
        (eq, ":quest_no", "qst_persuade_lords_to_make_peace"),
        (assign, ":quest_return_penalty", -10),
        (assign, ":quest_expire_penalty", -13),
      (else_try),
        (eq, ":quest_no", "qst_deal_with_night_bandits"),
        (assign, ":quest_return_penalty", -1),
        (assign, ":quest_expire_penalty", -1),
      
      (else_try),
        (eq, ":quest_no", "qst_follow_spy"),
        (assign, ":quest_return_penalty", -2),
        (assign, ":quest_expire_penalty", -3),
        (try_begin),
          (party_is_active, "$qst_follow_spy_spy_party"),
          (remove_party, "$qst_follow_spy_spy_party"),
        (try_end),
        (try_begin),
          (party_is_active, "$qst_follow_spy_spy_partners_party"),
          (remove_party, "$qst_follow_spy_spy_partners_party"),
        (try_end),
      (else_try),
        (eq, ":quest_no", "qst_capture_enemy_hero"),
        (assign, ":quest_return_penalty", -3),
        (assign, ":quest_expire_penalty", -4),
##      (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"),
        (assign, ":quest_return_penalty", -5),
        (assign, ":quest_expire_penalty", -6),
##      (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"),
        (assign, ":quest_return_penalty", -1),
        (assign, ":quest_expire_penalty", -1),
      (else_try),
        (eq, ":quest_no", "qst_deliver_message_to_prisoner_lord"),
        (assign, ":quest_return_penalty", 0),
        (assign, ":quest_expire_penalty", -1),
      (else_try),
        (eq, ":quest_no", "qst_duel_for_lady"),
        (assign, ":quest_return_penalty", -1),
        (assign, ":quest_expire_penalty", -1),
      # NE quests
# v585 Josef Portrait      
       (else_try),
        (eq, ":quest_no", "qst_deliver_portrait"),
        (assign, ":quest_return_penalty", -2),
        (assign, ":quest_expire_penalty", -3),
	(quest_get_slot, ":quest_target_party", "qst_deliver_portrait", slot_quest_target_party),
    (quest_get_slot, ":quest_target_center", "qst_deliver_portrait", slot_quest_target_center),
    (party_set_ai_behavior, ":quest_target_party", ai_bhvr_travel_to_party),
    (party_set_ai_object, ":quest_target_party", ":quest_target_center"),
    (party_set_flags, ":quest_target_party", pf_default_behavior, 0),
# v585 Josef love letter 
        (else_try),
        (eq, ":quest_no", "qst_deliver_letter"),
        (assign, ":quest_return_penalty", -2),
        (assign, ":quest_expire_penalty", -3),		
# v585 Josef King
	   (else_try),
        (eq, ":quest_no", "qst_fight_king"),
        (assign, ":quest_return_penalty", -1),
        (assign, ":quest_expire_penalty", -2),
# end v585 Josef	  
	  
	  
	  
	  # NE end quests
	  
	  
	  
	  
      #Kingdom Army quests
      (else_try),
        (eq, ":quest_no", "qst_follow_army"),
        (assign, ":quest_return_penalty", 0), #was -4 
        (assign, ":quest_expire_penalty", 0), #was -5
      (else_try),
        (eq, ":quest_no", "qst_deliver_cattle_to_army"),
        (assign, ":quest_return_penalty", 0),
        (assign, ":quest_expire_penalty", 0),
      (else_try),
        (eq, ":quest_no", "qst_join_siege_with_army"),
        (assign, ":quest_return_penalty", -1),
        (assign, ":quest_expire_penalty", -2),
      (else_try),
        (eq, ":quest_no", "qst_scout_waypoints"),
        (assign, ":quest_return_penalty", 0),
        (assign, ":quest_expire_penalty", 0),
      
      #Village Elder quests
      (else_try),
        (eq, ":quest_no", "qst_deliver_grain"),
        (assign, ":quest_return_penalty", -6),
        (assign, ":quest_expire_penalty", -7),
# NE quests 

	# v585 Josef lumber
	  (else_try),
        (eq, ":quest_no", "qst_deliver_lumber"),
        (assign, ":quest_return_penalty", -6),
        (assign, ":quest_expire_penalty", -7),
	# v585 Josef scholars	
	  (else_try),
        (eq, ":quest_no", "qst_escort_scholars"),
        (assign, ":quest_return_penalty", -1),
        (assign, ":quest_expire_penalty", -3),
		
	#end v585 Josef		
# NE end quests 

      (else_try),
        (eq, ":quest_no", "qst_deliver_cattle"),
        (assign, ":quest_return_penalty", -3),
        (assign, ":quest_expire_penalty", -4),
      (else_try),
        (eq, ":quest_no", "qst_train_peasants_against_bandits"),
        (assign, ":quest_return_penalty", -4),
        (assign, ":quest_expire_penalty", -5),

      #Mayor quests
      (else_try),
        (eq, ":quest_no", "qst_deliver_wine"),
        (assign, ":quest_return_penalty", -1),
        (assign, ":quest_expire_penalty", -3),
        (val_add, "$debt_to_merchants_guild", "$qst_deliver_wine_debt"),
      (else_try),
        (eq, ":quest_no", "qst_move_cattle_herd"),
        (assign, ":quest_return_penalty", -1),
        (assign, ":quest_expire_penalty", -3),
      (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),
		# NE quests
# v585 Josef Cheese Rustlers
	   (else_try),
        (eq, ":quest_no", "qst_cheese_rustlers"),
        (assign, ":quest_return_penalty", -1),
        (assign, ":quest_expire_penalty", -2),
# v585 Josef Cheese Paladins
	   (else_try),
        (eq, ":quest_no", "qst_cheese_paladins"),
        (assign, ":quest_return_penalty", -1),
        (assign, ":quest_expire_penalty", -2),
# end v585 Josef		
		# NE end quests
		
      #Other quests
      (else_try),
        (eq, ":quest_no", "qst_join_faction"),
        (assign, ":quest_return_penalty", -3),
        (assign, ":quest_expire_penalty", -3),
        (try_begin),
          (call_script, "script_get_number_of_hero_centers", "trp_player"),
          (gt, reg0, 0),
          (call_script, "script_change_player_relation_with_faction", "$g_invite_faction", -10),
        (try_end),
		
		
		(try_begin), #if the vassalage is part of a surrender option, then the faction returns to a state of war
		  (quest_slot_eq, "qst_join_faction", slot_quest_failure_consequence, 1),
		  (call_script, "script_diplomacy_start_war_between_kingdoms", "fac_player_supporters_faction", "$g_invite_faction", 0),
		  (call_script, "script_change_player_honor", -5),
		  (quest_set_slot, "qst_join_faction", slot_quest_failure_consequence, 0),
		(try_end),
		
		
        (assign, "$g_invite_faction", 0),
        (assign, "$g_invite_faction_lord", 0),
        (assign, "$g_invite_offered_center", 0),
      (else_try),
        (eq, ":quest_no", "qst_eliminate_bandits_infesting_village"),
        (assign, ":quest_return_penalty", -3),
        (assign, ":quest_expire_penalty", -3),
	  (else_try),
        (ge, ":quest_no", "qst_resolve_dispute"),
		(assign, ":authority_loss", -2),
        (assign, ":quest_return_penalty", 0),
        (assign, ":quest_expire_penalty", 0),
	  (else_try),
        (ge, ":quest_no", "qst_consult_with_minister"),
		(assign, ":authority_loss", -2),
        (assign, ":quest_return_penalty", 0),
        (assign, ":quest_expire_penalty", 0),
	  (try_end),
	  
      (try_begin),
        (gt, ":abort_type", 0),
        (lt, ":quest_no", "qst_resolve_dispute"),
		
        (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),
        (try_begin),
          (this_or_next|is_between, ":quest_giver", village_elders_begin, village_elders_end),
          (is_between, ":quest_giver", mayors_begin, mayors_end),
          (quest_get_slot, ":quest_giver_center", ":quest_no", slot_quest_giver_center),
          (call_script, "script_change_player_relation_with_center", ":quest_giver_center", ":relation_penalty"),
        (else_try),
          (call_script, "script_change_player_relation_with_troop", ":quest_giver", ":relation_penalty"),
        (try_end),
      (try_end),

      (fail_quest, ":quest_no"),

#NPC companion changes begin
      (try_begin),
        (gt, ":abort_type", 0),
		(neq, ":quest_no", "qst_consult_with_minister"),
		(neq, ":quest_no", "qst_resolve_dispute"),
		(neq, ":quest_no", "qst_visit_lady"),
		(neq, ":quest_no", "qst_formal_marriage_proposal"),
		(neq, ":quest_no", "qst_duel_courtship_rival"),
		(neq, ":quest_no", "qst_follow_army"),
		(neq, ":quest_no", "qst_denounce_lord"),
		(neq, ":quest_no", "qst_intrigue_against_lord"),
		(neq, ":quest_no", "qst_offer_gift"),
		(neq, ":quest_no", "qst_organize_feast"),
		
        (call_script, "script_objectionable_action", tmt_honest, "str_fail_quest"),
      (try_end),
#NPC companion changes end

	  (try_begin),
		(eq, ":quest_no", "qst_resolve_dispute"),
		(faction_slot_eq, "$players_kingdom", slot_faction_leader, "trp_player"),
		(call_script, "script_change_player_right_to_rule", ":authority_loss"),
		(try_for_range, ":lord", active_npcs_begin, active_npcs_end),
			(store_faction_of_troop, ":lord_faction", ":lord"),
			(eq, ":lord_faction", "fac_player_supporters_faction"),
			(call_script, "script_troop_change_relation_with_troop", ":lord", "trp_player", ":authority_loss"),
	    (try_end),
	  (try_end),
	  

	  (try_begin),
		(eq, ":quest_no", "qst_organize_feast"),
		(call_script, "script_add_notification_menu", "mnu_notification_feast_quest_expired", 0, 0),
	  (try_end),
	  
	  
      (call_script, "script_end_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, arg3 = continue_battle s5 = title_string
  # Output: none
  ("simulate_retreat",
    [
      (call_script, "script_music_set_situation_with_culture", mtf_sit_killed),
      (set_show_messages, 0),
      (store_script_param, ":players_side_damage", 1),
      (store_script_param, ":enemy_side_damage", 2),
      (store_script_param, ":continue_battle", 3),

      (assign, ":players_side_strength", 0),
      (assign, ":enemy_side_strength", 0),
      
      (assign, ":do_calculate", 1),
      (try_begin),
        (try_for_agents, ":cur_agent"),
          (agent_is_human, ":cur_agent"),
          (agent_is_alive, ":cur_agent"),
          (agent_set_slot, ":cur_agent", slot_agent_is_alive_before_retreat, 1),#needed for simulation

          (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),
        (eq, "$pin_player_fallen", 0),
        (lt, ":enemy_side_strength", ":players_side_strength"),
        (eq, ":continue_battle", 1),
        (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),
          (dialog_box,"str_casualty_display", s5),
        (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"),
        #do not check agent_is_alive, check slot_agent_is_alive_before_retreat instead, so that dead agents can still hit enemies
        (agent_slot_eq, ":cur_agent", slot_agent_is_alive_before_retreat, 1),
        (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", 2),
        (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", 2),
        (try_end),
        (assign, ":agents_hit", 18000),
        (val_add, ":min_distance", 3000),
        (val_div, ":agents_hit", ":min_distance"),
        (val_mul, ":agents_hit", 2),# max 10, min 2 hits within 150 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_div, ":level_dif", 5),
        (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_supporters_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"),
	  (call_script, "script_troop_get_relation_with_troop", ":troop_no", ":checked_troop_no"),
	  (lt, reg0, -10),
 ]),
  
  
  # 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_walled_center_with_less_strength_priority
  # Input: arg1 = troop_no, arg2 = preferred_center_no
  # Output: reg0 = center_no (Can fail)
  ("cf_troop_get_random_leaded_walled_center_with_less_strength_priority",
    [
      (store_script_param, ":troop_no", 1),
      (store_script_param, ":preferred_center_no", 2),

      (assign, ":num_centers", 0),
      (try_for_range, ":center_no", walled_centers_begin, walled_centers_end),
        (party_slot_eq, ":center_no", slot_town_lord, ":troop_no"),
        (party_slot_eq, ":center_no", slot_center_is_besieged_by, -1),
        (val_add, ":num_centers", 1),
        (try_begin),
          (eq, ":center_no", ":preferred_center_no"),
          (val_add, ":num_centers", 99),
        (try_end),
##        (call_script, "script_party_calculate_regular_strength", ":center_no"),
##        (assign, ":strength", reg0),
##        (lt, ":strength", 80),
##        (store_sub, ":strength", 100, ":strength"),
##        (val_div, ":strength", 20),
##        (val_add, ":num_centers", ":strength"),
      (try_end),
      (gt, ":num_centers", 0),
      (store_random_in_range, ":random_center", 0, ":num_centers"),
      (assign, ":result", -1),
      (try_for_range, ":center_no", walled_centers_begin, walled_centers_end),
        (eq, ":result", -1),
        (party_slot_eq, ":center_no", slot_town_lord, ":troop_no"),
        (party_slot_eq, ":center_no", slot_center_is_besieged_by, -1),
        (val_sub, ":random_center", 1),
        (try_begin),
          (eq, ":center_no", ":preferred_center_no"),
          (val_sub, ":random_center", 99),
        (try_end),
##        (try_begin),
##          (call_script, "script_party_calculate_regular_strength", ":center_no"),
##          (assign, ":strength", reg0),
##          (lt, ":strength", 80),
##          (store_sub, ":strength", 100, ":strength"),
##          (val_div, ":strength", 20),
##          (val_sub, ":random_center", ":strength"),
##        (try_end),
        (lt, ":random_center", 0),
        (assign, ":result", ":center_no"),
      (try_end),
      (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_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),
  ]),
  
  ("troop_write_family_relations_to_s1", 
    [
	(str_clear, s1),
	#redo, possibly using base from update_troop_notes
	
]),

   # 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: s11 = what troop_1 is to troop_2, reg0 = strength of relationship. Normally, "$g_talk_troop" should be troop_2
  
  ("troop_get_family_relation_to_troop", 
    [
    (store_script_param_1, ":troop_1"),
    (store_script_param_2, ":troop_2"),
		
    (troop_get_type, ":gender_1", ":troop_1"),
	(assign, ":relation_strength", 0),
	
    (troop_get_slot, ":spouse_of_1", ":troop_1", slot_troop_spouse),
    (troop_get_slot, ":spouse_of_2", ":troop_2", slot_troop_spouse),
	
	(try_begin),
		(gt, ":spouse_of_1", -1),
		(troop_get_slot, ":father_of_spouse_of_1", ":spouse_of_1", slot_troop_father),
	(else_try),
		(assign, ":father_of_spouse_of_1", -1),
	(try_end),
	
	(try_begin),
		(gt, ":spouse_of_2", -1),
		(troop_get_slot, ":father_of_spouse_of_2", ":spouse_of_2", slot_troop_father),
	(else_try),
		(assign, ":father_of_spouse_of_2", -1),
	(try_end),

	(try_begin),
		(gt, ":spouse_of_2", -1),
		(troop_get_slot, ":mother_of_spouse_of_2", ":spouse_of_2", slot_troop_mother),
	(else_try),
		(assign, ":mother_of_spouse_of_2", -1),
	(try_end),
	
    (troop_get_slot, ":father_of_1", ":troop_1", slot_troop_father),
    (troop_get_slot, ":father_of_2", ":troop_2", slot_troop_father),

	#For the sake of simplicity, we can assume that all male aristocrats in prior generations either married commoners or procured their brides from the Old Country, thus discounting intermarriage 
    (troop_get_slot, ":mother_of_1", ":troop_1", slot_troop_mother),
    (troop_get_slot, ":mother_of_2", ":troop_2", slot_troop_mother),
		
	(try_begin),
		(is_between, ":father_of_1", companions_begin, kingdom_ladies_end),
		(troop_get_slot, ":paternal_grandfather_of_1", ":father_of_1", slot_troop_father),
	(else_try),
		(assign, ":paternal_grandfather_of_1", -1),
	(try_end),
	
	(try_begin),
		(is_between, ":father_of_2", companions_begin, kingdom_ladies_end),
		(troop_get_slot, ":paternal_grandfather_of_2", ":father_of_2", slot_troop_father),
	(else_try),
		(assign, ":paternal_grandfather_of_2", -1),
	(try_end),
		
    (troop_get_slot, ":guardian_of_1", ":troop_1", slot_troop_guardian),
    (troop_get_slot, ":guardian_of_2", ":troop_2", slot_troop_guardian),

	(str_store_string, s11, "str_no_relation"),
	
	(try_begin),
	  (eq, ":troop_1", ":troop_2"),
	  #self
	(else_try),
	  (eq, ":spouse_of_1", ":troop_2"),
	  (assign, ":relation_strength", 20),
	  (try_begin),
	    (eq, ":gender_1", 1),
	    (str_store_string, s11, "str_wife"),
	  (else_try),
	    (str_store_string, s11, "str_husband"),
	  (try_end),
	(else_try),
	  (eq, ":father_of_2", ":troop_1"),
	  (assign, ":relation_strength", 15),
	  (str_store_string, s11, "str_father"),
	(else_try),
	  (eq, ":mother_of_2", ":troop_1"),
	  (assign, ":relation_strength", 15),
	  (str_store_string, s11, "str_mother"),
	(else_try),
	  (this_or_next|eq, ":father_of_1", ":troop_2"),
	  (eq, ":mother_of_1", ":troop_2"),
	  (assign, ":relation_strength", 15),	  
	  (try_begin),
	    (eq, ":gender_1", 1),
	    (str_store_string, s11, "str_daughter"),
	  (else_try),
	    (str_store_string, s11, "str_son"),
	  (try_end),
	(else_try),
	  (gt, ":father_of_1", -1), #necessary, as some lords do not have the father registered
	  (eq, ":father_of_1", ":father_of_2"),
	  (assign, ":relation_strength", 10),
	  (try_begin),
	    (eq, ":gender_1", 1),
	    (str_store_string, s11, "str_sister"),
	  (else_try),	
	    (str_store_string, s11, "str_brother"),
	  (try_end),
	(else_try),
	  (eq, ":guardian_of_2", ":troop_1"),
	  (assign, ":relation_strength", 10),
	  (try_begin),
	    (eq, ":gender_1", 1),
	    (str_store_string, s11, "str_sister"),
	  (else_try),	
	    (str_store_string, s11, "str_brother"),
	  (try_end),
	(else_try),
	  (eq, ":guardian_of_1", ":troop_2"),
	  (assign, ":relation_strength", 10),
	  (try_begin),
	    (eq, ":gender_1", 1),
	    (str_store_string, s11, "str_sister"),
	  (else_try),	
	    (str_store_string, s11, "str_brother"),
	  (try_end),		
	(else_try),
	  (gt, ":paternal_grandfather_of_1", -1),
	  (eq, ":paternal_grandfather_of_1", ":father_of_2"),
	  (assign, ":relation_strength", 4),
	  (try_begin),
	    (eq, ":gender_1", 1),
	    (str_store_string, s11, "str_niece"),
	  (else_try),
	    (str_store_string, s11, "str_nephew"),
	  (try_end),		
	(else_try), #specifically aunt and uncle by blood -- i assume that in a medieval society with lots of internal family conflicts, they would not include aunts and uncles by marriage
	  (gt, ":paternal_grandfather_of_2", -1),
	  (eq, ":paternal_grandfather_of_2", ":father_of_1"),	  
	  (assign, ":relation_strength", 4),	  
	  (try_begin),
	    (eq, ":gender_1", 1),
	    (str_store_string, s11, "str_aunt"),
	  (else_try),	
	    (str_store_string, s11, "str_uncle"),
	  (try_end),	
	(else_try),
	  (gt, ":paternal_grandfather_of_1", 0),
	  (eq, ":paternal_grandfather_of_2", ":paternal_grandfather_of_1"),
	  (assign, ":relation_strength", 2),
	  (str_store_string, s11, "str_cousin"),
   	(else_try),
   	  (eq, ":father_of_spouse_of_1", ":troop_2"),
   	  (assign, ":relation_strength", 5),
   	  (try_begin),
   	    (eq, ":gender_1", 1),
   	    (str_store_string, s11, "str_daughterinlaw"),
   	  (else_try),	
   	    (str_store_string, s11, "str_soninlaw"),
   	  (try_end),
	(else_try),
	  (eq, ":father_of_spouse_of_2", ":troop_1"),
	  (assign, ":relation_strength", 5),
	  (str_store_string, s11, "str_fatherinlaw"),
	(else_try),  
	  (eq, ":mother_of_spouse_of_2", ":troop_1"),
	  (neq, ":mother_of_spouse_of_2", "trp_player"), #May be necessary if mother for troops not set to -1
	  (assign, ":relation_strength", 5),
	  (str_store_string, s11, "str_motherinlaw"),

	(else_try),
	  (gt, ":father_of_spouse_of_1", -1), #necessary
	  (eq, ":father_of_spouse_of_1", ":father_of_2"),
	  (assign, ":relation_strength", 5),
	  (try_begin),
	    (eq, ":gender_1", 1),
	    (str_store_string, s11, "str_sisterinlaw"),
	  (else_try),	
	    (str_store_string, s11, "str_brotherinlaw"),	       
	  (try_end), 
	(else_try),
	  (gt, ":father_of_spouse_of_2", -1), #necessary
	  (eq, ":father_of_spouse_of_2", ":father_of_1"),
	  (assign, ":relation_strength", 5),
	  (try_begin),
	    (eq, ":gender_1", 1),
	    (str_store_string, s11, "str_sisterinlaw"),
	  (else_try),
	    (str_store_string, s11, "str_brotherinlaw"),
	  (try_end),
	(else_try),
	  (gt, ":spouse_of_2", -1), #necessary to avoid bug
	  (troop_slot_eq, ":spouse_of_2", slot_troop_guardian, ":troop_1"),
	  (assign, ":relation_strength", 5),
	  (try_begin),
	    (eq, ":gender_1", 1),
	    (str_store_string, s11, "str_sisterinlaw"),
	  (else_try),	
	    (str_store_string, s11, "str_brotherinlaw"),
	  (try_end),
	(else_try),
	  (gt, ":spouse_of_1", -1), #necessary to avoid bug
	  (troop_slot_eq, ":spouse_of_1", slot_troop_guardian, ":troop_2"),
	  (assign, ":relation_strength", 5),
	  (try_begin),
	    (eq, ":gender_1", 1),
	    (str_store_string, s11, "str_sisterinlaw"),
	  (else_try),	
	    (str_store_string, s11, "str_brotherinlaw"),
	  (try_end),		
	(try_end),
	
    (assign, reg4, ":gender_1"),
	(assign, reg0, ":relation_strength"),
	]),
  
  
  # script_complete_family_relations
  # Inputs: none
  # Outputs: none
  
  #complete family relations removed
  
  # 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)),

      (party_clear, "p_collective_ally"),
      (try_begin),
        (gt, "$g_ally_party", 0),
        (party_is_active, "$g_ally_party"),
        (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_clear, "p_collective_enemy"),
      (try_begin),
        (party_is_active, "$g_enemy_party"),
        (party_collect_attachments_to_party, "$g_enemy_party", "p_collective_enemy"),
      (try_end),
      (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", 0),
      (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", 0),
      (assign, "$g_starting_strength_enemy_party", reg0),
      (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", 0),
      (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.
	  
	  (try_begin),
		(gt, "$g_starting_strength_friends", 0), #this new to prevent occasional div by zero error 
		(val_div, "$g_strength_contribution_of_player","$g_starting_strength_friends"),
	  (else_try),
		(assign, "$g_strength_contribution_of_player", 100), #Or zero, maybe
	  (try_end),
	  
      (party_clear, "p_routed_enemies"), #new
      (assign, "$num_routed_us", 0),#newtoday
      (assign, "$num_routed_allies", 0),#newtoday
      (assign, "$num_routed_enemies", 0),#newtoday      
      (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_id", "p_main_party", ":i_stack"),
        (try_begin),
          (troop_set_slot, ":stack_troop_id", slot_troop_player_routed_agents, 0),
          #(troop_set_slot, ":stack_troop_id", slot_troop_enemy_routed_agents, 0),
          #(troop_set_slot, ":stack_troop_id", slot_troop_ally_routed_agents, 0),
        (try_end),
      (try_end),  

      (party_get_num_companion_stacks, ":num_stacks", "p_collective_friends"),
      (try_for_range, ":i_stack", 0, ":num_stacks"),
        (party_stack_get_troop_id, ":stack_troop_id", "p_collective_friends", ":i_stack"),
        (try_begin),
          #(troop_set_slot, ":stack_troop_id", slot_troop_player_routed_agents, 0),
          #(troop_set_slot, ":stack_troop_id", slot_troop_enemy_routed_agents, 0),
          (troop_set_slot, ":stack_troop_id", slot_troop_ally_routed_agents, 0),
        (try_end),
      (try_end),  

      (party_get_num_companion_stacks, ":num_stacks", "p_collective_enemy"),
      (try_for_range, ":i_stack", 0, ":num_stacks"),
        (party_stack_get_troop_id, ":stack_troop_id", "p_collective_enemy", ":i_stack"),
        (try_begin),
          #(troop_set_slot, ":stack_troop_id", slot_troop_player_routed_agents, 0),
          (troop_set_slot, ":stack_troop_id", slot_troop_enemy_routed_agents, 0),
          #(troop_set_slot, ":stack_troop_id", slot_troop_ally_routed_agents, 0),
        (try_end),
      (try_end),  

      (try_for_range, ":cur_faction", fac_kingdom_1, fac_kingdoms_end),
        (faction_set_slot, ":cur_faction", slot_faction_num_routed_agents, 0),
      (try_end),
      
      (assign, "$routed_party_added", 0), #new
      (party_clear, "p_total_enemy_casualties"), #new
      
#      (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", 0),
      (assign, ":main_party_strength", reg0),
      (call_script, "script_party_calculate_strength", "p_collective_enemy", 0),
      (assign, ":enemy_strength", reg0),
      (call_script, "script_party_calculate_strength", "p_collective_friends", 0),
      (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", ":party_no"),
  ##          (eq, ":party_faction", "fac_player_supporters_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, ":division_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_division, ":cur_agent_division", ":cur_agent"),
        (this_or_next|eq, ":division_no", grc_everyone),
        (eq, ":division_no", ":cur_agent_division"),
        (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"),
      (assign, reg10, ":num_stacks"),
      (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, s52, ":stack_troop"),
        (try_begin),
          (eq, ":i_stack", 1),
          (str_store_string, s51, "str_s52_and_s51"),
        (else_try),
          (gt, ":i_stack", 1),
          (str_store_string, s51, "str_s52_comma_s51"),
        (try_end),
      (try_end),
      (try_begin),
        (eq, ":num_stacks", 0),
        (str_store_string, s51, "str_noone"),
      (try_end),
  ]),

  # script_round_value
  # Input: arg1 = value
  # Output: reg0 = rounded_value
  ("round_value",
    [
      (store_script_param_1, ":value"),
      (try_begin),
        (lt, ":value", 100),
        (neq, ":value", 0),
        (val_add, ":value", 5),
        (val_div, ":value", 10),
        (val_mul, ":value", 10),
        (try_begin),
          (eq, ":value", 0),
          (assign, ":value", 5),
        (try_end),
      (else_try),
        (lt, ":value", 300),
        (val_add, ":value", 25),
        (val_div, ":value", 50),
        (val_mul, ":value", 50),
      (else_try),
        (val_add, ":value", 50),
        (val_div, ":value", 100),
        (val_mul, ":value", 100),
      (try_end),
      (assign, reg0, ":value"),
  ]),
  
  
##  # 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_and_chest
  # Input: none
  # Output: none
  ("change_banners_and_chest",
    [(party_get_slot, ":cur_leader", "$g_encountered_party", slot_town_lord),
     (try_begin),
       (ge, ":cur_leader", 0),
#normal_banner_begin
       (troop_get_slot, ":troop_banner_object", ":cur_leader", slot_troop_banner_scene_prop),
       (gt, ":troop_banner_object", 0),
       (replace_scene_props, banner_scene_props_begin, ":troop_banner_object"),
     (else_try),
       (replace_scene_props, banner_scene_props_begin, "spr_empty"),
#custom_banner_begin
#       (troop_get_slot, ":flag_spr", ":cur_leader", slot_troop_custom_banner_flag_type),
#       (ge, ":flag_spr", 0),
#       (val_add, ":flag_spr", custom_banner_flag_scene_props_begin),
#       (replace_scene_props, banner_scene_props_begin, ":flag_spr"),
#     (else_try),
#       (replace_scene_props, banner_scene_props_begin, "spr_empty"),
     (try_end),
     (try_begin),
       (neq, ":cur_leader", "trp_player"),
       (replace_scene_props, "spr_player_chest", "spr_locked_player_chest"),
     (try_end),
     ]),


  # script_remove_siege_objects
  # Input: none
  # Output: none
  ("remove_siege_objects",
    [
      (replace_scene_props, "spr_battlement_a_destroyed", "spr_battlement_a"),
      (replace_scene_props, "spr_snowy_castle_battlement_a_destroyed", "spr_snowy_castle_battlement_a"),
      (replace_scene_props, "spr_castle_e_battlement_a_destroyed", "spr_castle_e_battlement_a"),
      (replace_scene_props, "spr_castle_battlement_a_destroyed", "spr_castle_battlement_a"),
      (replace_scene_props, "spr_castle_battlement_b_destroyed", "spr_castle_battlement_b"),
      (replace_scene_props, "spr_earth_wall_a2", "spr_earth_wall_a"),
      (replace_scene_props, "spr_earth_wall_b2", "spr_earth_wall_b"),
      (replace_scene_props, "spr_belfry_platform_b", "spr_empty"),
      (replace_scene_props, "spr_belfry_platform_a", "spr_empty"),
      (replace_scene_props, "spr_belfry_a", "spr_empty"),
      (replace_scene_props, "spr_belfry_wheel", "spr_empty"),
      (replace_scene_props, "spr_siege_ladder_move_6m", "spr_empty"),
      (replace_scene_props, "spr_siege_ladder_move_8m", "spr_empty"),
      (replace_scene_props, "spr_siege_ladder_move_10m", "spr_empty"),
      (replace_scene_props, "spr_siege_ladder_move_12m", "spr_empty"),
      (replace_scene_props, "spr_siege_ladder_move_14m", "spr_empty"),
      (replace_scene_props, "spr_siege_ladder_12m", "spr_empty"),
      (replace_scene_props, "spr_siege_ladder_14m", "spr_empty"),
      (replace_scene_props, "spr_mangonel", "spr_empty"),
      (replace_scene_props, "spr_trebuchet_old", "spr_empty"),
      (replace_scene_props, "spr_trebuchet_new", "spr_empty"),
      (replace_scene_props, "spr_stone_ball", "spr_empty"),
      (replace_scene_props, "spr_Village_fire_big", "spr_empty"),
      ]),

  # 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),
      (val_clamp, ":str_offset", 0, 20),
      (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),
      (val_clamp, ":str_offset", 0, 20),
      (store_add, ":str_id", "str_center_relation_mnus_100",  ":str_offset"),
      (str_store_string, s3, ":str_id"),
  ]),


  # script_center_ambiance_sounds
  # Input: none
  # Output: none
  # to be called every two seconds
  ("center_ambiance_sounds",
    [
        (assign, ":sound_1", -1),
        (assign, ":sound_2", -1),
        (assign, ":sound_3", -1),
        (assign, ":sound_4", -1),
        (assign, ":sound_5", -1),
        (try_begin),
          (party_slot_eq, "$g_encountered_party", slot_party_type, spt_village),
          (try_begin),
            (neg|is_currently_night),
            (assign, ":sound_3", "snd_distant_dog_bark"),
            (assign, ":sound_3", "snd_distant_chicken"),
          (else_try),
            (assign, ":sound_1", "snd_distant_dog_bark"),
            (assign, ":sound_2", "snd_distant_owl"),
          (try_end),
        (else_try),
          (party_slot_eq, "$g_encountered_party", slot_party_type, spt_town),
          (try_begin),
            (neg|is_currently_night),
            (assign, ":sound_1", "snd_distant_carpenter"),
            (assign, ":sound_2", "snd_distant_blacksmith"),
            (assign, ":sound_3", "snd_distant_dog_bark"),
          (else_try),
            (assign, ":sound_1", "snd_distant_dog_bark"),
          (try_end),
        (try_end),
        (try_begin),
          (store_random_in_range, ":r", 0, 7),
          (try_begin),
            (eq, ":r", 1),
            (ge, ":sound_1", 0),
            (play_sound, ":sound_1"),
          (else_try),
            (eq, ":r", 2),
            (ge, ":sound_2", 0),
            (play_sound, ":sound_2"),
          (else_try),
            (eq, ":r", 3),
            (ge, ":sound_3", 0),
            (play_sound, ":sound_3"),
          (else_try),
            (eq, ":r", 4),
            (ge, ":sound_4", 0),
            (play_sound, ":sound_4"),
          (else_try),
            (eq, ":r", 5),
            (ge, ":sound_5", 0),
            (play_sound, ":sound_5"),
          (try_end),
        (try_end),
  ]),

  # script_center_set_walker_to_type
  # Input: arg1 = center_no, arg2 = walker_no, arg3 = walker_type, 
  # Output: none
  ("center_set_walker_to_type",
   [
       (store_script_param, ":center_no", 1),
       (store_script_param, ":walker_no", 2),
       (store_script_param, ":walker_type", 3),
       (store_add, ":type_slot", slot_center_walker_0_type, ":walker_no"),
       (party_set_slot, ":center_no", ":type_slot", ":walker_type"),
       (party_get_slot, ":center_faction", ":center_no", slot_center_original_faction),
       (faction_get_slot, ":center_culture", ":center_faction", slot_faction_culture),
       (store_random_in_range, ":walker_troop_slot", 0, 2),
       (try_begin),
         (party_slot_eq, ":center_no", slot_party_type, spt_village),
         (val_add, ":walker_troop_slot", slot_faction_village_walker_male_troop),
       (else_try),
         (val_add, ":walker_troop_slot", slot_faction_town_walker_male_troop),
       (try_end),
       (try_begin),
         (eq,":walker_type", walkert_spy),
         (assign,":original_walker_slot",":walker_troop_slot"),
         (val_add,":walker_troop_slot",4), # select spy troop id slot
       (try_end),
       (faction_get_slot, ":walker_troop_id", ":center_culture", ":walker_troop_slot"),
       (try_begin),
         (eq,":walker_type", walkert_spy),
         (faction_get_slot, ":original_walker", ":center_culture", ":original_walker_slot"),
         # restore spy inventory
         (try_for_range,":item_no","itm_horse_meat","itm_wooden_stick"),
            (store_item_kind_count,":num_items",":item_no",":original_walker"),
            (ge,":num_items",1),
            (store_item_kind_count,":num_items",":item_no",":walker_troop_id"),
            (lt,":num_items",1),
            (troop_add_items,":walker_troop_id",":item_no",1),
         (try_end),
         # determine spy recognition item
         (store_random_in_range,":spy_item_type",itp_type_head_armor,itp_type_hand_armor),
         (assign,":num",0),
         (try_for_range,":item_no","itm_horse_meat","itm_wooden_stick"),
            (store_item_kind_count,":num_items",":item_no",":walker_troop_id"),
            (ge,":num_items",1),
            (item_get_type, ":itp", ":item_no"),
            (eq,":itp",":spy_item_type"),
            (val_add,":num",1),
            (troop_remove_items,":walker_troop_id",":item_no",":num_items"),
         (try_end),
         (store_random_in_range,":random_item",0,":num"),
         (assign,":num",-1),
         (try_for_range,":item_no","itm_horse_meat","itm_wooden_stick"),
            (store_item_kind_count,":num_items",":item_no",":original_walker"),
            (ge,":num_items",1),
            (item_get_type, ":itp", ":item_no"),
            (eq,":itp",":spy_item_type"),
            (val_add,":num",1),
            (eq,":num",":random_item"),
            (troop_add_items,":walker_troop_id",":item_no",1),
            (assign,":spy_item",":item_no"),
         (try_end),
         (assign,"$spy_item_worn",":spy_item"),
         (assign,"$spy_quest_troop",":walker_troop_id"),
         (troop_equip_items,":walker_troop_id"),
       (try_end),
       (store_add, ":troop_slot", slot_center_walker_0_troop, ":walker_no"),
       (party_set_slot, ":center_no", ":troop_slot", ":walker_troop_id"),
       (store_random_in_range, ":walker_dna", 0, 1000000),
       (store_add, ":dna_slot", slot_center_walker_0_dna, ":walker_no"),
       (party_set_slot, ":center_no", ":dna_slot", ":walker_dna"),
     ]),


  # script_cf_center_get_free_walker
  # Input: arg1 = center_no
  # Output: reg0 = walker no (can fail)
  ("cf_center_get_free_walker",
   [
       (store_script_param, ":center_no", 1),
       (assign, ":num_free_walkers", 0),
       (try_for_range, ":walker_no", 0, num_town_walkers),
         (store_add, ":type_slot", slot_center_walker_0_type, ":walker_no"),
         (party_slot_eq, ":center_no", ":type_slot", walkert_default),
         (val_add, ":num_free_walkers", 1),
       (try_end),
       (gt, ":num_free_walkers", 0),
       (assign, reg0, -1),
       (store_random_in_range, ":random_rank", 0, ":num_free_walkers"),
       (try_for_range, ":walker_no", 0, num_town_walkers),
         (store_add, ":type_slot", slot_center_walker_0_type, ":walker_no"),
         (party_slot_eq, ":center_no", ":type_slot", walkert_default),
         (val_sub, ":num_free_walkers", 1),
         (eq, ":num_free_walkers", ":random_rank"),
         (assign, reg0, ":walker_no"),
       (try_end),
     ]),
    
  # script_center_remove_walker_type_from_walkers
  # Input: arg1 = center_no, arg2 = walker_type, 
  # Output: reg0 = 1 if comment found, 0 otherwise; s61 will contain comment string if found
  ("center_remove_walker_type_from_walkers",
   [
       (store_script_param, ":center_no", 1),
       (store_script_param, ":walker_type", 2),
       (try_for_range, ":walker_no", 0, num_town_walkers),
         (store_add, ":type_slot", slot_center_walker_0_type, ":walker_no"),
         (party_slot_eq, ":center_no", ":type_slot", ":walker_type"),
         (call_script, "script_center_set_walker_to_type", ":center_no", ":walker_no", walkert_default),
       (try_end),
     ]),
  
          
  # script_init_town_walkers
  # Input: none
  # Output: none
  ("init_town_walkers",
  [
    (try_begin),
      (eq, "$town_nighttime", 0),
      (try_for_range, ":walker_no", 0, num_town_walkers),
        (store_add, ":troop_slot", slot_center_walker_0_troop, ":walker_no"),
        (party_get_slot, ":walker_troop_id", "$current_town", ":troop_slot"),
        (gt, ":walker_troop_id", 0),
        (store_add, ":entry_no", town_walker_entries_start, ":walker_no"),
        (set_visitor, ":entry_no", ":walker_troop_id"),
      (try_end),  
    (try_end),  
  ]),


  # script_cf_enter_center_location_bandit_check
  # Input: none
  # Output: none
  ("cf_enter_center_location_bandit_check",
    [
      (neq, "$town_nighttime", 0),
      (party_slot_ge, "$current_town", slot_center_has_bandits, 1),
      (eq, "$g_defending_against_siege", 0),#Skip if the center is under siege (because of resting)
      (eq, "$sneaked_into_town", 0),#Skip if sneaked
      (try_begin),
        (party_slot_eq, "$current_town", slot_party_type, spt_village),
        (party_get_slot, ":cur_scene", "$current_town", slot_castle_exterior),
      (else_try),
        (party_get_slot, ":cur_scene", "$current_town", slot_town_center),
      (try_end),
      (modify_visitors_at_site, ":cur_scene"),
      (reset_visitors),
      (party_get_slot, ":bandit_troop", "$current_town", slot_center_has_bandits),
      (store_character_level, ":level", "trp_player"),

      (set_jump_mission, "mt_bandits_at_night"),
      (try_begin),
        (party_slot_eq, "$current_town", slot_party_type, spt_village),
        (assign, ":spawn_amount", 2),
        (store_div, ":level_fac",  ":level", 10),
        (val_add, ":spawn_amount", ":level_fac"),
        (try_for_range, ":unused", 0, 3),
          (gt, ":level", 10),
          (store_random_in_range, ":random_no", 0, 100),
          (lt, ":random_no", ":level"),
          (val_add, ":spawn_amount", 1),
        (try_end),
        (set_visitors, 4, ":bandit_troop", ":spawn_amount"),
        (assign, "$num_center_bandits", ":spawn_amount"),
        (set_jump_entry, 2),
      (else_try),
        (assign, ":spawn_amount", 1),
        (assign, "$num_center_bandits", 0),
        (try_begin),
          (gt, ":level", 15),
          (store_random_in_range, ":random_no", 0, 100),
          (lt, ":random_no", ":level"),
          (assign, ":spawn_amount", 2),
        (try_end),
        (val_add, "$num_center_bandits",  ":spawn_amount"),
        (set_visitors, 11, ":bandit_troop", ":spawn_amount"),
        (assign, ":spawn_amount", 1),
        (try_begin),
          (gt, ":level", 20),
          (store_random_in_range, ":random_no", 0, 100),
          (lt, ":random_no", ":level"),
          (assign, ":spawn_amount", 2),
        (try_end),
        (set_visitors, 27, ":bandit_troop", ":spawn_amount"),
        (val_add, "$num_center_bandits",  ":spawn_amount"),
        (try_begin),
          (gt, ":level", 9),
          (assign, ":spawn_amount", 1),
          (try_begin),
            (gt, ":level", 25),
            (store_random_in_range, ":random_no", 0, 100),
            (lt, ":random_no", ":level"),
            (assign, ":spawn_amount", 2),
          (try_end),
          (set_visitors, 28, ":bandit_troop", ":spawn_amount"),
          (val_add, "$num_center_bandits",  ":spawn_amount"),
        (try_end),
        (assign, "$town_entered", 1),
        (assign, "$all_doors_locked", 1),
      (try_end),

      (display_message, "@You have run into a trap!", 0xFFFF2222),
      (display_message, "@You are attacked by a group of bandits!", 0xFFFF2222),

      (jump_to_scene, ":cur_scene"),
      (change_screen_mission),
      ]),
  
  # script_init_town_agent
  # Input: none
  # Output: none
  ("init_town_agent",
    [
      (store_script_param, ":agent_no", 1),
      (agent_get_troop_id, ":troop_no", ":agent_no"),
      (set_fixed_point_multiplier, 100),
      (assign, ":stand_animation", -1),
      (try_begin),
        (this_or_next|is_between, ":troop_no", armor_merchants_begin, armor_merchants_end),
        (is_between, ":troop_no", weapon_merchants_begin, weapon_merchants_end),
        (try_begin),
          (troop_get_type, ":cur_troop_gender", ":troop_no"),
          (eq, ":cur_troop_gender", 0),
          (agent_set_animation, ":agent_no", "anim_stand_townguard"),
        (else_try),
          (agent_set_animation, ":agent_no", "anim_stand_townguard"),
        (end_try),
      (else_try),
        (is_between, ":troop_no", kingdom_ladies_begin, kingdom_ladies_end),
        (assign, ":stand_animation", "anim_stand_lady"),
      (else_try),
        (is_between, ":troop_no", active_npcs_begin, active_npcs_end),
        (assign, ":stand_animation", "anim_stand_lord"),
      (else_try),
        (is_between, ":troop_no", soldiers_begin, soldiers_end),
        (assign, ":stand_animation", "anim_stand_townguard"),
      (try_end),
      (try_begin),
        (ge, ":stand_animation", 0),
        (agent_set_stand_animation, ":agent_no", ":stand_animation"),
        (agent_set_animation, ":agent_no", ":stand_animation"),
        (store_random_in_range, ":random_no", 0, 100),
        (agent_set_animation_progress, ":agent_no", ":random_no"),
      (try_end),
      ]),

  # script_init_town_walker_agents
  # Input: none
  # Output: none
  ("init_town_walker_agents",
    [(assign, ":num_walkers", 0),
     (try_for_agents, ":cur_agent"),
       (agent_get_troop_id, ":cur_troop", ":cur_agent"),
       (is_between, ":cur_troop", walkers_begin, walkers_end),
       (val_add, ":num_walkers", 1),
       (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_agent_get_town_walker_details
  # This script assumes this is one of town walkers. 
  # Input: agent_id
  # Output: reg0: town_walker_type, reg1: town_walker_dna
  ("agent_get_town_walker_details",
    [(store_script_param, ":agent_no", 1),
     (agent_get_entry_no, ":entry_no", ":agent_no"),
     (store_sub, ":walker_no", ":entry_no", town_walker_entries_start),

     (store_add, ":type_slot", slot_center_walker_0_type, ":walker_no"),
     (party_get_slot, ":walker_type", "$current_town", ":type_slot"),
     (store_add, ":dna_slot", slot_center_walker_0_dna,  ":walker_no"),
     (party_get_slot, ":walker_dna", "$current_town", ":dna_slot"),
     (assign, reg0, ":walker_type"),
     (assign, reg1, ":walker_dna"),
     (assign, reg2, ":walker_no"),
  ]),


  ("town_walker_occupation_string_to_s14",
    [	
	(store_script_param, ":agent_no", 1),
	
	#Cairo, approx 1799:
	#adult males = 114,000
	#military, 10,400
	#civil, including religious 5,000
	#commerce 3,500
	#merchants 4,500
	#coffee shops, 1,500 (maybe broaden to inns and taverns)
	#artisans 21,800
	#workmen 4,300
	#itinerants 8,600
	#servants (inc water carriers) 26,400
	(assign, ":check_for_good_price", 0),
	(str_store_string, s14, "str_i_take_what_work_i_can_sirmadame_i_carry_water_or_help_the_merchants_with_their_loads_or_help_build_things_if_theres_things_to_be_built"),
	
	(call_script, "script_agent_get_town_walker_details", ":agent_no"),	
	(assign, ":type", reg0),
	(assign, ":walker_dna", reg1),
	
	(assign, ":item", -1),
	(assign, ":total_item_production", 0),
	(try_for_range, ":trade_good", trade_goods_begin, trade_goods_end),
		(call_script, "script_center_get_production", "$g_encountered_party", ":trade_good"),
		(val_add, ":total_item_production", reg0),
	(try_end),

	(val_max, ":total_item_production", 1),
	
	(store_mod, ":semi_random_number", ":walker_dna", ":total_item_production"),
	
	
	(try_begin),
		(eq, "$cheat_mode", 1),
		(assign, reg4, ":walker_dna"),
		(assign, reg5, ":total_item_production"),
		(assign, reg7, ":semi_random_number"), 
		(display_message, "str_dna_reg4_total_production_reg5_modula_reg7"),
	(try_end),
	
	(try_for_range, ":trade_good", trade_goods_begin, trade_goods_end),
		(gt, ":semi_random_number", -1),
		(call_script, "script_center_get_production", "$g_encountered_party", ":trade_good"),
		(val_sub, ":semi_random_number", reg0),
		(lt, ":semi_random_number", 0),
                (try_begin),
                  (eq, "$cheat_mode", 1),
		  (str_store_item_name, s9, ":trade_good"),
		  (display_message, "str_agent_produces_s9"),
                (try_end),
		(assign, ":item", ":trade_good"),
	(try_end),	
	
	
	(try_begin),
		(eq, ":type", walkert_needs_money),
		(is_between, "$g_encountered_party", towns_begin, towns_end),
		(str_store_string, s14, "str_im_not_doing_anything_sirmadame_theres_no_work_to_be_had_around_here_these_days"),
	(else_try),	
		(eq, ":type", walkert_needs_money),
		(str_store_string, s14, "str_im_not_doing_anything_sirmadame_i_have_no_land_of_my_own_and_theres_no_work_to_be_had_around_here_these_days"),
	(else_try),	
		(eq, ":type", walkert_needs_money_helped),
		(str_store_string, s14, "str_why_im_still_living_off_of_your_kindness_and_goodness_sirmadame_hopefully_there_will_be_work_shortly"),
	(else_try),
		(eq, ":item", "itm_grain"),
		(is_between, "$g_encountered_party", towns_begin, towns_end),
		(str_store_string, s14, "str_i_work_in_the_fields_just_outside_the_walls_where_they_grow_grain_we_dont_quite_grow_enough_to_meet_our_needs_though_and_have_to_import_grain_from_the_surrounding_countryside"),
		(assign, ":check_for_good_price", 1),
		
	(else_try),
		(eq, ":item", "itm_grain"),
		(str_store_string, s14, "str_i_work_mostly_in_the_fields_growing_grain_in_the_town_they_grind_it_to_make_bread_or_ale_and_we_can_also_boil_it_as_a_porridge"),
		(assign, ":check_for_good_price", 1),
		
	(else_try),	
		(eq, ":item", "itm_ale"),
		(str_store_string, s14, "str_i_work_in_the_breweries_making_ale_the_poor_folk_drink_a_lot_of_it_as_its_cheaper_than_wine_we_make_it_with_grain_brought_in_from_the_countryside"),
		(assign, ":check_for_good_price", 1),
		
	(else_try),	
		(eq, ":item", "itm_bread"),
		(str_store_string, s14, "str_i_work_in_a_mill_grinding_flour_to_make_bread_bread_is_cheap_keeps_well_and_fills_the_stomach"),
		(assign, ":check_for_good_price", 1),
		
	(else_try),	
		(eq, ":item", "itm_dried_meat"),
		(str_store_string, s14, "str_i_tend_cattle_we_dry_and_salt_meat_to_preserve_it_and_make_cheese_from_the_milk"),
		(assign, ":check_for_good_price", 1),
		
	(else_try),	
		(eq, ":item", "itm_cheese"),
		(str_store_string, s14, "str_i_tend_cattle_we_dry_and_salt_meat_to_preserve_it_and_make_cheese_from_the_milk_so_it_doesnt_spoil"),
		(assign, ":check_for_good_price", 1),
		
	(else_try),	
		(eq, ":item", "itm_butter"),
		(str_store_string, s14, "str_i_tend_cattle_we_dry_and_salt_meat_to_preserve_it_and_make_cheese_from_the_milk_so_it_doesnt_spoil"),
		(assign, ":check_for_good_price", 1),
		
	(else_try),	
		(eq, ":item", "itm_wool"),
		(str_store_string, s14, "str_i_tend_sheep_we_send_the_wool_to_the_cities_to_be_woven_into_cloth_and_make_mutton_sausage_when_we_cull_the_herds"),
		(assign, ":check_for_good_price", 1),
		
	(else_try),	
		(eq, ":item", "itm_sausages"),
		(str_store_string, s14, "str_i_tend_sheep_we_send_the_wool_to_the_cities_to_be_woven_into_cloth_and_make_mutton_sausage_when_we_cull_the_herds"),
		(assign, ":check_for_good_price", 1),
		
	(else_try),	
		(eq, ":item", "itm_wool_cloth"),
		(str_store_string, s14, "str_i_work_at_a_loom_spinning_cloth_from_wool_wool_is_some_of_the_cheapest_cloth_you_can_buy_but_it_will_still_keep_you_warm"),
		(assign, ":check_for_good_price", 1),
		
	(else_try),	
		(eq, ":item", "itm_smoked_fish"),
		(str_store_string, s14, "str_i_crew_a_fishing_boat_we_salt_and_smoke_the_flesh_to_sell_it_far_inland"),
		(assign, ":check_for_good_price", 1),
		
	(else_try),	
		(eq, ":item", "itm_salt"),
		(str_store_string, s14, "str_i_sift_salt_from_a_nearby_flat_they_need_salt_everywhere_to_preserve_meat_and_fish"),
		(assign, ":check_for_good_price", 1),
		
	(else_try),	
		(eq, ":item", "itm_iron"),
		(str_store_string, s14, "str_i_mine_iron_from_a_vein_in_a_nearby_cliffside_they_use_it_to_make_tools_arms_and_other_goods"),
		(assign, ":check_for_good_price", 1),
		
	(else_try),	
		(eq, ":item", "itm_pottery"),
		(str_store_string, s14, "str_i_make_pottery_which_people_use_to_store_grain_and_carry_water"),
		(assign, ":check_for_good_price", 1),
		
	(else_try),	
		(eq, ":item", "itm_tools"),
		(str_store_string, s14, "str_trade_explanation_tools"),
		(assign, ":check_for_good_price", 1),
		
	(else_try),	
		(eq, ":item", "itm_oil"),
		(str_store_string, s14, "str_trade_explanation_oil"),
		(assign, ":check_for_good_price", 1),
		
	(else_try),	
		(eq, ":item", "itm_linen"),
		(str_store_string, s14, "str_trade_explanation_linen"),
		(assign, ":check_for_good_price", 1),
		
	(else_try),	
		(eq, ":item", "itm_velvet"),
		(str_store_string, s14, "str_trade_explanation_velvet"),
		(assign, ":check_for_good_price", 1),
		
	(else_try),	
		(eq, ":item", "itm_spice"),
		(str_store_string, s14, "str_trade_explanation_spice"),
		(assign, ":check_for_good_price", 1),
		
	(else_try),	
		(eq, ":item", "itm_apples"),
		(str_store_string, s14, "str_trade_explanation_apples"),
		(assign, ":check_for_good_price", 1),
		
	(try_end),
	
	
	(try_begin),
		(eq, ":check_for_good_price", 1),
	
		(assign, ":trade_destination", -1),
		(store_skill_level, ":trade_skill", "skl_trade", "trp_player"),
	
		(try_begin),
			(is_between, "$g_encountered_party", villages_begin, villages_end),
			(party_get_slot, ":trade_town", "$g_encountered_party", slot_village_market_town),
		(else_try),	
			(assign, ":trade_town", "$g_encountered_party"),
		(try_end),
		
		(store_sub, ":item_to_price_slot", slot_town_trade_good_prices_begin, trade_goods_begin),
		(store_add, ":cur_good_price_slot", ":item", ":item_to_price_slot"),
		(party_get_slot, ":score_to_beat", ":trade_town", ":cur_good_price_slot"),
		(val_add, ":score_to_beat", 400),
		(store_mul, ":deduction_for_trade_skill", ":trade_skill", 35),
		(try_begin),
			(is_between, "$g_encountered_party", villages_begin, villages_end),
			(val_add, ":score_to_beat", 200),
		(try_end),
		(val_sub, ":score_to_beat", ":deduction_for_trade_skill"),
		
		(try_for_range, ":trade_route_slot", slot_town_trade_routes_begin, slot_town_trade_routes_end),
			(party_get_slot, ":other_town", ":trade_town", ":trade_route_slot"),
			(party_get_slot, ":price_in_other_town", ":other_town", ":cur_good_price_slot"),
			
			
			(try_begin),
				(eq, "$cheat_mode", 1),
				(assign, reg4, ":price_in_other_town"),
				(assign, reg5, ":score_to_beat"),
				(str_store_party_name, s10, ":other_town"),
				(display_message, "str_s10_has_reg4_needs_reg5"),
			(try_end),
			
			(gt, ":price_in_other_town", ":score_to_beat"),
		
			(assign, ":trade_destination", ":other_town"),
			(assign, ":score_to_beat", ":price_in_other_town"),
		(try_end),
		
		(is_between, ":trade_destination", centers_begin, centers_end),
		
		(str_store_party_name, s15, ":trade_destination"),
		(str_store_string, s14, "str_s14_i_hear_that_you_can_find_a_good_price_for_it_in_s15"),
		
		#Reasons -- raw material
		#Reason -- road cut
		#Reason -- villages looted
		
	(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", walkers_begin, 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", walkers_begin, 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, 0),
       (agent_set_speed_limit, ":agent_no", 5),
     (try_end),
  ]),

  # script_town_init_doors
  # Input: door_state (-1 = closed, 1 = open, 0 = use $town_nighttime)
  # Output: none (required for siege mission templates)
  ("town_init_doors",
   [(store_script_param, ":door_state", 1),
    (try_begin),
      (assign, ":continue", 0),
      (try_begin),
        (eq, ":door_state", 1),
        (assign, ":continue", 1),
      (else_try),
        (eq, ":door_state", 0),
        (eq, "$town_nighttime", 0),
        (assign, ":continue", 1),
      (try_end),
      (eq, ":continue", 1),# open doors
      (assign, ":end_cond", 1),
      (try_for_range, ":i_instance", 0, ":end_cond"),
        (scene_prop_get_instance, ":object", "spr_towngate_door_left", ":i_instance"),
        (ge, ":object", 0),
        (val_add, ":end_cond", 1),
        (prop_instance_get_position, pos1, ":object"),
        (position_rotate_z, pos1, -100),
        (prop_instance_animate_to_position, ":object", pos1, 1),
      (try_end),
      (assign, ":end_cond", 1),
      (try_for_range, ":i_instance", 0, ":end_cond"),
        (scene_prop_get_instance, ":object", "spr_towngate_rectangle_door_left", ":i_instance"),
        (ge, ":object", 0),
        (val_add, ":end_cond", 1),
        (prop_instance_get_position, pos1, ":object"),
        (position_rotate_z, pos1, -80),
        (prop_instance_animate_to_position, ":object", pos1, 1),
      (try_end),
      (assign, ":end_cond", 1),
      (try_for_range, ":i_instance", 0, ":end_cond"),
        (scene_prop_get_instance, ":object", "spr_towngate_door_right", ":i_instance"),
        (ge, ":object", 0),
        (val_add, ":end_cond", 1),
        (prop_instance_get_position, pos1, ":object"),
        (position_rotate_z, pos1, 100),
        (prop_instance_animate_to_position, ":object", pos1, 1),
      (try_end),
      (assign, ":end_cond", 1),
      (try_for_range, ":i_instance", 0, ":end_cond"),
        (scene_prop_get_instance, ":object", "spr_towngate_rectangle_door_right", ":i_instance"),
        (ge, ":object", 0),
        (val_add, ":end_cond", 1),
        (prop_instance_get_position, pos1, ":object"),
        (position_rotate_z, pos1, 80),
        (prop_instance_animate_to_position, ":object", pos1, 1),
      (try_end),
    (try_end),
  ]),

  # 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
    (try_begin),
      (scene_prop_get_instance, ":belfry_object_to_rotate", "spr_belfry_platform_a", 0),
    (try_end),
    
    #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", pos_belfry_begin),
      (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),

    (set_show_messages, 0),
    (team_give_order, "$attacker_team", grc_everyone, mordr_stand_ground),
    (team_give_order, "$attacker_team_2", grc_everyone, mordr_stand_ground),
    (set_show_messages, 1),
  ]),

  # 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, pos_belfry_begin),
    (position_transform_position_to_parent, pos5, pos4, pos_belfry_begin),
    (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, pos_belfry_begin),
      (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),

	# NE Building
	    (try_begin), # University upgrade stuff - Jinnai
      (faction_slot_eq, "fac_player_supporters_faction", slot_faction_state, sfs_active),
      (faction_slot_eq, "fac_player_supporters_faction", slot_faction_univ_belfry, 1),
      (val_div, ":belfry_speed", 2),
    (try_end),
	# NE end building
	
    (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", pos_belfry_begin),
          (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",
   [
##    (store_mission_timer_a, ":cur_seconds"),
    (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"),
        (agent_is_alive, ":cur_agent"),
        (agent_is_human, ":cur_agent"),
        (try_begin),
          (agent_get_slot, ":x_pos", ":cur_agent", slot_agent_target_x_pos),
          (neq, ":x_pos", 0),
          (agent_get_slot, ":y_pos", ":cur_agent", slot_agent_target_y_pos),
          (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"),
##          (this_or_next|eq, "$attacker_team", ":cur_agent_team"),
##          (             eq, "$attacker_team_2", ":cur_agent_team"),
##          (try_begin),
##            (gt, ":cur_seconds", 20),
##            (agent_get_position, pos1, ":cur_agent"),
##            (agent_set_scripted_destination, ":cur_agent", pos1, 0),
##          (else_try),
##            (try_begin),
##              (team_get_movement_order, ":order1", "$attacker_team", grc_infantry),
##              (team_get_movement_order, ":order2", "$attacker_team", grc_cavalry),
##              (team_get_movement_order, ":order3", "$attacker_team", grc_archers),
##              (this_or_next|neq, ":order1", mordr_stand_ground),
##              (this_or_next|neq, ":order2", mordr_stand_ground),
##              (neq, ":order3", mordr_stand_ground),
##              (set_show_messages, 0),
##              (team_give_order, "$attacker_team", grc_everyone, mordr_stand_ground),
##              (set_show_messages, 1),
##            (try_end),
##          (try_end),
        (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"),
          (this_or_next|eq, "$attacker_team", ":cur_agent_team"),
          (eq, "$attacker_team_2", ":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"),
          (this_or_next|eq, "$attacker_team", ":cur_agent_team"),
          (             eq, "$attacker_team_2", ":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),
      (set_show_messages, 0),
      (team_give_order, "$attacker_team", grc_everyone, mordr_charge),
      (set_show_messages, 1),
    (try_end),
    (eq, ":end_trigger", 1),
  ]),

  # script_siege_move_archers_to_archer_positions
  # Input: none
  # Output: none
  ("siege_move_archers_to_archer_positions",
   [
     (try_for_agents, ":agent_no"),
       (agent_is_alive, ":agent_no"),
       (agent_slot_eq, ":agent_no", slot_agent_is_not_reinforcement, 0),
       (agent_is_defender, ":agent_no"),
       (agent_get_class, ":agent_class", ":agent_no"),
       (agent_get_troop_id, ":agent_troop", ":agent_no"),
       (eq, ":agent_class", grc_archers),
       (try_begin),
         (agent_slot_eq, ":agent_no", slot_agent_target_entry_point, 0),
         (store_random_in_range, ":random_entry_point", 40, 44),
         (agent_set_slot, ":agent_no", slot_agent_target_entry_point, ":random_entry_point"),
       (try_end),
       (try_begin),
         (agent_get_position, pos0, ":agent_no"),
         (entry_point_get_position, pos1, ":random_entry_point"),
         (get_distance_between_positions, ":dist", pos0, pos1),
         (lt, ":dist", 300),
         (agent_clear_scripted_mode, ":agent_no"),
         (agent_set_slot, ":agent_no", slot_agent_is_in_scripted_mode, 0),
         (agent_set_slot, ":agent_no", slot_agent_is_not_reinforcement, 1),
         (str_store_troop_name, s1, ":agent_troop"),
         (assign, reg0, ":agent_no"),
#         (display_message, "@{s1} ({reg0}) reached pos"),
       (else_try),
         (agent_get_simple_behavior, ":agent_sb", ":agent_no"),
         (agent_get_combat_state, ":agent_cs", ":agent_no"),
         (this_or_next|eq, ":agent_sb", aisb_ranged),
         (eq, ":agent_sb", aisb_go_to_pos),#scripted mode
         (eq, ":agent_cs", 7), # 7 = no visible targets (state for ranged units)
         (try_begin),
           (agent_slot_eq, ":agent_no", slot_agent_is_in_scripted_mode, 0),
           (agent_set_scripted_destination, ":agent_no", pos1, 0),
           (agent_set_slot, ":agent_no", slot_agent_is_in_scripted_mode, 1),
           (str_store_troop_name, s1, ":agent_troop"),
           (assign, reg0, ":agent_no"),
#           (display_message, "@{s1} ({reg0}) moving to pos"),
         (try_end),
       (else_try),
         (try_begin),
           (agent_slot_eq, ":agent_no", slot_agent_is_in_scripted_mode, 1),
           (agent_clear_scripted_mode, ":agent_no"),
           (agent_set_slot, ":agent_no", slot_agent_is_in_scripted_mode, 0),
           (str_store_troop_name, s1, ":agent_troop"),
           (assign, reg0, ":agent_no"),
#           (display_message, "@{s1} ({reg0}) seeing target or changed mode"),
         (try_end),
       (try_end),
     (try_end),
     ]),


  # 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"),
    (team_get_hold_fire_order, ":cur_hold_fire", ":team_no", ":class_no"),
    (try_begin),
      (eq, ":cur_order", wordr_use_any_weapon),
      (eq, ":cur_hold_fire", aordr_fire_at_will),
      (str_store_string, s1, "@Any Weapon"),
    (else_try),
      (eq, ":cur_order", wordr_use_blunt_weapons),
      (eq, ":cur_hold_fire", aordr_fire_at_will),
      (str_store_string, s1, "@Blunt Weapons"),
    (else_try),
      (eq, ":cur_order", wordr_use_any_weapon),
      (eq, ":cur_hold_fire", aordr_hold_your_fire),
      (str_store_string, s1, "str_hold_fire"),
    (else_try),
      (eq, ":cur_order", wordr_use_blunt_weapons),
      (eq, ":cur_hold_fire", aordr_hold_your_fire),
      (str_store_string, s1, "str_blunt_hold_fire"),
    (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_group0_selected", 1),
      (team_give_order, ":team_no", 0, ":order"),
    (try_end),
    (try_begin),
      (eq, "$g_formation_group1_selected", 1),
      (team_give_order, ":team_no", 1, ":order"),
    (try_end),
    (try_begin),
      (eq, "$g_formation_group2_selected", 1),
      (team_give_order, ":team_no", 2, ":order"),
    (try_end),
    (try_begin),
      (eq, "$g_formation_group3_selected", 1),
      (team_give_order, ":team_no", 3, ":order"),
    (try_end),
    (try_begin),
      (eq, "$g_formation_group4_selected", 1),
      (team_give_order, ":team_no", 4, ":order"),
    (try_end),
    (try_begin),
      (eq, "$g_formation_group5_selected", 1),
      (team_give_order, ":team_no", 5, ":order"),
    (try_end),
    (try_begin),
      (eq, "$g_formation_group6_selected", 1),
      (team_give_order, ":team_no", 6, ":order"),
    (try_end),
    (try_begin),
      (eq, "$g_formation_group7_selected", 1),
      (team_give_order, ":team_no", 7, ":order"),
    (try_end),
    (try_begin),
      (eq, "$g_formation_group8_selected", 1),
      (team_give_order, ":team_no", 8, ":order"),
    (try_end),

    (try_begin),
      (eq, ":order", mordr_hold),
      (agent_get_position, pos1, ":leader_agent_no"),
      (try_begin),
        (eq, "$g_formation_group0_selected", 1),
        (team_set_order_position, ":team_no", 0, pos1),
      (try_end),
      (try_begin),
        (eq, "$g_formation_group1_selected", 1),
        (team_set_order_position, ":team_no", 1, pos1),
      (try_end),
      (try_begin),
        (eq, "$g_formation_group2_selected", 1),
        (team_set_order_position, ":team_no", 2, pos1),
      (try_end),
      (try_begin),
        (eq, "$g_formation_group3_selected", 1),
        (team_set_order_position, ":team_no", 3, pos1),
      (try_end),
      (try_begin),
        (eq, "$g_formation_group4_selected", 1),
        (team_set_order_position, ":team_no", 4, pos1),
      (try_end),
      (try_begin),
        (eq, "$g_formation_group5_selected", 1),
        (team_set_order_position, ":team_no", 5, pos1),
      (try_end),
      (try_begin),
        (eq, "$g_formation_group6_selected", 1),
        (team_set_order_position, ":team_no", 6, pos1),
      (try_end),
      (try_begin),
        (eq, "$g_formation_group7_selected", 1),
        (team_set_order_position, ":team_no", 7, pos1),
      (try_end),
      (try_begin),
        (eq, "$g_formation_group8_selected", 1),
        (team_set_order_position, ":team_no", 8, 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),

    #ozan added
    (try_begin),
      (eq, "$group0_has_troops", 1),
      (call_script, "script_store_movement_order_name_to_s1", ":team_no", 0),
      (overlay_set_text, "$g_presentation_but0_movement", s1),
      (call_script, "script_store_riding_order_name_to_s1", ":team_no", 0),
      (overlay_set_text, "$g_presentation_but0_riding", s1),
      (call_script, "script_store_weapon_usage_order_name_to_s1", ":team_no", 0),
      (overlay_set_text, "$g_presentation_but0_weapon_usage", s1),
    (try_end),
    (try_begin),
      (eq, "$group1_has_troops", 1),
      (call_script, "script_store_movement_order_name_to_s1", ":team_no", 1),
      (overlay_set_text, "$g_presentation_but1_movement", s1),
      (call_script, "script_store_riding_order_name_to_s1", ":team_no", 1),
      (overlay_set_text, "$g_presentation_but1_riding", s1),
      (call_script, "script_store_weapon_usage_order_name_to_s1", ":team_no", 1),
      (overlay_set_text, "$g_presentation_but1_weapon_usage", s1),
    (try_end),
    (try_begin),
      (eq, "$group2_has_troops", 1),
      (call_script, "script_store_movement_order_name_to_s1", ":team_no", 2),
      (overlay_set_text, "$g_presentation_but2_movement", s1),
      (call_script, "script_store_riding_order_name_to_s1", ":team_no", 2),
      (overlay_set_text, "$g_presentation_but2_riding", s1),
      (call_script, "script_store_weapon_usage_order_name_to_s1", ":team_no", 2),
      (overlay_set_text, "$g_presentation_but2_weapon_usage", s1),
    (try_end),
    (try_begin),
      (eq, "$group3_has_troops", 1),
      (call_script, "script_store_movement_order_name_to_s1", ":team_no", 3),
      (overlay_set_text, "$g_presentation_but3_movement", s1),
      (call_script, "script_store_riding_order_name_to_s1", ":team_no", 3),
      (overlay_set_text, "$g_presentation_but3_riding", s1),
      (call_script, "script_store_weapon_usage_order_name_to_s1", ":team_no", 3),
      (overlay_set_text, "$g_presentation_but3_weapon_usage", s1),
    (try_end),
    (try_begin),
      (eq, "$group4_has_troops", 1),
      (call_script, "script_store_movement_order_name_to_s1", ":team_no", 4),
      (overlay_set_text, "$g_presentation_but4_movement", s1),
      (call_script, "script_store_riding_order_name_to_s1", ":team_no", 4),
      (overlay_set_text, "$g_presentation_but4_riding", s1),
      (call_script, "script_store_weapon_usage_order_name_to_s1", ":team_no", 4),
      (overlay_set_text, "$g_presentation_but4_weapon_usage", s1),
    (try_end),
    (try_begin),
      (eq, "$group5_has_troops", 1),
      (call_script, "script_store_movement_order_name_to_s1", ":team_no", 5),
      (overlay_set_text, "$g_presentation_but5_movement", s1),
      (call_script, "script_store_riding_order_name_to_s1", ":team_no", 5),
      (overlay_set_text, "$g_presentation_but5_riding", s1),
      (call_script, "script_store_weapon_usage_order_name_to_s1", ":team_no", 5),
      (overlay_set_text, "$g_presentation_but5_weapon_usage", s1),
    (try_end),
    (try_begin),
      (eq, "$group6_has_troops", 1),
      (call_script, "script_store_movement_order_name_to_s1", ":team_no", 6),
      (overlay_set_text, "$g_presentation_but6_movement", s1),
      (call_script, "script_store_riding_order_name_to_s1", ":team_no", 6),
      (overlay_set_text, "$g_presentation_but6_riding", s1),
      (call_script, "script_store_weapon_usage_order_name_to_s1", ":team_no", 6),
      (overlay_set_text, "$g_presentation_but6_weapon_usage", s1),
    (try_end),
    (try_begin),
      (eq, "$group7_has_troops", 1),
      (call_script, "script_store_movement_order_name_to_s1", ":team_no", 7),
      (overlay_set_text, "$g_presentation_but7_movement", s1),
      (call_script, "script_store_riding_order_name_to_s1", ":team_no", 7),
      (overlay_set_text, "$g_presentation_but7_riding", s1),
      (call_script, "script_store_weapon_usage_order_name_to_s1", ":team_no", 7),
      (overlay_set_text, "$g_presentation_but7_weapon_usage", s1),
    (try_end),
    (try_begin),
      (eq, "$group8_has_troops", 1),
      (call_script, "script_store_movement_order_name_to_s1", ":team_no", 8),
      (overlay_set_text, "$g_presentation_but8_movement", s1),
      (call_script, "script_store_riding_order_name_to_s1", ":team_no", 8),
      (overlay_set_text, "$g_presentation_but8_riding", s1),
      (call_script, "script_store_weapon_usage_order_name_to_s1", ":team_no", 8),
      (overlay_set_text, "$g_presentation_but8_weapon_usage", s1),
    (try_end),

    #ozan added
    (assign, ":stat_position_y", 660),
    (try_begin),
      (position_set_y, pos1, ":stat_position_y"),
      (eq, "$group0_has_troops", 1),
      (position_set_x, pos1, 270),
      (overlay_set_position, "$g_presentation_but0_movement", pos1),
      (position_set_x, pos1, 410),
      (overlay_set_position, "$g_presentation_but0_riding", pos1),
      (position_set_x, pos1, 550),
      (overlay_set_position, "$g_presentation_but0_weapon_usage", pos1),
      (val_add, ":stat_position_y", -40),
    (try_end),
    (try_begin),
      (position_set_y, pos1, ":stat_position_y"),
      (eq, "$group1_has_troops", 1),
      (position_set_x, pos1, 270),
      (overlay_set_position, "$g_presentation_but1_movement", pos1),
      (position_set_x, pos1, 410),
      (overlay_set_position, "$g_presentation_but1_riding", pos1),
      (position_set_x, pos1, 550),
      (overlay_set_position, "$g_presentation_but1_weapon_usage", pos1),
      (val_add, ":stat_position_y", -40),
    (try_end),
    (try_begin),
      (position_set_y, pos1, ":stat_position_y"),
      (eq, "$group2_has_troops", 1),
      (position_set_x, pos1, 270),
      (overlay_set_position, "$g_presentation_but2_movement", pos1),
      (position_set_x, pos1, 410),
      (overlay_set_position, "$g_presentation_but2_riding", pos1),
      (position_set_x, pos1, 550),
      (overlay_set_position, "$g_presentation_but2_weapon_usage", pos1),
      (val_add, ":stat_position_y", -40),
    (try_end),
    (try_begin),
      (position_set_y, pos1, ":stat_position_y"),
      (eq, "$group3_has_troops", 1),
      (position_set_x, pos1, 270),
      (overlay_set_position, "$g_presentation_but3_movement", pos1),
      (position_set_x, pos1, 410),
      (overlay_set_position, "$g_presentation_but3_riding", pos1),
      (position_set_x, pos1, 550),
      (overlay_set_position, "$g_presentation_but3_weapon_usage", pos1),
      (val_add, ":stat_position_y", -40),
    (try_end),
    (try_begin),
      (position_set_y, pos1, ":stat_position_y"),
      (eq, "$group4_has_troops", 1),
      (position_set_x, pos1, 270),
      (overlay_set_position, "$g_presentation_but4_movement", pos1),
      (position_set_x, pos1, 410),
      (overlay_set_position, "$g_presentation_but4_riding", pos1),
      (position_set_x, pos1, 550),
      (overlay_set_position, "$g_presentation_but4_weapon_usage", pos1),
      (val_add, ":stat_position_y", -40),
    (try_end),
    (try_begin),
      (position_set_y, pos1, ":stat_position_y"),
      (eq, "$group5_has_troops", 1),
      (position_set_x, pos1, 270),
      (overlay_set_position, "$g_presentation_but5_movement", pos1),
      (position_set_x, pos1, 410),
      (overlay_set_position, "$g_presentation_but5_riding", pos1),
      (position_set_x, pos1, 550),
      (overlay_set_position, "$g_presentation_but5_weapon_usage", pos1),
      (val_add, ":stat_position_y", -40),
    (try_end),
    (try_begin),
      (position_set_y, pos1, ":stat_position_y"),
      (eq, "$group6_has_troops", 1),
      (position_set_x, pos1, 270),
      (overlay_set_position, "$g_presentation_but6_movement", pos1),
      (position_set_x, pos1, 410),
      (overlay_set_position, "$g_presentation_but6_riding", pos1),
      (position_set_x, pos1, 550),
      (overlay_set_position, "$g_presentation_but6_weapon_usage", pos1),
      (val_add, ":stat_position_y", -40),
    (try_end),
    (try_begin),
      (position_set_y, pos1, ":stat_position_y"),
      (eq, "$group7_has_troops", 1),
      (position_set_x, pos1, 270),
      (overlay_set_position, "$g_presentation_but7_movement", pos1),
      (position_set_x, pos1, 410),
      (overlay_set_position, "$g_presentation_but7_riding", pos1),
      (position_set_x, pos1, 550),
      (overlay_set_position, "$g_presentation_but7_weapon_usage", pos1),
      (val_add, ":stat_position_y", -40),
    (try_end),
    (try_begin),
      (position_set_y, pos1, ":stat_position_y"),
      (eq, "$group8_has_troops", 1),
      (position_set_x, pos1, 270),
      (overlay_set_position, "$g_presentation_but8_movement", pos1),
      (position_set_x, pos1, 410),
      (overlay_set_position, "$g_presentation_but8_riding", pos1),
      (position_set_x, pos1, 550),
      (overlay_set_position, "$g_presentation_but8_weapon_usage", pos1),
      (val_add, ":stat_position_y", -40),
    (try_end),
  ]),

  # 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_division, ":agent_division", ":agent_no"),
        (try_begin),
          (eq, ":agent_division", 0),
          (overlay_set_color, ":agent_overlay", 0x8d5220),
        (else_try),
          (eq, ":agent_division", 1),
          (overlay_set_color, ":agent_overlay", 0x34c6e4),
        (else_try),
          (eq, ":agent_division", 2),
          (overlay_set_color, ":agent_overlay", 0x569619),
        (else_try),
          (eq, ":agent_division", 3),
          (overlay_set_color, ":agent_overlay", 0xFFE500),
        (else_try),
          (eq, ":agent_division", 4),
          (overlay_set_color, ":agent_overlay", 0x990099),
        (else_try),
          (eq, ":agent_division", 5),
          (overlay_set_color, ":agent_overlay", 0x99FE80),
        (else_try),
          (eq, ":agent_division", 6),
          (overlay_set_color, ":agent_overlay", 0x9DEFFE),
        (else_try),
          (eq, ":agent_division", 7),
          (overlay_set_color, ":agent_overlay", 0xFECB9D),
        (else_try),
          (eq, ":agent_division", 8),
          (overlay_set_color, ":agent_overlay", 0xB19C9C),
        (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"),

    (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),
  ]),

  # 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),
      (eq, "$group0_has_troops", 1),
      (class_is_listening_order, ":player_team", 0),
      (overlay_set_val, "$g_presentation_obj_battle_check0", 1),
      (assign, "$g_formation_group0_selected", 1),
      (overlay_animate_to_alpha, "$g_presentation_obj_battle_but0", 250, 0x44),
    (else_try),
      (eq, "$group0_has_troops", 1),
      (overlay_set_val, "$g_presentation_obj_battle_check0", 0),
      (assign, "$g_formation_group0_selected", 0),
      (overlay_animate_to_alpha, "$g_presentation_obj_battle_but0", 250, 0),
    (try_end),
    (try_begin),
      (eq, "$group1_has_troops", 1),
      (class_is_listening_order, ":player_team", 1),
      (overlay_set_val, "$g_presentation_obj_battle_check1", 1),
      (assign, "$g_formation_group1_selected", 1),
      (overlay_animate_to_alpha, "$g_presentation_obj_battle_but1", 250, 0x44),
    (else_try),
      (eq, "$group1_has_troops", 1),
      (overlay_set_val, "$g_presentation_obj_battle_check1", 0),
      (assign, "$g_formation_group1_selected", 0),
      (overlay_animate_to_alpha, "$g_presentation_obj_battle_but1", 250, 0),
    (try_end),
    (try_begin),
      (eq, "$group2_has_troops", 1),
      (class_is_listening_order, ":player_team", 2),
      (overlay_set_val, "$g_presentation_obj_battle_check2", 1),
      (assign, "$g_formation_group2_selected", 1),
      (overlay_animate_to_alpha, "$g_presentation_obj_battle_but2", 250, 0x44),
    (else_try),
      (eq, "$group2_has_troops", 1),
      (overlay_set_val, "$g_presentation_obj_battle_check2", 0),
      (assign, "$g_formation_group2_selected", 0),
      (overlay_animate_to_alpha, "$g_presentation_obj_battle_but2", 250, 0),
    (try_end),
    (try_begin),
      (eq, "$group3_has_troops", 1),
      (class_is_listening_order, ":player_team", 3),
      (overlay_set_val, "$g_presentation_obj_battle_check3", 1),
      (assign, "$g_formation_group3_selected", 1),
      (overlay_animate_to_alpha, "$g_presentation_obj_battle_but3", 250, 0x44),
    (else_try),
      (eq, "$group3_has_troops", 1),
      (overlay_set_val, "$g_presentation_obj_battle_check3", 0),
      (assign, "$g_formation_group3_selected", 0),
      (overlay_animate_to_alpha, "$g_presentation_obj_battle_but3", 250, 0),
    (try_end),
    (try_begin),
      (eq, "$group4_has_troops", 1),
      (class_is_listening_order, ":player_team", 4),
      (overlay_set_val, "$g_presentation_obj_battle_check4", 1),
      (assign, "$g_formation_group4_selected", 1),
      (overlay_animate_to_alpha, "$g_presentation_obj_battle_but4", 250, 0x44),
    (else_try),
      (eq, "$group4_has_troops", 1),
      (overlay_set_val, "$g_presentation_obj_battle_check4", 0),
      (assign, "$g_formation_group4_selected", 0),
      (overlay_animate_to_alpha, "$g_presentation_obj_battle_but4", 250, 0),
    (try_end),
    (try_begin),
      (eq, "$group5_has_troops", 1),
      (class_is_listening_order, ":player_team", 5),
      (overlay_set_val, "$g_presentation_obj_battle_check5", 1),
      (assign, "$g_formation_group5_selected", 1),
      (overlay_animate_to_alpha, "$g_presentation_obj_battle_but5", 250, 0x44),
    (else_try),
      (eq, "$group5_has_troops", 1),
      (overlay_set_val, "$g_presentation_obj_battle_check5", 0),
      (assign, "$g_formation_group5_selected", 0),
      (overlay_animate_to_alpha, "$g_presentation_obj_battle_but5", 250, 0),
    (try_end),
    (try_begin),
      (eq, "$group6_has_troops", 1),
      (class_is_listening_order, ":player_team", 6),
      (overlay_set_val, "$g_presentation_obj_battle_check6", 1),
      (assign, "$g_formation_group6_selected", 1),
      (overlay_animate_to_alpha, "$g_presentation_obj_battle_but6", 250, 0x44),
    (else_try),
      (eq, "$group6_has_troops", 1),
      (overlay_set_val, "$g_presentation_obj_battle_check6", 0),
      (assign, "$g_formation_group6_selected", 0),
      (overlay_animate_to_alpha, "$g_presentation_obj_battle_but6", 250, 0),
    (try_end),
    (try_begin),
      (eq, "$group7_has_troops", 1),
      (class_is_listening_order, ":player_team", 7),
      (overlay_set_val, "$g_presentation_obj_battle_check7", 1),
      (assign, "$g_formation_group7_selected", 1),
      (overlay_animate_to_alpha, "$g_presentation_obj_battle_but7", 250, 0x44),
    (else_try),
      (eq, "$group7_has_troops", 1),
      (overlay_set_val, "$g_presentation_obj_battle_check7", 0),
      (assign, "$g_formation_group7_selected", 0),
      (overlay_animate_to_alpha, "$g_presentation_obj_battle_but7", 250, 0),
    (try_end),
    (try_begin),
      (eq, "$group8_has_troops", 1),
      (class_is_listening_order, ":player_team", 8),
      (overlay_set_val, "$g_presentation_obj_battle_check8", 1),
      (assign, "$g_formation_group8_selected", 1),
      (overlay_animate_to_alpha, "$g_presentation_obj_battle_but8", 250, 0x44),
    (else_try),
      (eq, "$group8_has_troops", 1),
      (overlay_set_val, "$g_presentation_obj_battle_check8", 0),
      (assign, "$g_formation_group8_selected", 0),
      (overlay_animate_to_alpha, "$g_presentation_obj_battle_but8", 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_group0", 0),
    (assign, ":num_us_ready_group1", 0),
    (assign, ":num_us_ready_group2", 0),
    (assign, ":num_us_ready_group3", 0),
    (assign, ":num_us_ready_group4", 0),
    (assign, ":num_us_ready_group5", 0),
    (assign, ":num_us_ready_group6", 0),
    (assign, ":num_us_ready_group7", 0),
    (assign, ":num_us_ready_group8", 0),

    (assign, ":num_us_ready_men", 0),
    (assign, ":num_us_wounded_men", 0),
    (assign, ":num_us_routed_men", 0),
    (assign, ":num_us_dead_men", 0),
    (assign, ":num_allies_ready_men", 0),
    (assign, ":num_allies_wounded_men", 0),
    (assign, ":num_allies_routed_men", 0),
    (assign, ":num_allies_dead_men", 0),
    (assign, ":num_enemies_ready_men", 0),
    (assign, ":num_enemies_wounded_men", 0),
    (assign, ":num_enemies_routed_men", 0),
    (assign, ":num_enemies_dead_men", 0),

    (get_scene_boundaries, pos2, pos3),

    (try_for_agents,":cur_agent"),
      (agent_is_human, ":cur_agent"),
      (agent_get_division, ":agent_division", ":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_division", 0),
            (val_add, ":num_us_ready_group0", 1),
            (eq, "$group0_has_troops", 1), #added to solve problem. test this.
          (else_try),
            (eq, ":agent_division", 1),
            (val_add, ":num_us_ready_group1", 1),
            (eq, "$group1_has_troops", 1), #added to solve problem.
          (else_try),
            (eq, ":agent_division", 2),
            (val_add, ":num_us_ready_group2", 1),
            (eq, "$group2_has_troops", 1), #added to solve problem.
          (else_try),
            (eq, ":agent_division", 3),
            (val_add, ":num_us_ready_group3", 1),
            (eq, "$group3_has_troops", 1), #added to solve problem.
          (else_try),
            (eq, ":agent_division", 4),
            (val_add, ":num_us_ready_group4", 1),
            (eq, "$group4_has_troops", 1), #added to solve problem.
          (else_try),
            (eq, ":agent_division", 5),
            (val_add, ":num_us_ready_group5", 1),
            (eq, "$group5_has_troops", 1), #added to solve problem.
          (else_try),
            (eq, ":agent_division", 6),
            (val_add, ":num_us_ready_group6", 1),
            (eq, "$group6_has_troops", 1), #added to solve problem.
          (else_try),
            (eq, ":agent_division", 7),
            (val_add, ":num_us_ready_group7", 1),
            (eq, "$group7_has_troops", 1), #added to solve problem.
          (else_try),
            (eq, ":agent_division", 8),
            (val_add, ":num_us_ready_group8", 1),
            (eq, "$group8_has_troops", 1), #added to solve problem.
          (try_end),
          (val_add, ":num_us_ready_men", 1),
        (else_try),
          (overlay_set_alpha, ":agent_overlay", 0),
          (agent_is_wounded, ":cur_agent"),
          (val_add, ":num_us_wounded_men", 1),
        (else_try),
          (agent_is_routed, ":cur_agent"),
          (val_add, ":num_us_routed_men", 1),
        (else_try),
          (val_add, ":num_us_dead_men", 1),
        (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),
          (agent_is_routed, ":cur_agent"),
          (val_add, ":num_allies_routed_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),
          (agent_is_routed, ":cur_agent"),
          (val_add, ":num_enemies_routed_men", 1),
        (else_try),
          (val_add, ":num_enemies_dead_men", 1),
        (try_end),
      (try_end),
    (try_end),
    
    (assign, reg1, ":num_us_ready_group0"),
    (assign, reg2, ":num_us_ready_group1"),
    (assign, reg3, ":num_us_ready_group2"),
    (assign, reg4, ":num_us_ready_group3"),
    (assign, reg5, ":num_us_ready_group4"),
    (assign, reg6, ":num_us_ready_group5"),
    (assign, reg7, ":num_us_ready_group6"),
    (assign, reg8, ":num_us_ready_group7"),
    (assign, reg9, ":num_us_ready_group8"),
    (assign, reg10, ":num_us_ready_men"),
    (assign, reg11, ":num_us_wounded_men"),
    (assign, reg12, ":num_us_routed_men"),
    (assign, reg13, ":num_us_dead_men"),
    (assign, reg14, ":num_allies_ready_men"),
    (assign, reg15, ":num_allies_wounded_men"),
    (assign, reg16, ":num_allies_routed_men"),
    (assign, reg17, ":num_allies_dead_men"),
    (assign, reg18, ":num_enemies_ready_men"),
    (assign, reg19, ":num_enemies_wounded_men"),
    (assign, reg20, ":num_enemies_routed_men"),
    (assign, reg21, ":num_enemies_dead_men"),

    (try_begin),
      (eq, "$group0_has_troops", 1),
      (str_store_class_name, s1, 0),
      (overlay_set_text, "$g_presentation_obj_battle_name0", "str_s1_reg1"),
    (try_end),
    (try_begin),
      (eq, "$group1_has_troops", 1),
      (str_store_class_name, s1, 1),
      (overlay_set_text, "$g_presentation_obj_battle_name1", "str_s1_reg2"),
    (try_end),
    (try_begin),
      (eq, "$group2_has_troops", 1),
      (str_store_class_name, s1, 2),
      (overlay_set_text, "$g_presentation_obj_battle_name2", "str_s1_reg3"),
    (try_end),
    (try_begin),
      (eq, "$group3_has_troops", 1),
      (str_store_class_name, s1, 3),
      (overlay_set_text, "$g_presentation_obj_battle_name3", "str_s1_reg4"),
    (try_end),
    (try_begin),
      (eq, "$group4_has_troops", 1),
      (str_store_class_name, s1, 4),
      (overlay_set_text, "$g_presentation_obj_battle_name4", "str_s1_reg5"),
    (try_end),
    (try_begin),
      (eq, "$group5_has_troops", 1),
      (str_store_class_name, s1, 5),
      (overlay_set_text, "$g_presentation_obj_battle_name5", "str_s1_reg6"),
    (try_end),
    (try_begin),
      (eq, "$group6_has_troops", 1),
      (str_store_class_name, s1, 6),
      (overlay_set_text, "$g_presentation_obj_battle_name6", "str_s1_reg7"),
    (try_end),
    (try_begin),
      (eq, "$group7_has_troops", 1),
      (str_store_class_name, s1, 7),
      (overlay_set_text, "$g_presentation_obj_battle_name7", "str_s1_reg8"),
    (try_end),
    (try_begin),
      (eq, "$group8_has_troops", 1),
      (str_store_class_name, s1, 8),
      (overlay_set_text, "$g_presentation_obj_battle_name8", "str_s1_reg9"),
    (try_end),
    
    (overlay_set_text, "$g_battle_us_ready", "@{!}{reg10}"),
    (overlay_set_text, "$g_battle_us_wounded", "@{!}{reg11}"),
    (overlay_set_text, "$g_battle_us_routed", "@{!}{reg12}"),
    (overlay_set_text, "$g_battle_us_dead", "str_reg13"),
    (overlay_set_text, "$g_battle_allies_ready", "str_reg14"),
    (overlay_set_text, "$g_battle_allies_wounded", "str_reg15"),
    (overlay_set_text, "$g_battle_allies_routed", "str_reg16"),
    (overlay_set_text, "$g_battle_allies_dead", "str_reg17"),
    (overlay_set_text, "$g_battle_enemies_ready", "str_reg18"),
    (overlay_set_text, "$g_battle_enemies_wounded", "str_reg19"),
    (overlay_set_text, "$g_battle_enemies_routed", "str_reg20"),
    (overlay_set_text, "$g_battle_enemies_dead", "str_reg21"),

    (assign, ":stat_position_x", 675),
    (assign, ":stat_position_y", 280),
    (val_add, ":stat_position_x", 70),
    (val_add, ":stat_position_y", 60),
    (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", 70),
    (position_set_x, pos1, ":stat_position_x"),
    (overlay_set_position, "$g_battle_us_wounded", pos1),
    (val_add, ":stat_position_x", 70),
    (position_set_x, pos1, ":stat_position_x"),
    (overlay_set_position, "$g_battle_us_routed", pos1),
    (val_add, ":stat_position_x", 70),
    (position_set_x, pos1, ":stat_position_x"),
    (overlay_set_position, "$g_battle_us_dead", pos1),
    (val_add, ":stat_position_x", -210),
    (val_add, ":stat_position_y", -30),
    (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", 70),
    (position_set_x, pos1, ":stat_position_x"),
    (overlay_set_position, "$g_battle_allies_wounded", pos1),
    (val_add, ":stat_position_x", 70),
    (position_set_x, pos1, ":stat_position_x"),
    (overlay_set_position, "$g_battle_allies_routed", pos1),
    (val_add, ":stat_position_x", 70),
    (position_set_x, pos1, ":stat_position_x"),
    (overlay_set_position, "$g_battle_allies_dead", pos1),
    (val_add, ":stat_position_x", -210),
    (val_add, ":stat_position_y", -30),
    (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", 70),
    (position_set_x, pos1, ":stat_position_x"),
    (overlay_set_position, "$g_battle_enemies_wounded", pos1),
    (val_add, ":stat_position_x", 70),
    (position_set_x, pos1, ":stat_position_x"),
    (overlay_set_position, "$g_battle_enemies_routed", pos1),
    (val_add, ":stat_position_x", 70),
    (position_set_x, pos1, ":stat_position_x"),
    (overlay_set_position, "$g_battle_enemies_dead", pos1),

    (call_script, "script_update_order_flags_on_map"),
  ]),

 # script_set_town_picture
  # Input: none
  # Output: none
  ("set_town_picture",
   [
        (try_begin),
          (party_get_current_terrain, ":cur_terrain", "$current_town"),
          (party_slot_eq,"$current_town",slot_party_type, spt_town),
          (try_begin),
            (this_or_next|eq, ":cur_terrain", rt_steppe),
            (this_or_next|eq, ":cur_terrain", rt_steppe_forest),
            (this_or_next|eq, ":cur_terrain", rt_desert),
            (             eq, ":cur_terrain", rt_desert_forest),
            (set_background_mesh, "mesh_pic_towndes"),
          (else_try),
            (this_or_next|eq, ":cur_terrain", rt_snow),
            (             eq, ":cur_terrain", rt_snow_forest),
            (set_background_mesh, "mesh_pic_townsnow"),
          (else_try),
            (set_background_mesh, "mesh_pic_town1"),
          (try_end),
        (else_try),
          (try_begin),
            (this_or_next|eq, ":cur_terrain", rt_steppe),
            (this_or_next|eq, ":cur_terrain", rt_steppe_forest),
            (this_or_next|eq, ":cur_terrain", rt_desert),
            (             eq, ":cur_terrain", rt_desert_forest),
            (set_background_mesh, "mesh_pic_castledes"),
          (else_try),
            (this_or_next|eq, ":cur_terrain", rt_snow),
            (             eq, ":cur_terrain", rt_snow_forest),
            (set_background_mesh, "mesh_pic_castlesnow"),
          (else_try),
            (set_background_mesh, "mesh_pic_castle1"),
          (try_end),
        (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", food_begin, food_end),
      (troop_get_inventory_slot_modifier, ":item_modifier", "trp_player", ":cur_slot"),
      (neq, ":item_modifier", imod_rotten),
      (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"),
      (call_script, "script_troop_get_player_relation", ":faction_leader"),
      (assign, ":leader_relation", reg0),
      #(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
  #Now ONLY called from the start
  ("assign_lords_to_empty_centers",
   [
   
    (try_begin),
		(eq, "$cheat_mode", 1),		
		(display_message, "str_assigning_lords_to_empty_centers"),
		(str_store_string, s65, "str_assign_lords_to_empty_centers_just_happened"),
		(call_script, "script_add_notification_menu", "mnu_debug_alert_from_s65", 0, 0),
    (try_end),
   
	(try_for_range, ":faction", kingdoms_begin, kingdoms_end),
		(faction_set_slot, ":faction", slot_faction_temp_slot, 0),
    (try_end),

	(try_for_range, ":active_npc", 0, active_npcs_end),
		(troop_set_slot, ":active_npc", slot_troop_temp_slot, 0),
    (try_end),
   
    #Factions will keep one unassigned center in reserve, unless they have landless lords
    (try_for_range, ":cur_center", centers_begin, centers_end),
	    (party_get_slot, ":center_lord", ":cur_center", slot_town_lord),
		(try_begin),
			(this_or_next|eq, ":center_lord", stl_unassigned),
				(eq, ":center_lord", stl_rejected_by_player),
			(store_faction_of_party, ":center_faction", ":cur_center"),
			
			(try_begin),
				(eq, "$cheat_mode", 1),
				(str_store_party_name, s4, ":cur_center"),
				(str_store_faction_name, s5, ":center_faction"),
				(display_message, "str_s4_of_the_s5_is_unassigned"),
			(try_end),
		
			(faction_get_slot, ":number_of_unassigned_centers_plus_landless_lords", ":center_faction", slot_faction_temp_slot),
			(val_add, ":number_of_unassigned_centers_plus_landless_lords", 1),
			(faction_set_slot,  ":center_faction", slot_faction_temp_slot, ":number_of_unassigned_centers_plus_landless_lords"),
		(else_try),
			(eq, ":center_lord", stl_reserved_for_player),

			(try_begin),
				(eq, "$cheat_mode", 1),
				(str_store_party_name, s4, ":cur_center"),
				(str_store_faction_name, s5, ":center_faction"),
				(display_message, "str_s4_of_the_s5_is_reserved_for_player"),
			(try_end),
			
		(else_try),
			(ge, ":center_lord", 0),
			(troop_set_slot, ":center_lord", slot_troop_temp_slot, 1),
		(try_end),	
	(try_end),
   
	(try_for_range, ":active_npc", 0, active_npcs_end),
		(troop_slot_eq, ":active_npc", slot_troop_occupation, slto_kingdom_hero),
		(this_or_next|gt, ":active_npc", "trp_player"),
			(eq, "$player_has_homage", 1),
			
		(troop_slot_eq, ":active_npc", slot_troop_temp_slot, 0),
		(store_faction_of_troop, ":npc_faction", ":active_npc"),

		(is_between, ":npc_faction", npc_kingdoms_begin, npc_kingdoms_end),
	
		(try_begin),
			(eq, "$cheat_mode", 1),
			(str_store_troop_name, s4, ":active_npc"),
			(str_store_faction_name, s5, ":npc_faction"),
			(display_message, "str_s4_of_the_s5_has_no_fiefs"),
		(try_end),
	
		(faction_get_slot, ":number_of_unassigned_centers_plus_landless_lords", ":npc_faction", slot_faction_temp_slot),
		(val_add, ":number_of_unassigned_centers_plus_landless_lords", 1),
		(faction_set_slot,  ":npc_faction", slot_faction_temp_slot, ":number_of_unassigned_centers_plus_landless_lords"),
	(try_end),
   
   	(try_begin),
	  (eq, "$cheat_mode", 1),
 	  (try_for_range, ":faction", kingdoms_begin, kingdoms_end),
		(faction_get_slot, reg4, ":faction", slot_faction_temp_slot),
		(str_store_faction_name, s4, ":faction"),
		(display_message, "str_s4_unassigned_centers_plus_landless_lords_=_reg4"),
	  (try_end),
    (try_end),
   
	(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"),
        
        (try_begin),
	      (eq, "$cheat_mode", 1),
		  (str_store_party_name, s5, ":cur_center"),
	      (try_begin),
			(neg|faction_slot_ge, ":center_faction", slot_faction_temp_slot, 2),
			(str_store_faction_name, s4, ":center_faction"),
			(display_message, "str_s4_holds_s5_in_reserve"),
		  (try_end),
        (try_end),
	  
		(faction_slot_ge, ":center_faction", slot_faction_temp_slot, 2),
		
		#(display_message, "@Considering grant of {s5}"),

		(assign, ":best_lord", -1),
		(assign, ":best_lord_score", -1),
		(try_begin),
			(eq, ":center_lord", stl_unassigned),
			(try_begin),
				(eq, "$players_kingdom", ":center_faction"),
				(eq, "$player_has_homage", 1),
				(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", active_npcs_begin, active_npcs_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),

			#This prioritizes granting of centers for troops which do not already have one
			(try_begin),
				(troop_slot_eq, ":cur_troop", slot_troop_temp_slot, 0),
				(is_between, ":cur_center", villages_begin, villages_end),
				(val_mul, ":score", 10),
			(try_end),
			
			(gt, ":score", ":best_lord_score"),
			(assign, ":best_lord_score", ":score"),
			(assign, ":best_lord", ":cur_troop"),
		(try_end),
	  
	    #Adjust count of centers and lords
 		(try_begin),
			(this_or_next|ge, ":best_lord", 0),
				(eq, ":best_lord", stl_reserved_for_player),
				
			(faction_get_slot, ":landless_lords_plus_unassigned_centers", ":center_faction", slot_faction_temp_slot),
			(val_sub, ":landless_lords_plus_unassigned_centers", 1),
			
			(try_begin),
				(eq, ":best_lord", stl_reserved_for_player),
				(troop_slot_eq, "trp_player", slot_troop_temp_slot, 0),
				(troop_set_slot, "trp_player", slot_troop_temp_slot, 1),
				(val_sub, ":landless_lords_plus_unassigned_centers", 1), 			
			(else_try),
				(troop_slot_eq, ":best_lord", slot_troop_temp_slot, 0),
				(troop_set_slot, ":best_lord", slot_troop_temp_slot, 1),
				(val_sub, ":landless_lords_plus_unassigned_centers", 1), 			
			(try_end),
			
			(faction_set_slot, ":center_faction", slot_faction_temp_slot, ":landless_lords_plus_unassigned_centers"),
		(try_end),
	  
	    #Give the center to the lord
		(try_begin),
			(ge, ":best_lord", 0),
			(call_script, "script_give_center_to_lord", ":cur_center", ":best_lord", 1),
		(else_try),
			(eq, ":best_lord", stl_reserved_for_player),
			(party_set_slot, ":cur_center", slot_town_lord, stl_reserved_for_player),
			(try_begin), #grant bound villages to player, if granting a castle
				(party_slot_eq, ":cur_center", slot_party_type, spt_castle),
#				(assign, ":give_at_least_one_village", 0),
				(try_for_range, ":cur_village", villages_begin, villages_end),
#					(eq, ":give_at_least_one_village", 0),
					(party_slot_eq, ":cur_village", slot_village_bound_center, ":cur_center"),
					(party_slot_eq, ":cur_village", slot_town_lord, stl_unassigned),
					(party_set_slot, ":cur_village", slot_town_lord, stl_reserved_for_player),
#					(assign, ":give_at_least_one_village", 1),
				(try_end),
			(try_end),
		(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", ":town_no"),

	
#    (store_faction_of_party, ":town_faction", ":town_no"),
#    (try_begin),
#		(neq, ":town_faction", ":party_faction"),
#		(assign, ":town_no", -1),
#		(assign, ":score_to_beat", 9999),
#		(try_for_range, ":other_town", towns_begin, towns_end),
#			(store_faction_of_party, ":other_town_faction", ":town_no"),
#			(store_relation, ":relation", ":other_town_faction", ":party_faction"),
#			(ge, ":relation", 0),
			
#			(store_distance_to_party_from_party, ":distance", ":village_no", ":other_town"),
#			(lt, ":distance", ":score_to_beat"),
#			(assign, ":town_no", ":other_town"),
#			(assign, ":score_to_beat", ":distance"),
#		(try_end),
#	(try_end),
	
	(try_begin),
		(is_between, ":town_no", towns_begin, towns_end),
	    (set_spawn_radius, 0),
	    (spawn_around_party, ":village_no", "pt_village_farmers"),
	    (assign, ":new_party", reg0),
	      
	    (party_set_faction, ":new_party", ":party_faction"),
	    (party_set_slot, ":new_party", slot_party_home_center, ":village_no"),
	    (party_set_slot, ":new_party", slot_party_last_traded_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"),
	(try_end),
	
    ]),

  #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), #this should probably always be a constant. Currently it is 25
	  (assign, ":percentage_change", 30),

	  (party_get_slot, ":origin", ":party_no", slot_party_last_traded_center),
	  (party_set_slot, ":party_no", slot_party_last_traded_center, ":center_no"),
	  
      (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),
		
		#This is to reconvert from absolute value
        (try_begin),
          (lt, ":price_dif", 0),
          (val_mul, ":cur_change", -1),
        (try_end),

		#The new price for the caravan or peasant is set before the change, so the prices in the trading town have full effect on the next center 
        (party_set_slot, ":party_no", ":cur_good_price_slot", ":cur_center_price"),
		
        (val_add, ":cur_center_price", ":cur_change"),
        (party_set_slot, ":center_no", ":cur_good_price_slot", ":cur_center_price"),
				
		(try_begin),
			(eq, "$cheat_mode", 3),
			(str_store_party_name, s3, ":origin"),
			(str_store_party_name, s4, ":center_no"),
			(str_store_item_name, s5, ":cur_good"),
			(assign, reg4, ":cur_change"),
			(assign, reg5, ":cur_center_price"),
			(display_message, "@{!}DEBUG -- Trade of {s5} from {s3} to {s4} brings price from {reg4} to  {reg5}"),
		(try_end),
		
      (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"),
      (faction_set_slot, "fac_player_supporters_faction", slot_faction_ai_state, sfai_default),
      (assign, "$players_oath_renounced_against_kingdom", 0),
      (assign, "$players_oath_renounced_given_center", 0),
      (assign, "$players_oath_renounced_begin_time", 0),
      
      (try_for_range,":other_kingdom",kingdoms_begin,kingdoms_end),
        (faction_slot_eq, ":other_kingdom", slot_faction_state, sfs_active),
        (neq, ":other_kingdom", "fac_player_supporters_faction"),
		# NE dk
		(neq, ":other_kingdom", "fac_dark_knights"),
		# NE End dk
        (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_supporters_faction", ":other_kingdom"),
          (val_max, ":other_kingdom_reln", 12),
        (try_end),
        (call_script, "script_set_player_relation_with_faction", ":other_kingdom", ":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"),
        (call_script, "script_give_center_to_faction_while_maintaining_lord", ":cur_center", ":faction_no"),
	  (else_try),
        #Give center to kingdom if part of player faction
     	(store_faction_of_party, ":cur_center_faction", ":cur_center"),
		(eq, ":cur_center_faction", "fac_player_supporters_faction"),
        (call_script, "script_give_center_to_faction_while_maintaining_lord", ":cur_center", ":faction_no"),
      (try_end),
      
      (try_for_range, ":quest_no", lord_quests_begin, lord_quests_end),
        (check_quest_active, ":quest_no"),
        (quest_get_slot, ":quest_giver_troop", ":quest_no", slot_quest_giver_troop),
        (store_troop_faction, ":quest_giver_faction", ":quest_giver_troop"),
        (store_relation, ":quest_giver_faction_relation", "fac_player_supporters_faction", ":quest_giver_faction"),
        (lt, ":quest_giver_faction_relation", 0),
        (call_script, "script_abort_quest", ":quest_no", 0),
      (try_end),
      (try_for_range, ":quest_no", lord_quests_begin_2, lord_quests_end_2),
        (check_quest_active, ":quest_no"),
        (quest_get_slot, ":quest_giver_troop", ":quest_no", slot_quest_giver_troop),
        (store_troop_faction, ":quest_giver_faction", ":quest_giver_troop"),
        (store_relation, ":quest_giver_faction_relation", "fac_player_supporters_faction", ":quest_giver_faction"),
        (lt, ":quest_giver_faction_relation", 0),
        (call_script, "script_abort_quest", ":quest_no", 0),
      (try_end),
      (try_begin),
        (neq, ":faction_no", "fac_player_supporters_faction"),
        (faction_set_slot, "fac_player_supporters_faction", slot_faction_state, sfs_inactive),
        (faction_set_slot, "fac_player_supporters_faction", slot_faction_leader, "trp_player"),
      (try_end),
	  
	  (try_begin),
		(troop_get_slot, ":spouse", "trp_player", slot_troop_spouse),
	    (is_between, ":spouse", kingdom_ladies_begin, kingdom_ladies_end),
		
		(try_begin),
			(ge, "$cheat_mode", 1),
			(str_store_troop_name, s4, ":spouse"),
			(display_message, "@{!}DEBUG - {s4} faction changed by marriage, case 1"), 
		(try_end),
		
	    (troop_set_faction, ":spouse", "$players_kingdom"),
	  (try_end),
	  	  
	  (try_for_range, ":center", centers_begin, centers_end),
	    (store_faction_of_party, ":center_faction", ":faction_no"),
		(neq, ":center_faction", "$players_kingdom"),
		(party_slot_eq, ":center", slot_town_lord, stl_reserved_for_player),
#		(party_set_slot, ":center", slot_town_lord, stl_unassigned),
	  (try_end),
	  
	  (troop_set_slot, "trp_player", slot_troop_stance_on_faction_issue, -1),
	  
	  #remove prisoners of player's faction if he was member of his own faction. And free companions which is prisoned in that faction.
      (try_for_parties, ":party_no"),
        (store_faction_of_party, ":party_faction", ":party_no"),
        (eq, ":party_faction", ":faction_no"),
        
        (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", "fac_player_supporters_faction"),
          (this_or_next|eq, ":cur_faction", ":faction_no"),
          (is_between, ":cur_troop_id", companions_begin, companions_end),
            
          (try_begin),
            (troop_is_hero, ":cur_troop_id"),
            (call_script, "script_remove_troop_from_prison", ":cur_troop_id"),
          (try_end),
          
          (party_prisoner_stack_get_size, ":stack_size", ":party_no", ":troop_iterator"),
          (party_remove_prisoners, ":party_no", ":cur_troop_id", ":stack_size"),
          
          (try_begin),
            (is_between, ":cur_troop_id", companions_begin, companions_end),
            
            (try_begin),
              (is_between, ":party_no", towns_begin, towns_end),
              (troop_set_slot, ":cur_troop_id", slot_troop_cur_center, ":party_no"),
            (else_try),
              (store_random_in_range, ":random_town_no", towns_begin, towns_end),       
              (troop_set_slot, ":cur_troop_id", slot_troop_cur_center, ":random_town_no"),
            (try_end),  
          (try_end),
        (try_end),
      (try_end),
      #remove prisoners end.

      #(call_script, "script_store_average_center_value_per_faction"),
      (call_script, "script_update_all_notes"),
      (assign, "$g_recalculate_ais", 1),
      ]),

  #script_player_leave_faction
  # INPUT: arg1 = give_back_fiefs
  # OUTPUT: none
  ("player_leave_faction",
    [
      (store_script_param, ":give_back_fiefs", 1),
	  
      (call_script, "script_check_and_finish_active_army_quests_for_faction", "$players_kingdom"),
      (assign, ":old_kingdom", "$players_kingdom"),
      (assign, ":old_has_homage", "$player_has_homage"),
      (assign, "$players_kingdom", 0),
      (assign, "$player_has_homage", 0),
	  
      (try_begin),
        (neq, ":give_back_fiefs", 0), #ie, give back fiefs = 1, thereby do it
        (try_for_range, ":cur_center", centers_begin, centers_end),
          (party_slot_eq, ":cur_center", slot_town_lord, "trp_player"),
          (call_script, "script_give_center_to_faction", ":cur_center", ":old_kingdom"),
		  
		  #The following line also occurs when a lord is stripped of his fiefs by an indictment
		  (party_set_slot, ":cur_center", slot_town_lord, stl_unassigned),
        (try_end),		
      (else_try),
	    #If you retain the fiefs
        (try_for_range, ":cur_center", centers_begin, centers_end),
          (party_slot_eq, ":cur_center", slot_town_lord, "trp_player"),
          (call_script, "script_give_center_to_faction", ":cur_center", "fac_player_supporters_faction"),
		  (party_set_slot, ":cur_center", slot_town_lord, "trp_player"),
          (troop_get_slot, ":cur_banner", "trp_player", slot_troop_banner_scene_prop),
          (gt, ":cur_banner", 0),
          (val_sub, ":cur_banner", banner_scene_props_begin),
          (val_add, ":cur_banner", banner_map_icons_begin),
          (party_set_banner_icon, ":cur_center", ":cur_banner"),		  		  
        (try_end),
        
        (try_for_range, ":cur_center", villages_begin, villages_end),
          (party_get_slot, ":cur_bound_center", ":cur_center", slot_village_bound_center),
          (try_begin),
            (party_slot_eq, ":cur_bound_center", slot_town_lord, "trp_player"),
            (call_script, "script_give_center_to_faction", ":cur_center", "fac_player_supporters_faction"),
            (party_set_slot, ":cur_center", slot_town_lord, "trp_player"),
          (else_try),
            (party_slot_eq, ":cur_center", slot_town_lord, "trp_player"),
            (call_script, "script_give_center_to_faction", ":cur_center", ":old_kingdom"),
          (try_end),
        (try_end),
	  
		(is_between, ":old_kingdom", kingdoms_begin, kingdoms_end),
		(neq, ":old_kingdom", "fac_player_supporters_faction"),		
        (store_relation, ":reln", "fac_player_supporters_faction", ":old_kingdom"),
        (store_sub, ":req_dif", -40, ":reln"),
        (call_script, "script_change_player_relation_with_faction", ":old_kingdom", ":req_dif"),
      (try_end),
	  
      (try_begin),
        (eq, ":old_has_homage", 1),
        (faction_get_slot, ":faction_leader", ":old_kingdom", slot_faction_leader),
        (call_script, "script_change_player_relation_with_troop", ":faction_leader", -20),
      (try_end),
	  
	  (try_begin),
		(troop_get_slot, ":spouse", "trp_player", slot_troop_spouse),
	    (is_between, ":spouse", kingdom_ladies_begin, kingdom_ladies_end),
		
		(try_begin),
			(ge, "$cheat_mode", 1),
			(str_store_troop_name, s4, ":spouse"),
			(display_message, "@{!}DEBUG - {s4} faction changed by marriage, case 3"), 
		(try_end),
		
		
	    (troop_set_faction, ":spouse", "fac_player_supporters_faction"),
	  (try_end),
	  
	  #Change relations with players_kingdom when player changes factions
	  (try_for_range, ":kingdom", kingdoms_begin, kingdoms_end),
	    (neq, ":kingdom", "fac_player_supporters_faction"),
	    (store_relation, ":relation_with_old_faction", ":old_kingdom", ":kingdom"),
	    (store_relation, ":relation_with_player_faction", "fac_player_faction", ":kingdom"),
	    
	    (try_begin),
	      (eq, ":old_kingdom", ":kingdom"),
	      (val_min, ":relation_with_player_faction", 0),
	    (else_try),	
	      (lt, ":relation_with_old_faction", 0),
	      (val_max, ":relation_with_player_faction", 0),
	    (try_end),
	    (set_relation, "fac_player_faction", ":kingdom", ":relation_with_player_faction"),
	    (set_relation, "fac_player_supporters_faction", ":kingdom", ":relation_with_player_faction"),
	  (try_end),
	  
	  (call_script, "script_update_all_notes"),
	  (assign, "$g_recalculate_ais", 1),
    ]),

	  
    ("deactivate_player_faction",
    [
	(faction_set_slot, "fac_player_supporters_faction", slot_faction_state, sfs_inactive),
    (faction_set_slot, "fac_player_supporters_faction", slot_faction_leader, "trp_player"),
    (assign, "$players_kingdom", 0),
    (assign, "$players_oath_renounced_against_kingdom", 0),
    (assign, "$players_oath_renounced_given_center", 0),
    (assign, "$players_oath_renounced_begin_time", 0),
    #(call_script, "script_store_average_center_value_per_faction"),
    (call_script, "script_update_all_notes"),
	
	(try_begin),
		(is_between, "$g_player_minister", companions_begin, companions_end),
		(assign, "$npc_to_rejoin_party", "$g_player_minister"),
	(try_end),
	(assign, "$g_player_minister", -1),
	
    (call_script, "script_add_notification_menu", "mnu_notification_player_faction_deactive", 0, 0),
    ]),

	
  #script_activate_player_faction
  # INPUT: arg1 = last_interaction_with_faction
  # OUTPUT: none
  
  #When a player convinces her husband to rebel
  #When a player proclaims herself queen
  #When a player seizes control of a center  
  #When a player recruits a lord through intrigue
  #When a player 
    ("activate_player_faction",
    [
    (store_script_param, ":liege", 1),

	#This moved to top, so that mnu_notification does not occur twice
	(try_begin),
		(faction_slot_eq, "fac_player_supporters_faction", slot_faction_state, sfs_inactive),
		(neg|is_between, ":liege", pretenders_begin, pretenders_end),
		(call_script, "script_add_notification_menu", "mnu_notification_player_faction_active", 0, 0),
	(try_end),

	
    (faction_set_slot, "fac_player_supporters_faction", slot_faction_state, sfs_active),
    (faction_set_slot, "fac_player_supporters_faction", slot_faction_leader, ":liege"),

	(assign, ":original_kingdom", "$players_kingdom"),
	
	(try_begin),
		(is_between, ":original_kingdom", npc_kingdoms_begin, npc_kingdoms_end),
		(call_script, "script_player_leave_faction", 0), #Ends quests, transfers control of centers
	(try_end),
	
	#Name faction
	(try_begin),
		(is_between, ":liege", active_npcs_begin, active_npcs_end),
		(store_faction_of_troop, ":liege_faction"),
		(is_between, ":liege_faction", npc_kingdoms_begin, npc_kingdoms_end),
		(faction_get_slot, ":adjective_string", ":liege_faction", slot_faction_adjective),
		(str_store_string, s1, ":adjective_string"),
		(faction_set_name, "fac_player_supporters_faction", "@{s1} Rebels"),
	(else_try),
		(str_store_troop_name, s2, ":liege"),
        (str_store_string, s1, "str_s2s_rebellion"),
	(try_end),	
    (faction_set_color, "fac_player_supporters_faction", 0xFF0000),
	
    (assign, "$players_kingdom", "fac_player_supporters_faction"),
    (assign, "$g_player_banner_granted", 1),
	
	
	
	#Any oaths renounced?
	(try_begin),
		(is_between, ":original_kingdom", npc_kingdoms_begin, npc_kingdoms_end),
		
        (faction_get_slot, ":old_leader", ":original_kingdom", slot_faction_leader),
        (call_script, "script_add_log_entry", logent_renounced_allegiance,   "trp_player",  -1, ":old_leader", "$players_kingdom"),

        #Initializing renounce war variables
        (assign, "$players_oath_renounced_against_kingdom", ":original_kingdom"),
        (assign, "$players_oath_renounced_given_center", 0),
        (store_current_hours, "$players_oath_renounced_begin_time"),
        
        (try_for_range, ":cur_center", walled_centers_begin, walled_centers_end),
          (store_faction_of_party, ":cur_center_faction", ":cur_center"),
          (party_set_slot, ":cur_center", slot_center_faction_when_oath_renounced, ":cur_center_faction"),
        (try_end),
        (party_set_slot, "$g_center_to_give_to_player", slot_center_faction_when_oath_renounced, "$players_oath_renounced_against_kingdom"),
		
		(store_relation, ":relation", ":original_kingdom", "fac_player_supporters_faction"),
		(ge, ":relation", 0),
		(call_script, "script_diplomacy_start_war_between_kingdoms", ":original_kingdom", "fac_player_supporters_faction", 1),
	(try_end),
	
	
	(try_begin),
		(troop_get_slot, ":spouse", "trp_player", slot_troop_spouse),
	    (is_between, ":spouse", kingdom_ladies_begin, kingdom_ladies_end),
		
		
		(try_begin),
			(ge, "$cheat_mode", 1),
			(str_store_troop_name, s4, ":spouse"),
			(display_message, "@{!}DEBUG - {s4} faction changed by marriage, case 2"), 
		(try_end),
		
	    (troop_set_faction, ":spouse", "fac_player_supporters_faction"),
	(try_end),
		 	
	
    #(call_script, "script_store_average_center_value_per_faction"),
    (call_script, "script_update_all_notes"),
	(assign, "$g_recalculate_ais", 1),
	
    ]),



  #script_agent_reassign_team
  # INPUT: arg1 = agent_no
  # OUTPUT: none
  ("agent_reassign_team",
    [
      (store_script_param, ":agent_no", 1),
      (get_player_agent_no, ":player_agent"),
      (try_begin),
        (ge, ":player_agent", 0),
        (agent_is_human, ":agent_no"),
        (agent_is_ally, ":agent_no"),
        (agent_get_party_id, ":party_no", ":agent_no"),
        (neq, ":party_no", "p_main_party"),
        (assign, ":continue", 1),
        (store_faction_of_party, ":party_faction", ":party_no"),
        (try_begin),
          (eq, ":party_faction", "$players_kingdom"),
          (is_between, "$players_kingdom", kingdoms_begin, kingdoms_end),
          (faction_slot_eq, "$players_kingdom", slot_faction_marshall, "trp_player"),
          (assign, ":continue", 0),
        (else_try),
          (party_stack_get_troop_id, ":leader_troop_id", ":party_no", 0),
          (neg|is_between, ":leader_troop_id", active_npcs_begin, active_npcs_end),
          (assign, ":continue", 0),
        (try_end),
        (eq, ":continue", 1),
        (agent_get_team, ":player_team", ":player_agent"),
        (val_add, ":player_team", 2),
        (agent_set_team, ":agent_no", ":player_team"),
      (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),
	 
	 (quest_set_slot, ":quest_no", slot_quest_giver_troop, ":giver_troop_no"),
	 
     (try_begin),
	   (eq, ":giver_troop_no", -1),
       (str_store_string, s63, "str_political_suggestion"),
	 (else_try),
       (is_between, ":giver_troop_no", active_npcs_begin, active_npcs_end),
       (str_store_troop_name_link, s62, ":giver_troop_no"),
       (str_store_string, s63, "@Given by: {s62}"),
     (else_try),
       (str_store_troop_name, s62, ":giver_troop_no"),
       (str_store_string, s63, "@Given by: {s62}"),
     (try_end),
     (store_current_hours, ":cur_hours"),          
     (str_store_date, s60, ":cur_hours"),
     (str_store_string, s60, "@Given on: {s60}"),
     (add_quest_note_from_sreg, ":quest_no", 0, s60, 0),
     (add_quest_note_from_sreg, ":quest_no", 1, s63, 0),
     (add_quest_note_from_sreg, ":quest_no", 2, 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", 7, "@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", ":giver_troop_no"),
     
     (try_begin),
       (eq, ":quest_no", "qst_report_to_army"),
       (assign, "$number_of_report_to_army_quest_notes", 8),
       (faction_get_slot, ":faction_ai_state", "$players_kingdom", slot_faction_ai_state),
       (call_script, "script_update_report_to_army_quest_note", "$players_kingdom", ":faction_ai_state", -1),     
     (try_end),  
	 
     (display_message, "str_quest_log_updated"),
   ]),

  #script_conclude_quest
  # INPUT: arg1 = quest_no
  # OUTPUT: none
  ("conclude_quest",
    [
      (store_script_param, ":quest_no", 1),
      (conclude_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", 7, "@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", 7, "@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", 7, "@This quest has failed. Talk to {s59} to explain the situation.", 0),
    ]),

  #script_report_quest_troop_positions
  # INPUT: arg1 = quest_no, arg2 = troop_no, arg3 = note_index
  # OUTPUT: none
  ("report_quest_troop_positions",
    [
      (store_script_param, ":quest_no", 1),
      (store_script_param, ":troop_no", 2),
      (store_script_param, ":note_index", 3),
      (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", ":note_index", s5, 1),
      (call_script, "script_update_troop_location_notes", ":troop_no", 1),
    ]),
   
  #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", 0, s1, 0),
      (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),
      (add_quest_note_from_sreg, ":quest_no", 6, s1, 0),
      (add_quest_note_from_sreg, ":quest_no", 7, s1, 0),
      (try_begin),
        (neg|check_quest_failed, ":quest_no"),
        (val_add, "$g_total_quests_completed", 1),
      (try_end),
	  (try_begin),
	    (eq, ":quest_no", "qst_consult_with_minister"),
	    (assign, "$g_minister_notification_quest", 0),
	  (try_end),
	  (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_cancel_quest
  # INPUT: arg1 = quest_no
  # OUTPUT: none
  ("cancel_quest",
    [(store_script_param, ":quest_no", 1),
     (str_clear, s1),
     (add_quest_note_from_sreg, ":quest_no", 0, s1, 0),
     (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),
     (add_quest_note_from_sreg, ":quest_no", 6, s1, 0),
     (add_quest_note_from_sreg, ":quest_no", 7, s1, 0),
     (cancel_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_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),
	   
	   (try_begin),
		(gt, ":min_dist_town", -1),
		(party_set_slot, ":cur_village", slot_village_market_town, ":min_dist_town"),
	   (else_try),
		(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"),
			(store_relation, ":relation", ":town_faction", ":village_faction"),
			(ge, ":relation", 0),
			(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),
     (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),
     ]),
  
# ne noble
  #script_update_volunteer_troops_in_town - Jinnai
  # INPUT: arg1 = center_no
  # OUTPUT: none
  ("update_volunteer_troops_in_town",
    [
       (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_noble_troop),
       (assign, ":volunteer_troop_tier", 1),
       (store_div, ":tier_upgrades", ":player_relation", 10),
       (val_min,":tier_upgrades",2),
       (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),
           (le, ":upgrade_troop_no", 0),
           (troop_get_upgrade_troop, ":upgrade_troop_no", ":volunteer_troop", 0),
         (try_end),
         (gt, ":upgrade_troop_no", 0),
         (val_add, ":volunteer_troop_tier", 1),
         (assign, ":volunteer_troop", ":upgrade_troop_no"),
       (try_end),
       
       (assign, ":upper_limit", 10),
       (try_begin),
         (ge, ":player_relation", 5),
         (assign, ":upper_limit", ":player_relation"),
         (val_div, ":upper_limit", 2),
         (val_add, ":upper_limit", 10),
       (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_npc_volunteer_troops_in_town - Jinnai
  # INPUT: arg1 = center_no
  # OUTPUT: none
  ("update_npc_volunteer_troops_in_town",
    [
       (store_script_param, ":center_no", 1),
       (party_get_slot, ":center_culture", ":center_no", slot_center_culture),
       (faction_get_slot, ":volunteer_troop", ":center_culture", slot_faction_noble_troop),
       (assign, ":volunteer_troop_tier", 1),
       (try_for_range, ":unused", 0, 5),
         (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),
           (le, ":upgrade_troop_no", 0),
           (troop_get_upgrade_troop, ":upgrade_troop_no", ":volunteer_troop", 0),
         (try_end),
         (gt, ":upgrade_troop_no", 0),
         (val_add, ":volunteer_troop_tier", 1),
         (assign, ":volunteer_troop", ":upgrade_troop_no"),
       (try_end),
       
       (assign, ":upper_limit", 16),
       
       (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_npc_volunteer_troop_type, ":volunteer_troop"),
       (party_set_slot, ":center_no", slot_center_npc_volunteer_troop_amount, ":amount"),
     ]),

# ne end noble

	 
  #script_update_volunteer_troops_in_village
  # INPUT: arg1 = center_no
  # 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),
	   
	   
##	   (try_begin),
##		(eq, "$cheat_mode", 2),
##	    (str_store_party_name, s4, ":center_no"),
##	    (str_store_faction_name, s5, ":center_culture"),
##	    (display_message, "str_updating_volunteers_for_s4_faction_is_s5"),
##	   (try_end),
	   
       (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),
           (le, ":upgrade_troop_no", 0),
           (troop_get_upgrade_troop, ":upgrade_troop_no", ":volunteer_troop", 0),
         (try_end),
         (gt, ":upgrade_troop_no", 0),
         (val_add, ":volunteer_troop_tier", 1),
         (assign, ":volunteer_troop", ":upgrade_troop_no"),
       (try_end),
       
       (assign, ":upper_limit", 7),
       (try_begin),
         (ge, ":player_relation", 5),
         (assign, ":upper_limit", ":player_relation"),
         (val_div, ":upper_limit", 2),
         (val_add, ":upper_limit", 10),
       (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_npc_volunteer_troops_in_village
  # INPUT: arg1 = center_no
  # OUTPUT: none
  ("update_npc_volunteer_troops_in_village",
    [
       (store_script_param, ":center_no", 1),
       (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),
       (try_for_range, ":unused", 0, 5),
         (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),
           (le, ":upgrade_troop_no", 0),
           (troop_get_upgrade_troop, ":upgrade_troop_no", ":volunteer_troop", 0),
         (try_end),
         (gt, ":upgrade_troop_no", 0),
         (val_add, ":volunteer_troop_tier", 1),
         (assign, ":volunteer_troop", ":upgrade_troop_no"),
       (try_end),
       
       (assign, ":upper_limit", 12),
       
       (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_npc_volunteer_troop_type, ":volunteer_troop"),
       (party_set_slot, ":center_no", slot_center_npc_volunteer_troop_amount, ":amount"),
     ]),

  #script_update_companion_candidates_in_taverns
  # INPUT: none
  # OUTPUT: none
  ("update_companion_candidates_in_taverns",
    [
      (try_begin),
        (eq, "$cheat_mode", 1),
        (display_message, "str_shuffling_companion_locations"),
      (try_end),
      
      (try_for_range, ":troop_no", companions_begin, companions_end),
        (troop_set_slot, ":troop_no", slot_troop_cur_center, -1),
        (troop_slot_eq, ":troop_no", slot_troop_days_on_mission, 0),
        (troop_slot_eq, ":troop_no", slot_troop_occupation, slto_inactive),
        
        (neg|troop_slot_ge, ":troop_no", slot_troop_prisoner_of_party, 0),
        
        (store_random_in_range, ":town_no", towns_begin, towns_end),
        (try_begin),
          (neg|troop_slot_eq, ":troop_no", slot_troop_home, ":town_no"),
          (neg|troop_slot_eq, ":troop_no", slot_troop_first_encountered, ":town_no"),
          (troop_set_slot, ":troop_no", slot_troop_cur_center, ":town_no"),
          (try_begin),
            (eq, "$cheat_mode", 1),
            (str_store_troop_name, 4, ":troop_no"),
            (str_store_party_name, 5, ":town_no"),
            (display_message, "@{!}{s4} is in {s5}"),
          (try_end),
        (try_end),
      (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),

     (party_set_slot,"p_town_2",slot_center_ransom_broker,"trp_ramun_the_slave_trader"),
     ]),

  #script_update_tavern_travellers
  # INPUT: none
  # OUTPUT: none
  ("update_tavern_travellers",
    [(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, ":end_cond", 15),
       (try_for_range, ":unused", 0, ":end_cond"),
         (store_random_in_range, ":info_faction", kingdoms_begin, kingdoms_end),
         (faction_slot_eq, ":info_faction", slot_faction_state, sfs_active),
         (neq, ":info_faction", "$players_kingdom"),
         (neq, ":info_faction", "fac_player_supporters_faction"),
         (party_set_slot, ":town_no", slot_center_traveler_info_faction, ":info_faction"),
         (assign, ":end_cond", 0),
       (try_end),
     (try_end),
	 
	 (troop_set_slot, "trp_belligerent_drunk", slot_troop_cur_center, "p_town_1"),
     ]),

  #script_update_villages_infested_by_bandits
  # INPUT: none
  # OUTPUT: none
  ("update_villages_infested_by_bandits",
    [(try_for_range, ":village_no", villages_begin, villages_end),
       (try_begin),
         (check_quest_active, "qst_eliminate_bandits_infesting_village"),
         (quest_slot_eq, "qst_eliminate_bandits_infesting_village", slot_quest_target_center, ":village_no"),
         (quest_get_slot, ":cur_state", "qst_eliminate_bandits_infesting_village", slot_quest_current_state),
         (val_add, ":cur_state", 1),
         (try_begin),
           (lt, ":cur_state", 3),
           (quest_set_slot, "qst_eliminate_bandits_infesting_village", slot_quest_current_state, ":cur_state"),
         (else_try),
           (party_set_slot, ":village_no", slot_village_infested_by_bandits, 0),
           (call_script, "script_abort_quest", "qst_eliminate_bandits_infesting_village", 2),
         (try_end),
       (else_try),
         (check_quest_active, "qst_deal_with_bandits_at_lords_village"),
         (quest_slot_eq, "qst_deal_with_bandits_at_lords_village", slot_quest_target_center, ":village_no"),
         (quest_get_slot, ":cur_state", "qst_deal_with_bandits_at_lords_village", slot_quest_current_state),
         (val_add, ":cur_state", 1),
         (try_begin),
           (lt, ":cur_state", 3),
           (quest_set_slot, "qst_deal_with_bandits_at_lords_village", slot_quest_current_state, ":cur_state"),
         (else_try),
           (party_set_slot, ":village_no", slot_village_infested_by_bandits, 0),
           (call_script, "script_abort_quest", "qst_deal_with_bandits_at_lords_village", 2),
         (try_end),
       (else_try),
         (party_set_slot, ":village_no", slot_village_infested_by_bandits, 0),
         (store_random_in_range, ":random_no", 0, 100),
         (lt, ":random_no", 3),
         (store_random_in_range, ":random_no", 0, 3),
         (try_begin),
           (eq, ":random_no", 0),
           (assign, ":bandit_troop", "trp_bandit"),
         (else_try),
           (eq, ":random_no", 1),
           (assign, ":bandit_troop", "trp_mountain_bandit"),
         (else_try),
           (assign, ":bandit_troop", "trp_forest_bandit"),
         (try_end),
         (party_set_slot, ":village_no", slot_village_infested_by_bandits, ":bandit_troop"),
         #Reduce prosperity of the village by 3: reduce to -1
         (call_script, "script_change_center_prosperity", ":village_no", -1),
		 (val_add, "$newglob_total_prosperity_from_bandits", -1),
         (try_begin),
           (eq, "$cheat_mode", 2),
           (str_store_party_name, s1, ":village_no"),
           (display_message, "@{!}DEBUG --{s1} is infested by bandits."),
         (try_end),
       (try_end),
     (try_end),
     ]),

  #script_update_booksellers
  # INPUT: none
  # OUTPUT: none
  ("update_booksellers",
    [(try_for_range, ":town_no", towns_begin, towns_end),
       (party_set_slot, ":town_no", slot_center_tavern_bookseller, 0),
     (try_end),
     
     (try_for_range, ":troop_no", tavern_booksellers_begin, tavern_booksellers_end),
       (store_random_in_range, ":town_no", towns_begin, towns_end),
       (party_set_slot, ":town_no", slot_center_tavern_bookseller, ":troop_no"),
     (try_end),
	 

	 
     ]),
     
  #script_update_tavern_minstels
  # INPUT: none
  # OUTPUT: none
  ("update_tavern_minstrels",
    [(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_begin),
		(eq, "$cheat_mode", 1),
		(str_store_troop_name, s4, ":troop_no"),
		(str_store_party_name, s5, ":town_no"),
		
	    (display_message, "str_s4_is_at_s5"),
	   (try_end),	
     (try_end),
	 
	 
     ]),
 
  ("update_other_taverngoers", 
  [
	(store_random_in_range, ":fight_promoter_tavern", towns_begin, towns_end),
	(troop_set_slot, "trp_fight_promoter", slot_troop_cur_center, ":fight_promoter_tavern"),
	
	(store_random_in_range, ":belligerent_drunk_tavern", towns_begin, towns_end),
	(troop_set_slot, "trp_belligerent_drunk", slot_troop_cur_center, ":belligerent_drunk_tavern"),	
	]), 
	
 
  #script_update_faction_notes
  # INPUT: faction_no
  # OUTPUT: none
  ("update_faction_notes",
    [
      (store_script_param, ":faction_no", 1),
            
      (try_begin),
        (this_or_next|faction_slot_eq, ":faction_no", slot_faction_state, sfs_inactive),
        (eq, ":faction_no", "fac_player_faction"),
        (faction_set_note_available, ":faction_no", 0),
      (else_try),
        (faction_set_note_available, ":faction_no", 1),
      (try_end),
##
##	(try_begin),
##		(eq, 2, 1),
##		(str_store_faction_name, s14, ":faction_no"),
##		(assign, reg4, "$temp"),
##		(display_message, "str_updating_faction_notes_for_s14_temp_=_reg4"),
##	(try_end),
##		
##    (try_begin),
##       (is_between, ":faction_no", kingdoms_begin, kingdoms_end),
##       (faction_slot_eq, ":faction_no", slot_faction_state, sfs_active),
##       (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, "@nowhere"),
##       (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, ":loop_var", "trp_kingdom_heroes_including_player_begin", active_npcs_end),
##         (assign, ":cur_troop", ":loop_var"),
##         (try_begin),
##           (eq, ":loop_var", "trp_kingdom_heroes_including_player_begin"),
##           (assign, ":cur_troop", "trp_player"),
##           (assign, ":troop_faction", "$players_kingdom"),
##         (else_try),
##           (store_troop_faction, ":troop_faction", ":cur_troop"),
##         (try_end),
##         (eq, ":troop_faction", ":faction_no"),
##         (neq, ":cur_troop", ":faction_leader"),
##         (troop_slot_eq, ":cur_troop", slot_troop_occupation, slto_kingdom_hero),
##         (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),
##	   
##	   #wars
##       (str_store_string, s12, "@noone"),
###       (assign, ":num_enemies", 0),
###       (try_for_range_backwards, ":cur_faction", kingdoms_begin, kingdoms_end),
###         (faction_slot_eq, ":cur_faction", slot_faction_state, sfs_active),
###         (store_relation, ":cur_relation", ":cur_faction", ":faction_no"),
###         (lt, ":cur_relation", 0),
###         (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, "@the {s11} and the {s12}"),
###         (else_try),
###           (str_store_faction_name_link, s11, ":cur_faction"),
###           (str_store_string, s12, "@the {s11}, the {s12}"),
###         (try_end),
###         (val_add, ":num_enemies", 1),
###       (try_end),
##	   
##       (str_store_string, s21, "str_foreign_relations__"),
##	   
##	   #other foreign relations
##       (try_for_range, ":cur_faction", kingdoms_begin, kingdoms_end),
##         (faction_slot_eq, ":cur_faction", slot_faction_state, sfs_active),
##		 (neq, ":faction_no", ":cur_faction"),
##		 (str_store_faction_name_link, s14, ":cur_faction"),
##         (call_script, "script_diplomacy_faction_get_diplomatic_status_with_faction", ":faction_no", ":cur_faction"),
##		 (assign, ":diplomatic_status", reg0),
##		 (assign, reg2, reg1), #length of events
##		 (call_script, "script_diplomacy_faction_get_diplomatic_status_with_faction", ":cur_faction", ":faction_no"),
##		 (assign, ":reverse_diplomatic_status", reg0),
##		 
##		 
##		 (try_begin),
##			(eq, ":diplomatic_status", -2),
##			(str_store_string, s21, "str_s21__the_s5_is_at_war_with_the_s14"), 
##		 
##			(store_add, ":slot_war_damage_inflicted", ":cur_faction", slot_faction_war_damage_inflicted_on_factions_begin),
##			(val_sub, ":slot_war_damage_inflicted", kingdoms_begin),
##			(faction_get_slot, ":war_damage_inflicted", ":faction_no", ":slot_war_damage_inflicted"),
##			(store_mul, ":war_damage_inflicted_x_2", ":war_damage_inflicted", 2),
##			
##			(store_add, ":slot_war_damage_suffered", ":faction_no", slot_faction_war_damage_inflicted_on_factions_begin),
##			(val_sub, ":slot_war_damage_suffered", kingdoms_begin),
##			(faction_get_slot, ":war_damage_suffered", ":cur_faction", ":slot_war_damage_suffered"),
##			(store_mul, ":war_damage_suffered_x_2", ":war_damage_suffered", 2),
##			
##			(try_begin),
##				(gt, ":war_damage_inflicted", ":war_damage_suffered_x_2"),
##				(str_store_string, s21, "str_s21_the_s5_has_had_the_upper_hand_in_the_fighting"),
##			(else_try),
##				(gt, ":war_damage_suffered", ":war_damage_inflicted_x_2"),
##				(str_store_string, s21, "@{s21}. The {s14} has gotten the worst of the fighting."),
##			(else_try),
##				(gt, ":war_damage_inflicted", 100),
##				(gt, ":war_damage_inflicted", 100),
##				(str_store_string, s21, "str_s21_the_fighting_has_gone_on_for_some_time_and_the_war_may_end_soon_with_a_truce"),
##			(else_try),
##				(str_store_string, s21, "str_s21_the_fighting_has_begun_relatively_recently_and_the_war_may_continue_for_some_time"),
##			(try_end),
##			
##			(try_begin),
##				(eq, "$cheat_mode", 1),
##				(assign, reg4, ":war_damage_inflicted"),
##				(assign, reg5, ":war_damage_suffered"),
##				(str_store_string, s21, "str_s21_reg4reg5"),
##			(try_end),
##		 (else_try),
##			(eq, ":diplomatic_status", 1),
##			(str_clear, s18),
##
##			(try_begin),
##				(neq, reg0, 1),
##				(str_store_string, s18, "str__however_the_truce_is_no_longer_binding_on_the_s14"),
##			(try_end),
##			(str_store_string, s21, "str_s21__the_s5_is_bound_by_truce_not_to_attack_the_s14s18_the_truce_will_expire_in_reg1_days"),
##			
##		 (else_try), 
##			(eq, ":diplomatic_status", -1),
##			(str_store_string, s21, "str_s21__the_s5_has_recently_suffered_provocation_by_subjects_of_the_s14_and_there_is_a_risk_of_war"),
##		 (else_try),
##			(eq, ":diplomatic_status", 0),
##			(str_store_string, s21, "str_s21__the_s5_has_no_outstanding_issues_with_the_s14"),
##		 (try_end),
##			 
##			 
##		 (try_begin),
##			(eq, ":reverse_diplomatic_status", -1),
##			(str_store_string, s21, "str_s21_the_s14_was_recently_provoked_by_subjects_of_the_s5_and_there_is_a_risk_of_war_"), 
##		 (try_end),
##		 
##		 (try_begin),
##			(eq, "$cheat_mode", 1),
##			(call_script, "script_diplomacy_faction_assess_faction_to_s14", ":faction_no", ":cur_faction", -1),
##			(str_store_string, s21, "str_s21_cheat_mode_assessment_s14_"), 
##	     (try_end),
##	  (try_end),	 
##
##	  
##	  (add_faction_note_from_sreg, ":faction_no", 0, "str_the_s5_is_ruled_by_s6_it_occupies_s8_its_vassals_are_s10__s21", 0),
##
##
##	   
##    (else_try),
##       (is_between, ":faction_no", kingdoms_begin, kingdoms_end),
##       (faction_slot_eq, ":faction_no", slot_faction_state, sfs_defeated),
##       (str_store_faction_name, s5, ":faction_no"),
##       (add_faction_note_from_sreg, ":faction_no", 0, "@{s5} has been defeated!", 0),
##       (str_clear, s1),
##       (add_faction_note_from_sreg, ":faction_no", 1, s1, 0),
##    (else_try),
##       (str_clear, s1),
##       (add_faction_note_from_sreg, ":faction_no", 0, s1, 0),
##       (add_faction_note_from_sreg, ":faction_no", 1, s1, 0),
##    (try_end),
##	
##    (try_begin),
##       (is_between, ":faction_no", "fac_kingdom_1", kingdoms_end), #Excluding player kingdom
##       (add_faction_note_tableau_mesh, ":faction_no", "tableau_faction_note_mesh"),
##    (else_try),
##       (add_faction_note_tableau_mesh, ":faction_no", "tableau_faction_note_mesh_banner"),
##    (try_end),
     ]),

  ("update_faction_political_notes",
    [(store_script_param, ":faction_no", 1),
	 
	(call_script, "script_evaluate_realm_stability", ":faction_no"),
    (add_faction_note_from_sreg, ":faction_no", 2, "str_instability_reg0_of_lords_are_disgruntled_reg1_are_restless", 0),
	]), 
	 
	 
	 
  #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, s54, ":troop_no"),
##     (try_begin),
##       (eq, ":troop_no", "trp_player"),
##       (this_or_next|eq, "$player_has_homage", 1),
##		(eq, "$players_kingdom", "fac_player_supporters_faction"),
##       (assign, ":troop_faction", "$players_kingdom"),
##     (else_try),
##       (store_troop_faction, ":troop_faction", ":troop_no"),
##     (try_end),
##	 
##	 (str_clear, s49),
##	 (try_begin),
##		(is_between, ":troop_no", lords_begin, kingdom_ladies_end),
##		(troop_get_slot, reg1, ":troop_no", slot_troop_age),
##		(str_store_string, s49, "str__age_reg1_family_"),
##		
##		(try_for_range, ":aristocrat", lords_begin, kingdom_ladies_end),
##			(call_script, "script_troop_get_family_relation_to_troop", ":aristocrat", ":troop_no"),
##			(gt, reg0, 0),
##
##			(try_begin),
##				(neg|is_between, ":aristocrat", kingdom_ladies_begin, kingdom_ladies_end),
##				(str_store_troop_name_link, s12, ":aristocrat"),
##				(call_script, "script_troop_get_relation_with_troop", ":aristocrat", ":troop_no"),
##				(str_store_string, s49, "str_s49_s12_s11_rel_reg0"),
##			(else_try),	
##				(str_store_troop_name, s12, ":aristocrat"),
##				(str_store_string, s49, "str_s49_s12_s11"),
##			(try_end),	
##			
##		(try_end),
##	 (try_end),
##	 
##     (try_begin),
##       (neq, ":troop_no", "trp_player"),
##       (neg|is_between, ":troop_faction", kingdoms_begin, kingdoms_end),
##       (str_clear, s54),
##       (add_troop_note_from_sreg, ":troop_no", 0, s54, 0),
##       (add_troop_note_from_sreg, ":troop_no", 1, s54, 0),
##       (add_troop_note_from_sreg, ":troop_no", 2, s54, 0),
###     (else_try),
###       (is_between, ":troop_no", kingdom_ladies_begin, kingdom_ladies_end),
###       (str_clear, s54),
###       (add_troop_note_from_sreg, ":troop_no", 0, s54, 0),
###       (add_troop_note_from_sreg, ":troop_no", 1, s54, 0),
###       (add_troop_note_from_sreg, ":troop_no", 2, s54, 0),
##     (else_try),
##       (is_between, ":troop_no", pretenders_begin, pretenders_end),
##       (neg|troop_slot_eq, ":troop_no", slot_troop_occupation, slto_kingdom_hero),
##       (neq, ":troop_no", "$supported_pretender"),
##       (troop_get_slot, ":orig_faction", ":troop_no", slot_troop_original_faction),
##       (try_begin),
##         (faction_slot_eq, ":orig_faction", slot_faction_state, sfs_active),
##         (faction_slot_eq, ":orig_faction", slot_faction_has_rebellion_chance, 1),
##         (str_store_faction_name_link, s56, ":orig_faction"),
##         (add_troop_note_from_sreg, ":troop_no", 0, "@{s54} is a claimant to the throne of {s56}.", 0),
##         (add_troop_note_tableau_mesh, ":troop_no", "tableau_troop_note_mesh"),
##       (else_try),
##         (str_clear, s54),
##         (add_troop_note_from_sreg, ":troop_no", 0, s54, 0),
##         (add_troop_note_from_sreg, ":troop_no", 1, s54, 0),
##         (add_troop_note_from_sreg, ":troop_no", 2, s54, 0),
##       (try_end),
##     (else_try),
##       (faction_get_slot, ":faction_leader", ":troop_faction", slot_faction_leader),
##       (str_store_troop_name_link, s55, ":faction_leader"),
##       (str_store_faction_name_link, s56, ":troop_faction"),
##       (assign, ":troop_is_player_faction", 0),
##       (assign, ":troop_is_faction_leader", 0),
##       (try_begin),
##         (eq, ":troop_faction", "fac_player_faction"),
##         (assign, ":troop_is_player_faction", 1),
##       (else_try),
##         (eq, ":faction_leader", ":troop_no"),
##         (assign, ":troop_is_faction_leader", 1),
##       (try_end),
##       (assign, ":num_centers", 0),
##       (str_store_string, s58, "@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, s58, ":cur_center"),
##         (else_try),
##           (eq, ":num_centers", 1),
##           (str_store_party_name_link, s57, ":cur_center"),
##           (str_store_string, s58, "@{s57} and {s58}"),
##         (else_try),
##           (str_store_party_name_link, s57, ":cur_center"),
##           (str_store_string, s58, "@{!}{s57}, {s58}"),
##         (try_end),
##         (val_add, ":num_centers", 1),
##       (try_end),
##       (troop_get_type, reg3, ":troop_no"),
##       (troop_get_slot, reg5, ":troop_no", slot_troop_renown),
##       (str_clear, s59),
##       (try_begin),
###         (troop_get_slot, ":relation", ":troop_no", slot_troop_player_relation),
##         (call_script, "script_troop_get_player_relation", ":troop_no"),
##         (assign, ":relation", reg0),
##         (store_add, ":normalized_relation", ":relation", 100),
##         (val_add, ":normalized_relation", 5),
##         (store_div, ":str_offset", ":normalized_relation", 10),
##         (val_clamp, ":str_offset", 0, 20),
##         (store_add, ":str_id", "str_relation_mnus_100_ns",  ":str_offset"),
##         (neq, ":str_id", "str_relation_plus_0_ns"),
##         (str_store_string, s60, "@{reg3?She:He}"),
##         (str_store_string, s59, ":str_id"),
##         (str_store_string, s59, "@{!}^{s59}"),
##       (try_end),
##
##	#lord recruitment changes begin
##	#This sends a bunch of political information to s47. 
##	
##
##
##	   
##	    #refresh registers
##        (assign, reg9, ":num_centers"),
##        (troop_get_type, reg3, ":troop_no"),
##        (troop_get_slot, reg5, ":troop_no", slot_troop_renown),
##		(assign, reg4, ":troop_is_faction_leader"),
##		(assign, reg6, ":troop_is_player_faction"),
##		
##        (add_troop_note_from_sreg, ":troop_no", 0, "str_reg6reg4s54_is_the_ruler_of_s56_s54_is_a_vassal_of_s55_of_s56_renown_reg5_reg9reg3shehe_is_the_reg3ladylord_of_s58reg3shehe_has_no_fiefss59_s49", 0),
##	#lord recruitment changes end
##
##        (add_troop_note_tableau_mesh, ":troop_no", "tableau_troop_note_mesh"),
##     (try_end),
     ]),

  #script_update_troop_location_notes
  # INPUT: troop_no
  # OUTPUT: none
  ("update_troop_location_notes",
    [
      (store_script_param, ":troop_no", 1),
      (store_script_param, ":see_or_hear", 2),      
      (try_begin),
        (call_script, "script_get_information_about_troops_position", ":troop_no", 1),
        (neq, reg0, 0),       
        
        (call_script, "script_search_troop_prisoner_of_party", ":troop_no"),
        (eq, reg0, -1),
	                   
	    (troop_get_type, reg1, ":troop_no"),         
        (try_begin),
          (eq, ":see_or_hear", 0),
          (add_troop_note_from_sreg, ":troop_no", 2, "@The last time you saw {reg1?her:him}, {s1}", 1),
        (else_try),
          (add_troop_note_from_sreg, ":troop_no", 2, "@The last time you heard about {reg1?her:him}, {s1}", 1),
        (try_end),
      (try_end),
     ]),

  #script_update_troop_location_notes_prisoned
  # INPUT: troop_no
  # OUTPUT: none
  ("update_troop_location_notes_prisoned",
    [
      (store_script_param, ":troop_no", 1),
      (store_script_param, ":capturer_faction_no", 2),
      
      (troop_get_type, reg1, ":troop_no"),             
      (str_store_faction_name_link, s1, ":capturer_faction_no"),
       
      (add_troop_note_from_sreg, ":troop_no", 2, "str_reg1shehe_is_prisoner_of_s1", 1),
    ]),
	 
  ("update_troop_political_notes",
      [
		(store_script_param, ":troop_no", 1),
		(try_begin),
		    (str_clear, s47),

			(store_faction_of_troop, ":troop_faction", ":troop_no"),

		    (faction_get_slot, ":faction_leader", ":troop_faction", slot_faction_leader),

		    (str_clear, s40),
		    (assign, ":logged_a_rivalry", 0),
		    (try_for_range, ":kingdom_hero", active_npcs_begin, active_npcs_end),
				(call_script, "script_troop_get_relation_with_troop", ":troop_no", ":kingdom_hero"),
				(lt, reg0, -10),
				
		   		(str_store_troop_name_link, s39, ":kingdom_hero"),
				(try_begin),
					(eq, ":logged_a_rivalry", 0),
					(str_store_string, s40, "str_s39_rival"),
					(assign, ":logged_a_rivalry", 1),
				(else_try),
					(str_store_string, s41, "str_s40"),
					(str_store_string, s40, "str_s41_s39_rival"),
				(try_end),
		   
		    (try_end),

		    (str_clear, s46),
		    (try_begin),
				(ge, "$cheat_mode", 1),
				(try_begin),
					(troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_martial),
					(str_store_string, s46, "str_reputation_cheat_mode_only_martial_"),
				(else_try),	
					(troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_debauched),
					(str_store_string, s46, "str_reputation_cheat_mode_only_debauched_"),
				(else_try),	
					(troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_selfrighteous),
					(str_store_string, s46, "str_reputation_cheat_mode_only_pitiless_"),
				(else_try),	
					(troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_cunning),
					(str_store_string, s46, "str_reputation_cheat_mode_only_calculating_"),
				(else_try),	
					(troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_quarrelsome),
					(str_store_string, s46, "str_reputation_cheat_mode_only_quarrelsome_"),
				(else_try),	
					(troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_goodnatured),
					(str_store_string, s46, "str_reputation_cheat_mode_only_goodnatured_"),
				(else_try),	
					(troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_upstanding),
					(str_store_string, s46, "str_reputation_cheat_mode_only_upstanding_"),
				(else_try),
					(troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_conventional),
					(str_store_string, s46, "str_reputation_cheat_mode_only_conventional_"),
				(else_try),
					(troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_adventurous),
					(str_store_string, s46, "str_reputation_cheat_mode_only_adventurous_"),
				(else_try),
					(troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_otherworldly),
					(str_store_string, s46, "str_reputation_cheat_mode_only_romantic_"),
				(else_try),
					(troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_moralist),
					(str_store_string, s46, "str_reputation_cheat_mode_only_moralist_"),
				(else_try),
					(troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_ambitious),
					(str_store_string, s46, "str_reputation_cheat_mode_only_ambitious_"),
				(else_try),	
					(troop_get_slot, reg11, ":troop_no", slot_lord_reputation_type),
					(str_store_string, s46, "str_reputation_cheat_mode_only_reg11_"),
				(try_end),

				(try_begin),
					(eq, "$cheat_mode", 1),
					(try_for_range, ":love_interest_slot", slot_troop_love_interest_1, slot_troop_love_interests_end),
						(troop_get_slot, ":love_interest", ":troop_no", ":love_interest_slot"),
						(is_between, ":love_interest", kingdom_ladies_begin, kingdom_ladies_end),
						(str_store_troop_name_link, s39, ":love_interest"),
						(call_script, "script_troop_get_relation_with_troop", ":troop_no", ":love_interest"),
						(str_store_string, s2, "str_love_interest"),
						(try_begin),
							(troop_slot_eq, ":troop_no", slot_troop_betrothed, ":love_interest"),
							(str_store_string, s2, "str_betrothed"),
						(try_end),
						(str_store_string, s40, "str_s40_s39_s2_reg0"),
					(try_end),
				(try_end),
				
		    (try_end),
			
		    (str_store_string, s45, "str_other_relations_s40_"),

		    (str_clear, s44),
		    (try_begin),
				(neq, ":troop_no", ":faction_leader"),
				(call_script, "script_troop_get_relation_with_troop", ":troop_no", ":faction_leader"),
				(str_store_string, s44, "str_relation_with_liege_reg0_"),
		    (try_end),

			(str_clear, s48),

		    (try_begin),
				(eq, "$cheat_mode", 1),
				(store_current_hours, ":hours"),
				(gt, ":hours", 0),
#				(display_message, "@{!}Updating political factors"),
				(call_script, "script_calculate_troop_political_factors_for_liege", ":troop_no", ":faction_leader"),
				(str_store_string, s48, "str_sense_of_security_military_reg1_court_position_reg3_"),
			(try_end),
			(str_store_string, s47, "str_s46s45s44s48"),

			(add_troop_note_from_sreg, ":troop_no", 3, "str_political_details_s47_", 1),

		(try_end),	 
    ]),	 
	 
  #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),
##     (try_begin),
##       (ge, ":lord_troop", 0),
##       (store_troop_faction, ":lord_faction", ":lord_troop"),
##       (str_store_troop_name_link, s1, ":lord_troop"),
##       (try_begin),
##         (eq, ":lord_troop", "trp_player"),
##         (gt, "$players_kingdom", 0),
##         (str_store_faction_name_link, s2, "$players_kingdom"),
##       (else_try),
##         (str_store_faction_name_link, s2, ":lord_faction"),
##       (try_end),
##       (str_store_party_name, s50, ":center_no"),
##       (try_begin),
##         (party_slot_eq, ":center_no", slot_party_type, spt_town),
##         (str_store_string, s51, "@The town of {s50}"),
##       (else_try),
##         (party_slot_eq, ":center_no", slot_party_type, spt_village),
##         (party_get_slot, ":bound_center", ":center_no", slot_village_bound_center),
##         (str_store_party_name_link, s52, ":bound_center"),
##         (str_store_string, s51, "@The village of {s50} near {s52}"),
##       (else_try),
##         (str_store_string, s51, "@{!}{s50}"),
##       (try_end),
##       (str_store_string, s2, "@{s51} belongs to {s1} of {s2}.^"),
##     (else_try),
##       (str_clear, s2),
##     (try_end),
##     (try_begin),
##       (is_between, ":center_no", villages_begin, villages_end),
##     (else_try),
##       (assign, ":num_villages", 0),
##       (try_for_range_backwards, ":village_no", villages_begin, villages_end),
##         (party_slot_eq, ":village_no", slot_village_bound_center, ":center_no"),
##         (try_begin),
##           (eq, ":num_villages", 0),
##           (str_store_party_name_link, s8, ":village_no"),
##         (else_try),
##           (eq, ":num_villages", 1),
##           (str_store_party_name_link, s7, ":village_no"),
##           (str_store_string, s8, "@{s7} and {s8}"),
##         (else_try),
##           (str_store_party_name_link, s7, ":village_no"),
##           (str_store_string, s8, "@{!}{s7}, {s8}"),
##         (try_end),
##         (val_add, ":num_villages", 1),
##       (try_end),
##       (try_begin),
##         (eq, ":num_villages", 0),
##         (str_store_string, s2, "@{s2}It has no villages.^"),
##       (else_try),
##         (store_sub, reg0, ":num_villages", 1),
##         (str_store_string, s2, "@{s2}{reg0?Its villages are:Its village is} {s8}.^"),
##       (try_end),
##     (try_end),
##     (call_script, "script_get_prosperity_text_to_s50", ":center_no"),
##     (add_party_note_from_sreg, ":center_no", 0, "@{s2}Its prosperity is: {s50}", 0),
##     (add_party_note_tableau_mesh, ":center_no", "tableau_center_note_mesh"),
     ]),
      

  #script_update_center_recon_notes
  # INPUT: center_no
  # OUTPUT: none
  ("update_center_recon_notes",
    [(store_script_param, ":center_no", 1),
     (try_begin),
       (this_or_next|is_between, ":center_no", towns_begin, towns_end),
       (is_between, ":center_no", castles_begin, castles_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"),
       (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.^Has food stock for {reg6} days.", 1),
     (try_end),
     ]),
  
  #script_update_all_notes
  # INPUT: none
  # OUTPUT: none
  ("update_all_notes",
    [
      (call_script, "script_update_troop_notes", "trp_player"),
      (try_for_range, ":troop_no", active_npcs_begin, active_npcs_end),
	    (this_or_next|troop_slot_eq, ":troop_no", slot_troop_occupation, slto_kingdom_hero),
	    (this_or_next|troop_slot_eq, ":troop_no", slot_troop_occupation, slto_kingdom_lady),
			(troop_slot_eq, ":troop_no", slot_troop_occupation, slto_inactive_pretender),
        (call_script, "script_update_troop_notes", ":troop_no"),
      (try_end),
      (try_for_range, ":center_no", centers_begin, centers_end),
        (call_script, "script_update_center_notes", ":center_no"),
      (try_end),
      (try_for_range, ":faction_no", kingdoms_begin, kingdoms_end),
        (call_script, "script_update_faction_notes", ":faction_no"),
      (try_end),
    ]),

  #script_agent_troop_get_banner_mesh
  # INPUT: agent_no, troop_no
  # OUTPUT: banner_mesh
  ("agent_troop_get_banner_mesh",
    [
       (store_script_param, ":agent_no", 1),
       (store_script_param, ":troop_no", 2),
       (assign, ":banner_troop", -1),
       (assign, ":banner_mesh", "mesh_banners_default_b"),
       (try_begin),
         (lt, ":agent_no", 0),
         (try_begin),
           (ge, ":troop_no", 0),
           (this_or_next|troop_slot_ge, ":troop_no", slot_troop_banner_scene_prop, 1),
           (eq, ":troop_no", "trp_player"),
           (assign, ":banner_troop", ":troop_no"),
         (else_try),
           (is_between, ":troop_no", companions_begin, companions_end),
           (assign, ":banner_troop", "trp_player"),
         (else_try),
           (assign, ":banner_mesh", "mesh_banners_default_a"),
         (try_end),
       (else_try),
         (eq, "$g_is_quick_battle", 1),
         (agent_get_team, ":agent_team", ":agent_no"),
         (try_begin),
           (eq, ":agent_team", 0),
           (assign, ":banner_mesh", "$g_quick_battle_team_0_banner"),
         (else_try),
           (assign, ":banner_mesh", "$g_quick_battle_team_1_banner"),
         (try_end),
       (else_try),
         (game_in_multiplayer_mode),
         (agent_get_group, ":agent_group", ":agent_no"),
         (try_begin),
           (neg|player_is_active, ":agent_group"),
           (agent_get_player_id, ":agent_group", ":agent_no"),
         (try_end),
         (try_begin),
           #if player banners are not allowed, use the default banner mesh
           (eq, "$g_multiplayer_allow_player_banners", 1),
           (player_is_active, ":agent_group"),
           (player_get_banner_id, ":player_banner", ":agent_group"),
           (ge, ":player_banner", 0),
           (store_add, ":banner_mesh", ":player_banner", arms_meshes_begin),
           (assign, ":already_used", 0),
           (try_for_range, ":cur_faction", npc_kingdoms_begin, npc_kingdoms_end), #wrong client data check
             (faction_slot_eq, ":cur_faction", slot_faction_banner, ":banner_mesh"),
             (assign, ":already_used", 1),
           (try_end),
           (eq, ":already_used", 0), #otherwise use the default banner mesh
         (else_try),
           (agent_get_team, ":agent_team", ":agent_no"),
           (team_get_faction, ":team_faction_no", ":agent_team"),

           (try_begin),
             (agent_is_human, ":agent_no"),
             (faction_get_slot, ":banner_mesh", ":team_faction_no", slot_faction_banner),
           (else_try),
             (agent_get_rider, ":rider_agent_no", ":agent_no"),
             #(agent_get_position, pos1, ":agent_no"),
             #(position_get_x, ":pos_x", pos1),
             #(position_get_y, ":pos_y", pos1),
             #(assign, reg0, ":pos_x"),
             #(assign, reg1, ":pos_y"),
             #(assign, reg2, ":agent_no"),
             #(display_message, "@{!}agent_no:{reg2}, pos_x:{reg0} , posy:{reg1}"),
             (try_begin),
               (ge, ":rider_agent_no", 0),
               (agent_is_active, ":rider_agent_no"),
               (agent_get_team, ":rider_agent_team", ":rider_agent_no"),
               (team_get_faction, ":rider_team_faction_no", ":rider_agent_team"),
               (faction_get_slot, ":banner_mesh", ":rider_team_faction_no", slot_faction_banner),
             (else_try),
               (assign, ":banner_mesh", "mesh_banners_default_c"),
             (try_end),                   
           (try_end),             
         (try_end),
       (else_try),
         (agent_get_troop_id, ":troop_id", ":agent_no"),
         (this_or_next|troop_slot_ge,  ":troop_id", slot_troop_banner_scene_prop, 1),
         (eq, ":troop_no", "trp_player"),
         (assign, ":banner_troop", ":troop_id"),
       (else_try),
         (agent_get_party_id, ":agent_party", ":agent_no"),
         (try_begin),
           (lt, ":agent_party", 0),
           (is_between, ":troop_id", companions_begin, companions_end),
           (main_party_has_troop, ":troop_id"),
           (assign, ":agent_party", "p_main_party"),
         (try_end),
         (ge, ":agent_party", 0),
         (party_get_template_id, ":party_template", ":agent_party"),
         (try_begin),
           (eq, ":party_template", "pt_deserters"),
           (assign, ":banner_mesh", "mesh_banners_default_c"),
         (else_try),
           (is_between, ":agent_party", centers_begin, centers_end),
           (is_between, ":troop_id", companions_begin, companions_end),
           (neq, "$talk_context", tc_tavern_talk),
           #this should be a captured companion in prison
           (assign, ":banner_troop", "trp_player"),
         (else_try),
           (is_between, ":agent_party", centers_begin, centers_end),
           (party_get_slot, ":town_lord", "$g_encountered_party", slot_town_lord),
           (ge, ":town_lord", 0),
           (assign, ":banner_troop", ":town_lord"),
         (else_try),
           (this_or_next|party_slot_eq, ":agent_party", slot_party_type, spt_kingdom_hero_party),
           (eq, ":agent_party", "p_main_party"),
           (party_get_num_companion_stacks, ":num_stacks", ":agent_party"),
           (gt, ":num_stacks", 0),
           (party_stack_get_troop_id, ":leader_troop_id", ":agent_party", 0),
           (this_or_next|troop_slot_ge,  ":leader_troop_id", slot_troop_banner_scene_prop, 1),
           (eq, ":leader_troop_id", "trp_player"),
           (assign, ":banner_troop", ":leader_troop_id"),
         (try_end),
       (else_try), #Check if we are in a tavern
         (eq, "$talk_context", tc_tavern_talk),
         (neq, ":troop_no", "trp_player"),
         (assign, ":banner_mesh", "mesh_banners_default_d"),
       (else_try), #can't find party, this can be a town guard
         (neq, ":troop_no", "trp_player"),
         (is_between, "$g_encountered_party", walled_centers_begin, walled_centers_end),
         (party_get_slot, ":town_lord", "$g_encountered_party", slot_town_lord),
         (ge, ":town_lord", 0),
         (assign, ":banner_troop", ":town_lord"),
       (try_end),
       (try_begin),
         (ge, ":banner_troop", 0),
         (try_begin),
           (neg|troop_slot_ge, ":banner_troop", slot_troop_banner_scene_prop, 1),
           (assign, ":banner_mesh", "mesh_banners_default_b"),
         (else_try), 
           (troop_get_slot, ":banner_spr", ":banner_troop", slot_troop_banner_scene_prop),
           (store_add, ":banner_scene_props_end", banner_scene_props_end_minus_one, 1),
           (is_between, ":banner_spr", banner_scene_props_begin, ":banner_scene_props_end"),
           (val_sub, ":banner_spr", banner_scene_props_begin),
           (store_add, ":banner_mesh", ":banner_spr", arms_meshes_begin),
         (try_end),
       (try_end),
       (assign, reg0, ":banner_mesh"),
     ]),
  #script_shield_item_set_banner
  # INPUT: agent_no
  # OUTPUT: none
  ("shield_item_set_banner",
    [
       (store_script_param, ":tableau_no",1),
       (store_script_param, ":agent_no", 2),
       (store_script_param, ":troop_no", 3),
       (call_script, "script_agent_troop_get_banner_mesh", ":agent_no", ":troop_no"),
       (cur_item_set_tableau_material, ":tableau_no", reg0),
     ]),

  
  #script_troop_agent_set_banner
  # INPUT: agent_no
  # OUTPUT: none
  ("troop_agent_set_banner",
    [
       (store_script_param, ":tableau_no",1),
       (store_script_param, ":agent_no", 2),
       (store_script_param, ":troop_no", 3),
       (call_script, "script_agent_troop_get_banner_mesh", ":agent_no", ":troop_no"),
       (cur_agent_set_banner_tableau_material, ":tableau_no", reg0),
     ]),

##  #script_shield_item_set_banner
##  # INPUT: agent_no
##  # OUTPUT: none
##  ("shield_item_set_banner",
##    [
##       (store_script_param, ":tableau_no",1),
##       (store_script_param, ":agent_no", 2),
##       (store_script_param, ":troop_no", 3),
##       (assign, ":banner_troop", -1),
##       (try_begin),
##         (lt, ":agent_no", 0),
##         (try_begin),
##           (ge, ":troop_no", 0),
##           (troop_slot_ge, ":troop_no", slot_troop_banner_scene_prop, 0),
##           (assign, ":banner_troop", ":troop_no"),
##         (else_try),
##           (assign, ":banner_troop", -2),
##         (try_end),
##       (else_try),
##         (agent_get_troop_id, ":troop_id", ":agent_no"),
##         (troop_slot_ge,  ":troop_id", slot_troop_custom_banner_flag_type, 0),
##         (assign, ":banner_troop", ":troop_id"),
##       (else_try),
##         (agent_get_party_id, ":agent_party", ":agent_no"),
##         (try_begin),
##           (lt, ":agent_party", 0),
##           (is_between, ":troop_id", companions_begin, companions_end),
##           (main_party_has_troop, ":troop_id"),
##           (assign, ":agent_party", "p_main_party"),
##         (try_end),
##         (ge, ":agent_party", 0),
##         (party_get_template_id, ":party_template", ":agent_party"),
##         (try_begin),
##           (eq, ":party_template", "pt_deserters"),
##           (assign, ":banner_troop", -3),
##         (else_try),
##           (is_between, ":agent_party", centers_begin, centers_end),
##           (party_get_slot, ":town_lord", "$g_encountered_party", slot_town_lord),
##           (ge, ":town_lord", 0),
##           (assign, ":banner_troop", ":town_lord"),
##         (else_try),
##           (this_or_next|party_slot_eq, ":agent_party", slot_party_type, spt_kingdom_hero_party),
##           (             eq, ":agent_party", "p_main_party"),
##           (party_get_num_companion_stacks, ":num_stacks", ":agent_party"),
##           (gt, ":num_stacks", 0),
##           (party_stack_get_troop_id, ":leader_troop_id", ":agent_party", 0),
##           (troop_slot_ge,  ":leader_troop_id", slot_troop_banner_scene_prop, 1),
##           (assign, ":banner_troop", ":leader_troop_id"),
##         (try_end),
##       (else_try), #Check if we are in a tavern
##         (eq, "$talk_context", tc_tavern_talk),
##         (neq, ":troop_no", "trp_player"),
##         (assign, ":banner_troop", -4),
##       (else_try), #can't find party, this can be a town guard
##         (neq, ":troop_no", "trp_player"),
##         (is_between, "$g_encountered_party", walled_centers_begin, walled_centers_end),
##         (party_get_slot, ":town_lord", "$g_encountered_party", slot_town_lord),
##         (ge, ":town_lord", 0),
##         (assign, ":banner_troop", ":town_lord"),
##       (try_end),
##       (cur_item_set_tableau_material, ":tableau_no", ":banner_troop"),
##     ]),

  #script_add_troop_to_cur_tableau
  # INPUT: troop_no
  # OUTPUT: none
  ("add_troop_to_cur_tableau",
    [
       (store_script_param, ":troop_no",1),

       (set_fixed_point_multiplier, 100),
       (assign, ":banner_mesh", -1),
       (troop_get_slot, ":banner_spr", ":troop_no", slot_troop_banner_scene_prop),
       (store_add, ":banner_scene_props_end", banner_scene_props_end_minus_one, 1),
       (try_begin),
         (is_between, ":banner_spr", banner_scene_props_begin, ":banner_scene_props_end"),
         (val_sub, ":banner_spr", banner_scene_props_begin),
         (store_add, ":banner_mesh", ":banner_spr", banner_meshes_begin),
       (try_end),

       (cur_tableau_clear_override_items),
       
#       (cur_tableau_set_override_flags, af_override_fullhelm),
       (cur_tableau_set_override_flags, af_override_head|af_override_weapons),
       
       (init_position, pos2),
       (cur_tableau_set_camera_parameters, 1, 6, 6, 10, 10000),

       (init_position, pos5),
       (assign, ":eye_height", 162),
       (store_mul, ":camera_distance", ":troop_no", 87323),
#       (val_mod, ":camera_distance", 5),
       (assign, ":camera_distance", 139),
       (store_mul, ":camera_yaw", ":troop_no", 124337),
       (val_mod, ":camera_yaw", 50),
       (val_add, ":camera_yaw", -25),
       (store_mul, ":camera_pitch", ":troop_no", 98123),
       (val_mod, ":camera_pitch", 20),
       (val_add, ":camera_pitch", -14),
       (assign, ":animation", "anim_stand_man"),
       
##       (troop_get_inventory_slot, ":horse_item", ":troop_no", ek_horse),
##       (try_begin),
##         (gt, ":horse_item", 0),
##         (assign, ":eye_height", 210),
##         (cur_tableau_add_horse, ":horse_item", pos2, anim_horse_stand, 0),
##         (assign, ":animation", anim_ride_0),
##         (position_set_z, pos5, 125),
##         (try_begin),
##           (is_between, ":camera_yaw", -10, 10), #make sure horse head doesn't obstruct face.
##           (val_min, ":camera_pitch", -5),
##         (try_end),
##       (try_end),
       (position_set_z, pos5, ":eye_height"),

       # camera looks towards -z axis
       (position_rotate_x, pos5, -90),
       (position_rotate_z, pos5, 180),

       # now apply yaw and pitch
       (position_rotate_y, pos5, ":camera_yaw"),
       (position_rotate_x, pos5, ":camera_pitch"),
       (position_move_z, pos5, ":camera_distance", 0),
       (position_move_x, pos5, 5, 0),

       (try_begin),
         (ge, ":banner_mesh", 0),

         (init_position, pos1),
         (position_set_z, pos1, -1500),
         (position_set_x, pos1, 265),
         (position_set_y, pos1, 400),
         (position_transform_position_to_parent, pos3, pos5, pos1),
         (cur_tableau_add_mesh, ":banner_mesh", pos3, 400, 0),
       (try_end),
       (cur_tableau_add_troop, ":troop_no", pos2, ":animation" , 0),

       (cur_tableau_set_camera_position, pos5),

       (copy_position, pos8, pos5),
       (position_rotate_x, pos8, -90), #y axis aligned with camera now. z is up
       (position_rotate_z, pos8, 30), 
       (position_rotate_x, pos8, -60), 
       (cur_tableau_add_sun_light, pos8, 175,150,125),
     ]),

  #script_add_troop_to_cur_tableau_for_character
  # INPUT: troop_no
  # OUTPUT: none
  ("add_troop_to_cur_tableau_for_character",
    [
       (store_script_param, ":troop_no",1),

       (set_fixed_point_multiplier, 100),

       (cur_tableau_clear_override_items),
       (cur_tableau_set_override_flags, af_override_fullhelm),
##       (cur_tableau_set_override_flags, af_override_head|af_override_weapons),
       
       (init_position, pos2),
       (cur_tableau_set_camera_parameters, 1, 4, 8, 10, 10000),

       (init_position, pos5),
       (assign, ":cam_height", 150),
#       (val_mod, ":camera_distance", 5),
       (assign, ":camera_distance", 360),
       (assign, ":camera_yaw", -15),
       (assign, ":camera_pitch", -18),
       (assign, ":animation", anim_stand_man),
       
       (position_set_z, pos5, ":cam_height"),

       # camera looks towards -z axis
       (position_rotate_x, pos5, -90),
       (position_rotate_z, pos5, 180),

       # now apply yaw and pitch
       (position_rotate_y, pos5, ":camera_yaw"),
       (position_rotate_x, pos5, ":camera_pitch"),
       (position_move_z, pos5, ":camera_distance", 0),
       (position_move_x, pos5, 5, 0),

       (try_begin),
         (troop_is_hero, ":troop_no"),
         (cur_tableau_add_troop, ":troop_no", pos2, ":animation", -1),
       (else_try),
         (store_mul, ":random_seed", ":troop_no", 126233),
         (val_mod, ":random_seed", 1000),
         (val_add, ":random_seed", 1),
         (cur_tableau_add_troop, ":troop_no", pos2, ":animation", ":random_seed"),
       (try_end),
       (cur_tableau_set_camera_position, pos5),

       (copy_position, pos8, pos5),
       (position_rotate_x, pos8, -90), #y axis aligned with camera now. z is up
       (position_rotate_z, pos8, 30), 
       (position_rotate_x, pos8, -60), 
       (cur_tableau_add_sun_light, pos8, 175,150,125),
     ]),

  #script_add_troop_to_cur_tableau_for_inventory
  # INPUT: troop_no
  # OUTPUT: none
  ("add_troop_to_cur_tableau_for_inventory",
    [
       (store_script_param, ":troop_no",1),
       (store_mod, ":side", ":troop_no", 4), #side flag is inside troop_no value
       (val_div, ":troop_no", 4), #removing the flag bit
       (val_mul, ":side", 90), #to degrees

       (set_fixed_point_multiplier, 100),

       (cur_tableau_clear_override_items),
       
       (init_position, pos2),
       (position_rotate_z, pos2, ":side"),
       (cur_tableau_set_camera_parameters, 1, 4, 6, 10, 10000),

       (init_position, pos5),
       (assign, ":cam_height", 105),
#       (val_mod, ":camera_distance", 5),
       (assign, ":camera_distance", 380),
       (assign, ":camera_yaw", -15),
       (assign, ":camera_pitch", -18),
       (assign, ":animation", anim_stand_man),
       
       (position_set_z, pos5, ":cam_height"),

       # camera looks towards -z axis
       (position_rotate_x, pos5, -90),
       (position_rotate_z, pos5, 180),

       # now apply yaw and pitch
       (position_rotate_y, pos5, ":camera_yaw"),
       (position_rotate_x, pos5, ":camera_pitch"),
       (position_move_z, pos5, ":camera_distance", 0),
       (position_move_x, pos5, 5, 0),

       (try_begin),
         (troop_is_hero, ":troop_no"),
         (cur_tableau_add_troop, ":troop_no", pos2, ":animation", -1),
       (else_try),
         (store_mul, ":random_seed", ":troop_no", 126233),
         (val_mod, ":random_seed", 1000),
         (val_add, ":random_seed", 1),
         (cur_tableau_add_troop, ":troop_no", pos2, ":animation", ":random_seed"),
       (try_end),
       (cur_tableau_set_camera_position, pos5),

       (copy_position, pos8, pos5),
       (position_rotate_x, pos8, -90), #y axis aligned with camera now. z is up
       (position_rotate_z, pos8, 30), 
       (position_rotate_x, pos8, -60), 
       (cur_tableau_add_sun_light, pos8, 175,150,125),
     ]),

  #script_add_troop_to_cur_tableau_for_profile
  # INPUT: troop_no
  # OUTPUT: none
  ("add_troop_to_cur_tableau_for_profile",
    [
       (store_script_param, ":troop_no",1),

       (set_fixed_point_multiplier, 100),

       (cur_tableau_clear_override_items),
       
       (cur_tableau_set_camera_parameters, 1, 4, 6, 10, 10000),

       (init_position, pos5),
       (assign, ":cam_height", 105),
#       (val_mod, ":camera_distance", 5),
       (assign, ":camera_distance", 380),
       (assign, ":camera_yaw", -15),
       (assign, ":camera_pitch", -18),
       (assign, ":animation", anim_stand_man),
       
       (position_set_z, pos5, ":cam_height"),

       # camera looks towards -z axis
       (position_rotate_x, pos5, -90),
       (position_rotate_z, pos5, 180),

       # now apply yaw and pitch
       (position_rotate_y, pos5, ":camera_yaw"),
       (position_rotate_x, pos5, ":camera_pitch"),
       (position_move_z, pos5, ":camera_distance", 0),
       (position_move_x, pos5, 5, 0),

       (profile_get_banner_id, ":profile_banner"),
       (try_begin),
         (ge, ":profile_banner", 0),
         (init_position, pos2),
         (val_add, ":profile_banner", banner_meshes_begin),
         (position_set_x, pos2, -175),
         (position_set_y, pos2, -300),
         (position_set_z, pos2, 180),
         (position_rotate_x, pos2, 90),
         (position_rotate_y, pos2, -15),
         (cur_tableau_add_mesh, ":profile_banner", pos2, 0, 0),
       (try_end),

       (init_position, pos2),
       (try_begin),
         (troop_is_hero, ":troop_no"),
         (cur_tableau_add_troop, ":troop_no", pos2, ":animation", -1),
       (else_try),
         (store_mul, ":random_seed", ":troop_no", 126233),
         (val_mod, ":random_seed", 1000),
         (val_add, ":random_seed", 1),
         (cur_tableau_add_troop, ":troop_no", pos2, ":animation", ":random_seed"),
       (try_end),
       (cur_tableau_set_camera_position, pos5),

       (copy_position, pos8, pos5),
       (position_rotate_x, pos8, -90), #y axis aligned with camera now. z is up
       (position_rotate_z, pos8, 30), 
       (position_rotate_x, pos8, -60), 
       (cur_tableau_add_sun_light, pos8, 175,150,125),
     ]),

  #script_add_troop_to_cur_tableau_for_retirement
  # INPUT: type
  # OUTPUT: none
  ("add_troop_to_cur_tableau_for_retirement", [
    (store_script_param, ":type", 1),
    (cur_tableau_set_override_flags, af_override_everything),

    (try_begin),
      (eq, ":type", 0),
      (cur_tableau_add_override_item, "itm_pilgrim_hood"),
      (cur_tableau_add_override_item, "itm_pilgrim_disguise"),
      (cur_tableau_add_override_item, "itm_wrapping_boots"),
      (assign, ":animation", "anim_pose_1"),
    (else_try),
      (eq, ":type", 1),
      (cur_tableau_add_override_item, "itm_pilgrim_hood"),
      (cur_tableau_add_override_item, "itm_red_tunic"),
      (cur_tableau_add_override_item, "itm_wrapping_boots"),
      (cur_tableau_add_override_item, "itm_dagger"),
      (assign, ":animation", "anim_pose_1"),
    (else_try),
      (eq, ":type", 2),
      (cur_tableau_add_override_item, "itm_linen_tunic"),
      (cur_tableau_add_override_item, "itm_wrapping_boots"),
      (assign, ":animation", "anim_pose_2"),
    (else_try),
      (eq, ":type", 3),
      (cur_tableau_add_override_item, "itm_nomad_vest"),
      (cur_tableau_add_override_item, "itm_nomad_boots"),
      (assign, ":animation", "anim_pose_2"),
    (else_try),
      (eq, ":type", 4),
      (cur_tableau_add_override_item, "itm_leather_apron"),
      (cur_tableau_add_override_item, "itm_leather_boots"),
      (assign, ":animation", "anim_pose_3"),
    (else_try),
      (eq, ":type", 5),
      (cur_tableau_add_override_item, "itm_red_shirt"),
      (cur_tableau_add_override_item, "itm_woolen_hose"),
      (cur_tableau_add_override_item, "itm_fur_hat"),
      (assign, ":animation", "anim_pose_3"),
    (else_try),
      (eq, ":type", 6),
      (cur_tableau_add_override_item, "itm_red_gambeson"),
      (cur_tableau_add_override_item, "itm_leather_boots"),
      (cur_tableau_add_override_item, "itm_sword_medieval_c"),
      (assign, ":animation", "anim_pose_4"),
    (else_try),
      (eq, ":type", 7),
      (cur_tableau_add_override_item, "itm_nobleman_outfit"),
      (cur_tableau_add_override_item, "itm_blue_hose"),
      (cur_tableau_add_override_item, "itm_sword_medieval_c"),
      (assign, ":animation", "anim_pose_4"),
    (else_try),
      (eq, ":type", 8),
      (cur_tableau_add_override_item, "itm_courtly_outfit"),
      (cur_tableau_add_override_item, "itm_woolen_hose"),
      (cur_tableau_add_override_item, "itm_sword_medieval_c"),
      (assign, ":animation", "anim_pose_4"),
    (else_try),
##      (eq, ":type", 9),
      (cur_tableau_add_override_item, "itm_heraldic_mail_with_surcoat_for_tableau"),
      (cur_tableau_add_override_item, "itm_mail_boots_for_tableau"),
      (cur_tableau_add_override_item, "itm_sword_medieval_c"),
      (assign, ":animation", "anim_pose_5"),
##    (else_try), #not used
##      (cur_tableau_add_override_item, "itm_heraldic_mail_with_tabard"),
##      (cur_tableau_add_override_item, "itm_iron_greaves"),
##      (cur_tableau_add_override_item, "itm_sword_medieval_c"),
##      (assign, ":animation", "anim_pose_5"),
    (try_end),

##    (set_fixed_point_multiplier, 100),
##    (cur_tableau_set_background_color, 0x00000000),
##    (cur_tableau_set_ambient_light, 10,11,15),

##     (init_position, pos8),
##     (position_set_x, pos8, -210),
##     (position_set_y, pos8, 200),
##     (position_set_z, pos8, 300),
##     (cur_tableau_add_point_light, pos8, 550,500,450),


    (set_fixed_point_multiplier, 100),
    (cur_tableau_set_camera_parameters, 1, 6, 6, 10, 10000),
    (assign, ":cam_height", 155),
    (assign, ":camera_distance", 575),
    (assign, ":camera_yaw", -5),
    (assign, ":camera_pitch", 10),

    (init_position, pos5),
    (position_set_z, pos5, ":cam_height"),
    # camera looks towards -z axis
    (position_rotate_x, pos5, -90),
    (position_rotate_z, pos5, 180),
    # now apply yaw and pitch
    (position_rotate_y, pos5, ":camera_yaw"),
    (position_rotate_x, pos5, ":camera_pitch"),
    (position_move_z, pos5, ":camera_distance", 0),
    (position_move_x, pos5, 60, 0),

    (init_position, pos2),
    (cur_tableau_add_troop, "trp_player", pos2, ":animation", 0),
    (cur_tableau_set_camera_position, pos5),

    (copy_position, pos8, pos5),
    (position_rotate_x, pos8, -90), #y axis aligned with camera now. z is up
    (position_rotate_z, pos8, 30),
    (position_rotate_x, pos8, -60),
    (cur_tableau_add_sun_light, pos8, 175,150,125),
    ]),
  
  #script_add_troop_to_cur_tableau_for_party
  # INPUT: troop_no
  # OUTPUT: none
  ("add_troop_to_cur_tableau_for_party",
    [
       (store_script_param, ":troop_no",1),
       (store_mod, ":hide_weapons", ":troop_no", 2), #hide_weapons flag is inside troop_no value
       (val_div, ":troop_no", 2), #removing the flag bit

       (set_fixed_point_multiplier, 100),

       (cur_tableau_clear_override_items),
       (try_begin),
         (eq, ":hide_weapons", 1),
         (cur_tableau_set_override_flags, af_override_fullhelm|af_override_head|af_override_weapons),
       (try_end),
       
       (init_position, pos2),
       (cur_tableau_set_camera_parameters, 1, 6, 6, 10, 10000),

       (init_position, pos5),
       (assign, ":cam_height", 105),
#       (val_mod, ":camera_distance", 5),
       (assign, ":camera_distance", 450),
       (assign, ":camera_yaw", 15),
       (assign, ":camera_pitch", -18),
       (assign, ":animation", anim_stand_man),
       
       (troop_get_inventory_slot, ":horse_item", ":troop_no", ek_horse),
       (try_begin),
         (gt, ":horse_item", 0),
         (eq, ":hide_weapons", 0),
         (cur_tableau_add_horse, ":horse_item", pos2, "anim_horse_stand", 0),
         (assign, ":animation", "anim_ride_0"),
         (assign, ":camera_yaw", 23),
         (assign, ":cam_height", 150),
         (assign, ":camera_distance", 550),
       (try_end),
       (position_set_z, pos5, ":cam_height"),

       # camera looks towards -z axis
       (position_rotate_x, pos5, -90),
       (position_rotate_z, pos5, 180),

       # now apply yaw and pitch
       (position_rotate_y, pos5, ":camera_yaw"),
       (position_rotate_x, pos5, ":camera_pitch"),
       (position_move_z, pos5, ":camera_distance", 0),
       (position_move_x, pos5, 5, 0),

       (try_begin),
         (troop_is_hero, ":troop_no"),
         (cur_tableau_add_troop, ":troop_no", pos2, ":animation", -1),
       (else_try),
         (store_mul, ":random_seed", ":troop_no", 126233),
         (val_mod, ":random_seed", 1000),
         (val_add, ":random_seed", 1),
         (cur_tableau_add_troop, ":troop_no", pos2, ":animation", ":random_seed"),
       (try_end),
       (cur_tableau_set_camera_position, pos5),

       (copy_position, pos8, pos5),
       (position_rotate_x, pos8, -90), #y axis aligned with camera now. z is up
       (position_rotate_z, pos8, 30), 
       (position_rotate_x, pos8, -60), 
       (cur_tableau_add_sun_light, pos8, 175,150,125),
     ]),

  #script_get_prosperity_text_to_s50
  # INPUT: center_no
  # OUTPUT: none
  ("get_prosperity_text_to_s50",
    [(store_script_param, ":center_no", 1),
     (party_get_slot, ":prosperity", ":center_no", slot_town_prosperity),
     (val_div, ":prosperity", 20),
     (try_begin),
       (eq, ":prosperity", 0), #0..19
       (str_store_string, s50, "@Very Poor"),
     (else_try),
       (eq, ":prosperity", 1), #20..39
       (str_store_string, s50, "@Poor"),
     (else_try),
       (eq, ":prosperity", 2), #40..59
       (str_store_string, s50, "@Average"),
     (else_try),
       (eq, ":prosperity", 3), #60..79
       (str_store_string, s50, "@Rich"),
     (else_try),
       (str_store_string, s50, "@Very Rich"), #80..99
     (try_end),
     ]),

  #script_spawn_bandits
  # INPUT: none
  # OUTPUT: none
  ("spawn_bandits",
    [
     (set_spawn_radius,1),
	
	 (try_begin),
		(eq, "$cheat_mode", 1),
		(display_message, "@{!}DEBUG : Doing spawn bandit script"),
	 (try_end),
	 
	 (party_template_set_slot, "pt_steppe_bandits", slot_party_template_lair_type, "pt_steppe_bandit_lair"),
	 (party_template_set_slot, "pt_taiga_bandits", slot_party_template_lair_type, "pt_taiga_bandit_lair"),
	 (party_template_set_slot, "pt_mountain_bandits", slot_party_template_lair_type, "pt_mountain_bandit_lair"),
	 (party_template_set_slot, "pt_forest_bandits", slot_party_template_lair_type, "pt_forest_bandit_lair"),
	 (party_template_set_slot, "pt_sea_raiders", slot_party_template_lair_type, "pt_sea_raider_lair"),
	 (party_template_set_slot, "pt_desert_bandits", slot_party_template_lair_type, "pt_desert_bandit_lair"),
	
	 (party_template_set_slot, "pt_steppe_bandits", slot_party_template_lair_spawnpoint, "p_steppe_bandit_spawn_point"),
	 (party_template_set_slot, "pt_taiga_bandits", slot_party_template_lair_spawnpoint, "p_taiga_bandit_spawn_point"),
	 (party_template_set_slot, "pt_mountain_bandits", slot_party_template_lair_spawnpoint, "p_mountain_bandit_spawn_point"),
	 (party_template_set_slot, "pt_forest_bandits", slot_party_template_lair_spawnpoint, "p_forest_bandit_spawn_point"),
	 (party_template_set_slot, "pt_sea_raiders", slot_party_template_lair_spawnpoint, "p_sea_raider_spawn_point_1"),
	 (party_template_set_slot, "pt_desert_bandits", slot_party_template_lair_spawnpoint, "p_desert_bandit_spawn_point"),
		
     (try_begin),
       (store_num_parties_of_template, ":num_parties", "pt_mountain_bandits"),
       (lt,":num_parties",16), #was 14 at mount&blade, 18 in warband, 16 last decision
       (store_random,":spawn_point",num_mountain_bandit_spawn_points),
       (val_add,":spawn_point","p_mountain_bandit_spawn_point"),
       (set_spawn_radius, 25),
       (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",16), #was 14 at mount&blade, 18 in warband, 16 last decision
       (store_random,":spawn_point",num_forest_bandit_spawn_points),
       (val_add,":spawn_point","p_forest_bandit_spawn_point"),
       (set_spawn_radius, 25),
       (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",16), #was 14 at mount&blade, 18 in warband, 16 last decision
       (store_random,":spawn_point",num_sea_raider_spawn_points),
       (val_add,":spawn_point","p_sea_raider_spawn_point_1"),
       (set_spawn_radius, 25),
       (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",16), #was 14 at mount&blade, 18 in warband, 16 last decision
       (store_random,":spawn_point",num_steppe_bandit_spawn_points),
       (val_add,":spawn_point","p_steppe_bandit_spawn_point"),
       (set_spawn_radius, 25),
       (spawn_around_party,":spawn_point","pt_steppe_bandits"),
     (try_end),
     (try_begin),
       (store_num_parties_of_template, ":num_parties", "pt_taiga_bandits"),
       (lt,":num_parties",16), #was 14 at mount&blade, 18 in warband, 16 last decision
       (store_random,":spawn_point",num_taiga_bandit_spawn_points),
       (val_add,":spawn_point","p_taiga_bandit_spawn_point"),
       (set_spawn_radius, 25),
       (spawn_around_party,":spawn_point","pt_taiga_bandits"),
     (try_end),
     (try_begin),
       (store_num_parties_of_template, ":num_parties", "pt_desert_bandits"),
       (lt,":num_parties",16), #was 14 at mount&blade, 18 in warband, 16 last decision
       (store_random,":spawn_point",num_desert_bandit_spawn_points),
       (val_add,":spawn_point","p_desert_bandit_spawn_point"),
       (set_spawn_radius, 25),
       (spawn_around_party,":spawn_point","pt_desert_bandits"),
     (try_end),
     (try_begin),
       (store_num_parties_of_template, ":num_parties", "pt_looters"),
       (lt,":num_parties",42), #was 33 at mount&blade, 50 in warband, 42 last decision
       (store_random_in_range,":spawn_point",villages_begin,villages_end), #spawn looters twice to have lots of them at the beginning       
       (set_spawn_radius, 25),
       (spawn_around_party,":spawn_point","pt_looters"),
       (assign, ":spawned_party_id", reg0),
       (try_begin),
         (check_quest_active, "qst_deal_with_looters"),
         (party_set_flags, ":spawned_party_id", pf_quest_party, 1),
       (else_try),
         (party_set_flags, ":spawned_party_id", pf_quest_party, 0),
       (try_end),
     (try_end),
     (try_begin),
       (store_num_parties_of_template, ":num_parties", "pt_deserters"),
       (lt,":num_parties",15),
       (set_spawn_radius, 4),
       (try_for_range, ":troop_no", active_npcs_begin, active_npcs_end),
	     (troop_slot_eq, ":troop_no", slot_troop_occupation, slto_kingdom_hero),
         (store_random_in_range, ":random_no", 0, 100),
         (lt, ":random_no", 5),
         (troop_get_slot, ":party_no", ":troop_no", slot_troop_leaded_party),
         (store_troop_faction, ":troop_faction", ":troop_no"),
         (neq, ":troop_faction", "fac_player_supporters_faction"),
         (gt, ":party_no", 0),
         (neg|party_is_in_any_town, ":party_no"),
##         (party_get_attached_to, ":attached_party_no", ":party_no"),
##         (lt, ":attached_party_no", 0),#in wilderness
         (spawn_around_party, ":party_no", "pt_deserters"),
         (assign, ":new_party", reg0),
         (store_troop_faction, ":faction_no", ":troop_no"),
         (faction_get_slot, ":tier_1_troop", ":faction_no", slot_faction_tier_1_troop),
         (store_character_level, ":level", "trp_player"),
         (store_mul, ":max_number_to_add", ":level", 2),
         (val_add, ":max_number_to_add", 11),
         (store_random_in_range, ":number_to_add", 10, ":max_number_to_add"),
         (party_add_members, ":new_party", ":tier_1_troop", ":number_to_add"),
         (store_random_in_range, ":random_no", 1, 4),
         (try_for_range, ":unused", 0, ":random_no"),
           (party_upgrade_with_xp, ":new_party", 1000000, 0),
         (try_end),
##         (str_store_party_name, s1, ":party_no"),
##         (call_script, "script_get_closest_center", ":party_no"),
##         (try_begin),
##           (gt, reg0, 0),
##           (str_store_party_name, s2, reg0),
##         (else_try),
##           (str_store_string, s2, "@unknown place"),
##         (try_end),
##         (assign, reg1, ":number_to_add"),
##         (display_message, "@{reg1} Deserters spawned from {s1}, near {s2}."),
       (try_end),
     (try_end), #deserters ends
	 
	 
	 #Spawn bandit lairs
	(try_for_range, ":bandit_template", "pt_steppe_bandits", "pt_deserters"),
		(party_template_get_slot, ":bandit_lair_party", ":bandit_template", slot_party_template_lair_party),
		(le, ":bandit_lair_party", 1),
		
		(party_template_get_slot, ":bandit_lair_template", ":bandit_template", slot_party_template_lair_type),
		(party_template_get_slot, ":bandit_lair_template_spawnpoint", ":bandit_template", slot_party_template_lair_spawnpoint),
	 
		(set_spawn_radius, 20),
	 
        (spawn_around_party, ":bandit_lair_template_spawnpoint", ":bandit_lair_template"),
		(assign, ":new_camp", reg0),
		
		(party_set_slot, ":new_camp", slot_party_type, spt_bandit_lair),
		
		(str_store_party_name, s4, ":new_camp"),
		
		(party_get_position, pos4, ":new_camp"),
        #(party_set_flags, ":new_camp", pf_icon_mask, 1),
		
		(party_get_current_terrain, ":new_camp_terrain", ":new_camp"),
		(position_get_z, ":elevation", pos4),
		(position_get_y, ":lair_y", pos4),		
								
		(assign, ":center_too_close", 0),
		(try_for_range, ":center", centers_begin, centers_end),
			(eq, ":center_too_close", 0),
			(store_distance_to_party_from_party, ":distance", ":new_camp", ":center"),
			(lt, ":distance", 3),
			(assign, ":center_too_close", 1),
		(try_end),
						
		(try_begin),
			(eq, ":center_too_close", 1),
			(party_is_active, ":new_camp"),
			(remove_party, ":new_camp"),
			(party_template_set_slot, ":bandit_template", slot_party_template_lair_party, 0),			
		(else_try),
			(eq, ":bandit_template", "pt_sea_raiders"),
			(eq, ":new_camp_terrain", 3),
			(map_get_water_position_around_position, pos5, pos4, 4),			
			(party_template_set_slot, ":bandit_template", slot_party_template_lair_party, ":new_camp"),
			(party_set_flags, ":new_camp", pf_disabled, 1),			
		(else_try),	
			(eq, ":bandit_template", "pt_mountain_bandits"),
			(eq, ":new_camp_terrain", 3),
			(gt, ":elevation", 250),			
			(party_template_set_slot, ":bandit_template", slot_party_template_lair_party, ":new_camp"),
			(party_set_flags, ":new_camp", pf_disabled, 1),			
		(else_try),
			(eq, ":bandit_template", "pt_desert_bandits"),
			(eq, ":new_camp_terrain", 5),
			(gt, ":lair_y", -9000),
			(gt, ":elevation", 125),
			(party_template_set_slot, ":bandit_template", slot_party_template_lair_party, ":new_camp"),
			(party_set_flags, ":new_camp", pf_disabled, 1),			
		(else_try),	
			(eq, ":bandit_template", "pt_steppe_bandits"),
			(this_or_next|eq, ":new_camp_terrain", 2),
			(eq, ":new_camp_terrain", 10),
			(this_or_next|eq, ":new_camp_terrain", 10),
			(gt, ":elevation", 200),
			(party_template_set_slot, ":bandit_template", slot_party_template_lair_party, ":new_camp"),
			(party_set_flags, ":new_camp", pf_disabled, 1),			
		(else_try),	
			(eq, ":bandit_template", "pt_taiga_bandits"),
			(eq, ":new_camp_terrain", 12),				
			(party_template_set_slot, ":bandit_template", slot_party_template_lair_party, ":new_camp"),
			(party_set_flags, ":new_camp", pf_disabled, 1),
		(else_try),	
			(eq, ":bandit_template", "pt_forest_bandits"),
			(eq, ":new_camp_terrain", 11),				
			(party_template_set_slot, ":bandit_template", slot_party_template_lair_party, ":new_camp"),
			(party_set_flags, ":new_camp", pf_disabled, 1),			
		(else_try),
			(party_is_active, ":new_camp"),
			(str_store_party_name, s4, ":new_camp"),
			(remove_party, ":new_camp"),
			(party_template_set_slot, ":bandit_template", slot_party_template_lair_party, 0),
		(else_try),
		(try_end),	 	 
	(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),
     #(assign, "$num_routed_us", 0), #these should not assign to 0 here to protect routed agents to spawn again in next turns.
     #(assign, "$num_routed_allies", 0),
     #(assign, "$num_routed_enemies", 0),

     #initialize all routed counts of troops
     (try_for_agents, ":cur_agent"),
       (agent_is_human, ":cur_agent"),     
       (agent_get_party_id, ":agent_party", ":cur_agent"),
       (agent_get_troop_id, ":agent_troop_id", ":cur_agent"),
       (troop_set_slot, ":agent_troop_id", slot_troop_player_routed_agents, 0),
       (troop_set_slot, ":agent_troop_id", slot_troop_ally_routed_agents, 0),
       (troop_set_slot, ":agent_troop_id", slot_troop_enemy_routed_agents, 0),
     (try_end),
     
     (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"),
         (assign, "$any_allies_at_the_last_battle", 1),
       (try_end),
       #count routed agents in player party, ally parties and enemy parties
       (try_begin),
         (agent_is_routed, ":cur_agent"),
         (agent_get_slot, ":agent_was_running_away", ":cur_agent", slot_agent_is_running_away),
         (eq, ":agent_was_running_away", 1),
         (try_begin),
           (agent_get_troop_id, ":routed_ag_troop_id", ":cur_agent"),
           (agent_get_party_id, ":routed_ag_party_id", ":cur_agent"),
           #only enemies
           #only regulars           
           (store_faction_of_party, ":faction_of_routed_agent_party", ":routed_ag_party_id"),
              
           (try_begin),
             (eq, ":agent_party", "p_main_party"),
             (val_add, "$num_routed_us", 1),
           (else_try),
             (agent_is_ally, ":cur_agent"),     
             (val_add, "$num_routed_allies", 1),
           (else_try),
             #for now only count and include routed enemy agents in new routed party.
             (val_add, "$num_routed_enemies", 1),
             (faction_get_slot, ":num_routed_agents_in_this_faction", ":faction_of_routed_agent_party", slot_faction_num_routed_agents),
             (val_add, ":num_routed_agents_in_this_faction", 1),
             (faction_set_slot, ":faction_of_routed_agent_party", slot_faction_num_routed_agents, ":num_routed_agents_in_this_faction"),           
             (party_add_members, "p_routed_enemies", ":routed_ag_troop_id", 1),     
           (try_end),
         (try_end),
         (agent_get_troop_id, ":agent_troop_id", ":cur_agent"),
         (try_begin),
           (eq, ":agent_party", "p_main_party"),
           (troop_get_slot, ":player_routed_agents", ":agent_troop_id", slot_troop_player_routed_agents),
           (val_add, ":player_routed_agents", 1),
           (troop_set_slot, ":agent_troop_id", slot_troop_player_routed_agents, ":player_routed_agents"),
           
         (else_try),
           (agent_is_ally, ":cur_agent"),     
           (troop_get_slot, ":ally_routed_agents", ":agent_troop_id", slot_troop_ally_routed_agents),
           (val_add, ":ally_routed_agents", 1),
           (troop_set_slot, ":agent_troop_id", slot_troop_ally_routed_agents, ":ally_routed_agents"),
           
         (else_try),
           (troop_get_slot, ":enemy_routed_agents", ":agent_troop_id", slot_troop_enemy_routed_agents),
           (val_add, ":enemy_routed_agents", 1),
           (troop_set_slot, ":agent_troop_id", slot_troop_enemy_routed_agents, ":enemy_routed_agents"),

         (try_end),   
       (try_end),
       #count and save killed agents in player party, ally parties and enemy parties
       (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"),
         (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),
       (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),
     (party_get_skill_level, reg0, "p_main_party", ":skill_no"),
      (assign, reg0, ":max_skill"),
     (assign, reg1, ":skill_owner"),
     ]),

  #script_upgrade_hero_party
  # INPUT: arg1 = party_id, arg2 = xp_amount
  ("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_get_improvement_details
  # INPUT: arg1 = improvement
  # OUTPUT: reg0 = base_cost
  ("get_improvement_details",
    [(store_script_param, ":improvement_no", 1),
     (try_begin),
       (eq, ":improvement_no", slot_center_has_manor),
       (str_store_string, s0, "@Manor"),
       (str_store_string, s1, "@A manor lets you rest at the village and pay your troops half wages while you rest."),
       (assign, reg0, 8000),
     (else_try),
       (eq, ":improvement_no", slot_center_has_fish_pond),
       (str_store_string, s0, "@Mill"),
       (str_store_string, s1, "@A mill increases village prosperity by 5%."),
       (assign, reg0, 6000),
     (else_try),
       (eq, ":improvement_no", slot_center_has_watch_tower),
       (str_store_string, s0, "@Watch Tower"),
       (str_store_string, s1, "@A watch tower lets the villagers raise alarm earlier. The time it takes for enemies to loot the village increases by 50%."),
       (assign, reg0, 5000),
     (else_try),
       (eq, ":improvement_no", slot_center_has_school),
       (str_store_string, s0, "@School"),
       (str_store_string, s1, "@A school increases the loyalty of the villagers to you by +1 every week."),
       (assign, reg0, 9000),
	   
	 # NE building
     (else_try),
       (eq, ":improvement_no", slot_center_has_cattle_ranch),
       (str_store_string, s0, "@Cattle Ranch"),
       (str_store_string, s1, "@A cattle ranch increases the growth rate of the village's cattle and eliminates the possiblity of a famine."),
       (assign, reg0, 10000),
       (assign, reg1, 2), #Lumber
       (assign, reg2, 1), #Iron
       (assign, reg3, 1), #Tools
     (else_try),
       (eq, ":improvement_no", slot_center_has_palisade),
       (str_store_string, s0, "@Palisade"),
       (str_store_string, s1, "@A palisade is a simple wooden wall around the village that helps protect from enemies.  The time it takes for enemies to loot the village increases by 25%."),
       (assign, reg0, 7000),
       (assign, reg1, 2), #Lumber
       (assign, reg2, 0), #Iron
       (assign, reg3, 0), #Tools
     (else_try),
       (eq, ":improvement_no", slot_center_has_horse_ranch),
       (str_store_string, s0, "@Horse Ranch"),
       (str_store_string, s1, "@A horse ranch increases village prosperity by 2% every two weeks and allows horses to be purchased from the village."),
       (assign, reg0, 12000),
       (assign, reg1, 3), #Lumber
       (assign, reg2, 2), #Iron
       (assign, reg3, 1), #Tools
     (else_try),
       (eq, ":improvement_no", slot_center_has_distillery),
       (str_store_string, s0, "@Distillery"),
       (str_store_string, s1, "@A distillery increases village prosperity by 2% every month and allows wine and ale to be purchased from the village."),
       (assign, reg0, 5000),
       (assign, reg1, 1), #Lumber
       (assign, reg2, 1), #Iron
       (assign, reg3, 0), #Tools
     (else_try),
       (eq, ":improvement_no", slot_center_has_caltrops),
       (str_store_string, s0, "@Caltrops"),
       (str_store_string, s1, "@Caltrops are set around the village when enemies are sighted.  It prevents horses from being used in the attack, but it also prevents them from being used in the defense."),
       (assign, reg0, 3000),
       (assign, reg1, 0), #Lumber
       (assign, reg2, 1), #Iron
       (assign, reg3, 0), #Tools
    # NE end building	   
     (else_try),
       (eq, ":improvement_no", slot_center_has_messenger_post),
       (str_store_string, s0, "@Messenger Post"),
       (str_store_string, s1, "@A messenger post lets the inhabitants send you a message whenever enemies are nearby, even if you are far away from here."),
       (assign, reg0, 4000),
     (else_try),
       (eq, ":improvement_no", slot_center_has_prisoner_tower),
       (str_store_string, s0, "@Prison Tower"),
       (str_store_string, s1, "@A prison tower reduces the chance of captives held here running away successfully."),
       (assign, reg0, 7000),
	   
	   
	 # NE building
	   (else_try),
       (eq, ":improvement_no", slot_center_has_caravan_escort),
       (str_store_string, s0, "@Caravan Escort Outpost"),
       (str_store_string, s1, "@A caravan escort outpost sends 30 extra mercenaries with any caravan that originates from the town, more than enough to defend from the wandering mercenary war parties."),
       (assign, reg0, 6000),
       (assign, reg1, 1), #Lumber
       (assign, reg2, 1), #Iron
       (assign, reg3, 0), #Tools
     (else_try),
       (eq, ":improvement_no", slot_center_has_bookstore),
       (str_store_string, s0, "@Bookstore"),
       (str_store_string, s1, "@A bookstore adds a random weekly selection of books to the goods vendor."),
       (assign, reg0, 4000),
       (assign, reg1, 1), #Lumber
       (assign, reg2, 0), #Iron
       (assign, reg3, 0), #Tools
     (else_try),
       (eq, ":improvement_no", slot_center_has_festival_square),
       (str_store_string, s0, "@Festival Square"),
       (str_store_string, s1, "@A festival square allows the town to have a regular bazaar and hold monthly festivals.  The loyalty of a town increases monthly and party morale increases for every day spent in town."),
       (assign, reg0, 6000),
       (assign, reg1, 0), #Lumber
       (assign, reg2, 0), #Iron
       (assign, reg3, 1), #Tools
     (else_try),
       (eq, ":improvement_no", slot_center_has_blacksmith),
       (str_store_string, s0, "@Blacksmith"),
       (str_store_string, s1, "@A blacksmith provides unlimited arrows and bolts for siege defenders."),
       (assign, reg0, 8000),
       (assign, reg1, 2), #Lumber
       (assign, reg2, 2), #Iron
       (assign, reg3, 1), #Tools
     (else_try),
       (eq, ":improvement_no", slot_center_has_cathedral),
       (str_store_string, s0, "@Cathedral"),
       (str_store_string, s1, "@A cathedral allows the most powerful Swadian troops to be recruited."),
       (assign, reg0, 55000),
       (assign, reg1, 4), #Lumber
       (assign, reg2, 4), #Iron
       (assign, reg3, 2), #Tools
     (else_try),
       (eq, ":improvement_no", slot_center_has_ivory_temple),
       (str_store_string, s0, "@Ivory Temple"),
       (str_store_string, s1, "@An ivory temple allows the most powerful Vaegris troops to be recruited."),
       (assign, reg0, 50000),
       (assign, reg1, 4), #Lumber
       (assign, reg2, 4), #Iron
       (assign, reg3, 2), #Tools
     (else_try),
       (eq, ":improvement_no", slot_center_has_palace),
       (str_store_string, s0, "@Palace"),
       (str_store_string, s1, "@A palace allows the most powerful Khergit troops to be recruited."),
       (assign, reg0, 45000),
       (assign, reg1, 4), #Lumber
       (assign, reg2, 4), #Iron
       (assign, reg3, 2), #Tools
     (else_try),
       (eq, ":improvement_no", slot_center_has_hall),
       (str_store_string, s0, "@Halls of Glory"),
       (str_store_string, s1, "@The halls of glory allow the most powerful Nord troops to be recruited."),
       (assign, reg0, 45000),
       (assign, reg1, 4), #Lumber
       (assign, reg2, 4), #Iron
       (assign, reg3, 2), #Tools
     (else_try),
       (eq, ":improvement_no", slot_center_has_chambers),
       (str_store_string, s0, "@Council Chambers"),
       (str_store_string, s1, "@The council chambers allow the most powerful Rhodokian troops to be recruited."),
       (assign, reg0, 50000),
       (assign, reg1, 4), #Lumber
       (assign, reg2, 4), #Iron
       (assign, reg3, 2), #Tools
	 (else_try),
       (eq, ":improvement_no", slot_center_has_baths),
       (str_store_string, s0, "@House of Swords"),
       (str_store_string, s1, "@The baths allow the most powerful Sarranid troops to be recruited."),
       (assign, reg0, 50000),
       (assign, reg1, 4), #Lumber
       (assign, reg2, 4), #Iron
       (assign, reg3, 2), #Tools
     (else_try),
       (eq, ":improvement_no", slot_center_university_placeholder),
       (str_store_string, s0, "@University"),
       (str_store_string, s1, "@A university provides random scientific breakthroughs and improvements to the kingdom."),
       (assign, reg0, 40000),
       (assign, reg1, 0), #Lumber
       (assign, reg2, 0), #Iron
       (assign, reg3, 0), #Tools
	   # NE end build
     (try_end),
     ]),
  
  #script_cf_troop_agent_is_alive
  # INPUT: arg1 = troop_id
  ("cf_troop_agent_is_alive",
    [(store_script_param, ":troop_no", 1),
     (assign, ":alive_count", 0),
     (try_for_agents, ":cur_agent"),
       (agent_get_troop_id, ":cur_agent_troop", ":cur_agent"),
       (eq, ":troop_no", ":cur_agent_troop"),
       (agent_is_alive, ":cur_agent"),
       (val_add, ":alive_count", 1),
     (try_end),
     (gt, ":alive_count", 0),
     ]),

  #script_cf_village_recruit_volunteers_cond
  # INPUT: none
  # OUTPUT: none
  ("cf_village_recruit_volunteers_cond",
    [
	
	 (try_begin),
		(eq, "$cheat_mode", 1),
		(display_message, "str_checking_volunteer_availability_script"),
	 (try_end),
	 
	 (neg|party_slot_eq, "$current_town", slot_village_state, svs_looted),
     (neg|party_slot_eq, "$current_town", slot_village_state, svs_being_raided),
     (neg|party_slot_ge, "$current_town", slot_village_infested_by_bandits, 1),
	  # NE quests 
	 	 # v585 Josefgirl
     (neg|party_slot_ge, "$current_town", slot_village_infested_by_wedding, 1),	 
	 #endv585 Josef
	 # NE end quests 
     (store_faction_of_party, ":village_faction", "$current_town"),
     (party_get_slot, ":center_relation", "$current_town", slot_center_player_relation),
     (store_relation, ":village_faction_relation", ":village_faction", "fac_player_faction"),
	 
     (ge, ":center_relation", 0),
	 (try_begin),
		(eq, "$cheat_mode", 1),
		(display_message, "str_center_relation_at_least_zero"),
	 (try_end),
	 
	 
	 
	 
     (this_or_next|ge, ":center_relation", 5),
     (this_or_next|eq, ":village_faction", "$players_kingdom"),
     (this_or_next|ge, ":village_faction_relation", 0),
     (this_or_next|eq, ":village_faction", "$supported_pretender_old_faction"),
		(eq, "$players_kingdom", 0),

	 (try_begin),
		(eq, "$cheat_mode", 1),
		(display_message, "str_relationfaction_conditions_met"),
	 (try_end),

		
     (party_slot_ge, "$current_town", slot_center_volunteer_troop_amount, 0),
     (party_slot_ge, "$current_town", slot_center_volunteer_troop_type, 1),
	 
	 (try_begin),
		(eq, "$cheat_mode", 1),
		(display_message, "str_troops_available"),
	 (try_end),
	 
	 
     (party_get_free_companions_capacity, ":free_capacity", "p_main_party"),
     (ge, ":free_capacity", 1),
	 
	 (try_begin),
		(eq, "$cheat_mode", 1),
		(display_message, "str_party_has_capacity"),
	 (try_end),
	 
	 
     ]),

  #script_village_recruit_volunteers_recruit
  # INPUT: none
  # OUTPUT: none
  ("village_recruit_volunteers_recruit",
    [(party_get_slot, ":volunteer_troop", "$current_town", slot_center_volunteer_troop_type),
     (party_get_slot, ":volunteer_amount", "$current_town", slot_center_volunteer_troop_amount),
     (party_get_free_companions_capacity, ":free_capacity", "p_main_party"),
     (val_min, ":volunteer_amount", ":free_capacity"),
     (store_troop_gold, ":gold", "trp_player"),
	 # NE
     (try_begin), #Recruit nobles from towns now too - Jinnai
       (party_slot_eq, "$current_town", slot_party_type, spt_town),
       (try_begin), 
         (eq,"$setting_use_new_noble_recruit_system",1),
         (assign, ":cost",100),
       (else_try),
         (assign, ":cost",50),
       (try_end),
     (else_try),
       (assign,":cost",10),
     (try_end),
     (store_div, ":gold_capacity", ":gold", ":cost"),#10 denars per man
     (val_min, ":volunteer_amount", ":gold_capacity"),
     (party_add_members, "p_main_party", ":volunteer_troop", ":volunteer_amount"),
     (party_set_slot, "$current_town", slot_center_volunteer_troop_amount, -1),
     (store_mul, ":totalcost", ":volunteer_amount", ":cost"),#10 denars per man
     (troop_remove_gold, "trp_player", ":totalcost"),
     (val_mul,":totalcost",-1),
     (call_script, "script_adjust_finances", slot_finance_wages, ":totalcost"),
	 # ne end finances
     ]),

  #script_get_troop_item_amount
  # INPUT: arg1 = troop_no, arg2 = item_no
  # OUTPUT: reg0 = item_amount
  ("get_troop_item_amount",
    [(store_script_param, ":troop_no", 1),
     (store_script_param, ":item_no", 2),
     (troop_get_inventory_capacity, ":inv_cap", ":troop_no"),
     (assign, ":count", 0),
     (try_for_range, ":i_slot", 0, ":inv_cap"),
       (troop_get_inventory_slot, ":cur_item", ":troop_no", ":i_slot"),
       (eq, ":cur_item", ":item_no"),
       (val_add, ":count", 1),
     (try_end),
     (assign, reg0, ":count"),
     ]),

  #script_get_name_from_dna_to_s50
  # INPUT: arg1 = dna
  # OUTPUT: s50 = name
  ("get_name_from_dna_to_s50",
    [(store_script_param, ":dna", 1),
     (store_sub, ":num_names", names_end, names_begin),
     (store_sub, ":num_surnames", surnames_end, surnames_begin),
     (assign, ":selected_name", ":dna"),
     (val_mod, ":selected_name", ":num_names"),
     (assign, ":selected_surname", ":dna"),
     (val_div, ":selected_surname", ":num_names"),
     (val_mod, ":selected_surname", ":num_surnames"),
     (val_add, ":selected_name", names_begin),
     (val_add, ":selected_surname", surnames_begin),
     (str_store_string, s50, ":selected_name"),
     (str_store_string, s50, ":selected_surname"),
     ]),
     
  #script_change_center_prosperity
  # INPUT: arg1 = center_no, arg2 = difference
  # OUTPUT: none
  ("change_center_prosperity",
    [(store_script_param, ":center_no", 1),
     (store_script_param, ":difference", 2),
     (party_get_slot, ":old_prosperity", ":center_no", slot_town_prosperity),
     (store_add, ":new_prosperity", ":old_prosperity", ":difference"),
     (val_clamp, ":new_prosperity", 0, 100),
     (store_div, ":old_state", ":old_prosperity", 20),
     (store_div, ":new_state", ":new_prosperity", 20),
	 
     (try_begin),
       (neq, ":old_state", ":new_state"),
	   (neg|is_between, ":center_no", castles_begin, castles_end),
	   
       (str_store_party_name_link, s2, ":center_no"),
       (call_script, "script_get_prosperity_text_to_s50", ":center_no"),
       (str_store_string, s3, s50),
       (party_set_slot, ":center_no", slot_town_prosperity, ":new_prosperity"),
       (call_script, "script_get_prosperity_text_to_s50", ":center_no"),
       (str_store_string, s4, s50),
       (try_begin),
         (party_slot_eq, ":center_no", slot_town_lord, "trp_player"),
         (display_message, "@Prosperity of {s2} has changed from {s3} to {s4}."),
       (try_end),
       (call_script, "script_update_center_notes", ":center_no"),
     (else_try),
       (party_set_slot, ":center_no", slot_town_prosperity, ":new_prosperity"),
     (try_end),
	 
	 (try_begin),
		(store_current_hours, ":hours"),
		(gt, ":hours", 1),
		(store_sub, ":actual_difference", ":new_prosperity", ":old_prosperity"),
		(try_begin),
			(lt, ":actual_difference", 0),
			(val_add, "$newglob_total_prosperity_losses", ":actual_difference"),
	    (else_try),
			(gt, ":actual_difference", 0),
			(val_add, "$newglob_total_prosperity_gains", ":actual_difference"),
		(try_end),
	 (try_end),
	 
	 #This will add up all non-trade prosperity
	 (try_begin),
		(eq, "$cheat_mode", 3),
		(assign, reg4, "$newglob_total_prosperity_from_bandits"), 
		(assign, reg5, "$newglob_total_prosperity_from_caravan_trade"),	 
	    (assign, reg7, "$newglob_total_prosperity_from_villageloot"), 
	    (assign, reg8, "$newglob_total_prosperity_from_townloot"),	 
	    (assign, reg9, "$newglob_total_prosperity_from_village_trade"),
	    (assign, reg10, "$newglob_total_prosperity_from_convergence"),
	    (assign, reg11, "$newglob_total_prosperity_losses"),
	    (assign, reg12, "$newglob_total_prosperity_gains"),
		(display_message, "@{!}DEBUG: Total prosperity actual losses: {reg11}"),
		(display_message, "@{!}DEBUG: Total prosperity actual gains: {reg12}"),
		
		(display_message, "@{!}DEBUG: Prosperity changes from random bandits: {reg4}"),
		(display_message, "@{!}DEBUG: Prosperity changes from caravan trades: {reg5}"),
		(display_message, "@{!}DEBUG: Prosperity changes from farmer trades: {reg9}"),
		(display_message, "@{!}DEBUG: Prosperity changes from looted villages: {reg7}"),
		(display_message, "@{!}DEBUG: Prosperity changes from sieges: {reg8}"),
		(display_message, "@{!}DEBUG: Theoretical prosperity changes from convergence: {reg10}"),
	 (try_end),
	 
     ]),

  #script_get_center_ideal_prosperity
  # INPUT: arg1 = center_no
  # OUTPUT: reg0 = ideal_prosperity
  ("get_center_ideal_prosperity",
    [(store_script_param, ":center_no", 1),
     (assign, ":ideal", 65),
       (call_script, "script_center_get_goods_availability", ":center_no"),
       (store_mul, ":hardship_index", reg0, 2),
       (val_sub, ":ideal", ":hardship_index"),   

     (try_begin),
       (is_between, ":center_no", villages_begin, villages_end),
       (party_slot_eq, ":center_no", slot_center_has_fish_pond, 1),
       (val_add, ":ideal", 5),
     (try_end),
	
	# NE building
	       (try_begin),
         (party_slot_eq, ":center_no", slot_center_has_horse_ranch, 1),
         (val_add, ":ideal", 2),
       (try_end),
       (try_begin),
         (party_slot_eq, ":center_no", slot_center_has_distillery, 1),
         (val_add, ":ideal", 2),
       (try_end),
	   
	   # NE end building
	   
#     (try_begin),
#       (is_between, ":center_no", villages_begin, villages_end),
#       (try_begin),
#         (party_slot_eq, ":center_no", slot_center_has_fish_pond, 1),
#         (val_add, ":ideal", 5),
#       (try_end),
#       (party_get_slot, ":land_quality", ":center_no", slot_village_land_quality),
#       (val_mul, ":land_quality", 3),
#       (val_add, ":ideal", ":land_quality"),
#       (party_get_slot, ":num_cattle", ":center_no", slot_village_number_of_cattle),
#       (val_div, ":num_cattle", 20),
#       (val_add, ":ideal", ":num_cattle"),
#     (else_try),
#       (try_for_range, ":village_no", villages_begin, villages_end),
#         (party_slot_eq, ":village_no", slot_village_bound_center, ":center_no"),
#         (party_get_slot, ":prosperity", ":village_no", slot_town_prosperity),
#         (val_div, ":prosperity", 20),
#         (val_add, ":ideal", ":prosperity"),
#       (try_end),
#     (try_end),

     (val_max, ":ideal", 0),

     (assign, reg0, ":ideal"),
     ]),

  ("good_price_affects_good_production",
	[
	(store_script_param, ":center", 1),	 
	(store_script_param, ":input_item_no", 2),	 
	(store_script_param, ":production", 3),	 
	(store_script_param, ":impact_divisor", 4),	 

	(assign, reg4, ":production"),

	
	
	(try_begin),
		(gt, ":production", 0), #let's take -20 as the zero production rate, although in actuality production can go lower, representing increased demand
	
		(store_sub, ":input_good_price_slot", ":input_item_no", trade_goods_begin),
		(val_add, ":input_good_price_slot", slot_town_trade_good_prices_begin),
		(party_get_slot, ":input_price", ":center", ":input_good_price_slot"),
	
		

		(try_begin), #1/2 impact for low prices
			(lt, ":input_price", 1000),
			(val_mul, ":impact_divisor", 2),
		(try_end),
		
		(try_begin),
			(gt, ":impact_divisor", 1),
			(val_sub, ":input_price", 1000),
			(val_div, ":input_price", ":impact_divisor"),
			(val_add, ":input_price", 1000),
		(try_end),
		

		(val_mul, ":production", 1000),
		(val_div, ":production", ":input_price"),
	
#		(assign, reg5, ":production"),
#		(str_store_item_name, s4, ":input_item_no"),
#		(display_message, "@{s4} price of {reg3} reduces production from {reg4} to {reg5}"),
		
	(try_end),
	
		
	(assign, reg0, ":production"),
	
	]),
	


	
  #script_get_poorest_village_of_faction
  # INPUT: arg1 = center_no
  # OUTPUT: reg0 = ideal_prosperity
  ("get_poorest_village_of_faction",
    [(store_script_param, ":faction_no", 1),
     (assign, ":min_prosperity_village", -1),
     (assign, ":min_prosperity", 101),
     (try_for_range, ":village_no", villages_begin, villages_end),
       (store_faction_of_party, ":village_faction", ":village_no"),
       (eq, ":village_faction", ":faction_no"),
       (party_get_slot, ":prosperity", ":village_no", slot_town_prosperity),
       (lt, ":prosperity", ":min_prosperity"),
       (assign, ":min_prosperity", ":prosperity"),
       (assign, ":min_prosperity_village", ":village_no"),
     (try_end),
     (assign, reg0, ":min_prosperity_village"),
     ]),

  #script_troop_add_gold
  # INPUT: arg1 = troop_no, arg2 = amount
  # OUTPUT: none
  ("troop_add_gold",
    [
      (store_script_param, ":troop_no", 1),
      (store_script_param, ":amount", 2),
      
      (troop_add_gold, ":troop_no", ":amount"),
      (try_begin),
        (eq, ":troop_no", "trp_player"),
        (play_sound, "snd_money_received"),
      (try_end),
     ]),     

#NPC companion changes begin
  ("initialize_npcs",
    [

# set strings

        (troop_set_slot, "trp_npc1", slot_troop_morality_type, tmt_egalitarian),  #borcha
        (troop_set_slot, "trp_npc1", slot_troop_morality_value, 4),  #borcha
        (troop_set_slot, "trp_npc1", slot_troop_2ary_morality_type, tmt_aristocratic),  #borcha
        (troop_set_slot, "trp_npc1", slot_troop_2ary_morality_value, -1),
        (troop_set_slot, "trp_npc1", slot_troop_personalityclash_object, "trp_npc7"),  #borcha - deshavi
        (troop_set_slot, "trp_npc1", slot_troop_personalityclash2_object, "trp_npc16"),  #borcha - klethi
        (troop_set_slot, "trp_npc1", slot_troop_personalitymatch_object, "trp_npc2"),  #borcha - marnid
        (troop_set_slot, "trp_npc1", slot_troop_home, "p_village_25"), #Dashbiga
        (troop_set_slot, "trp_npc1", slot_troop_payment_request, 300), 
		(troop_set_slot, "trp_npc1", slot_troop_kingsupport_argument, argument_ruler),
		(troop_set_slot, "trp_npc1", slot_troop_kingsupport_opponent, "trp_npc14"), #lezalit
		(troop_set_slot, "trp_npc1", slot_troop_town_with_contacts, "p_town_17"), #ichamur
		(troop_set_slot, "trp_npc1", slot_troop_original_faction, 0), #ichamur
		(troop_set_slot, "trp_npc1", slot_lord_reputation_type, lrep_roguish), #
	## NE Companion party additions
        (troop_set_slot, "trp_npc1", slot_troop_original_faction, fac_kingdom_5),
        (troop_set_slot, "trp_npc1", slot_troop_honor_req, -100),
        (troop_set_slot, "trp_npc1", slot_troop_renown_req, 0),	
		
		
        (troop_set_slot, "trp_npc2", slot_troop_morality_type, tmt_humanitarian), #marnid
        (troop_set_slot, "trp_npc2", slot_troop_morality_value, 2),  
        (troop_set_slot, "trp_npc2", slot_troop_2ary_morality_type, tmt_honest),  
        (troop_set_slot, "trp_npc2", slot_troop_2ary_morality_value, 1),
        (troop_set_slot, "trp_npc2", slot_troop_personalityclash_object, "trp_npc5"), #marnid - beheshtur
        (troop_set_slot, "trp_npc2", slot_troop_personalityclash2_object, "trp_npc9"), #marnid - alayen
        (troop_set_slot, "trp_npc2", slot_troop_personalitymatch_object, "trp_npc1"),  #marnid - borcha
        (troop_set_slot, "trp_npc2", slot_troop_home, "p_town_1"), #Sargoth
        (troop_set_slot, "trp_npc2", slot_troop_payment_request, 0), 
		(troop_set_slot, "trp_npc2", slot_troop_kingsupport_argument, argument_victory),
		(troop_set_slot, "trp_npc2", slot_troop_kingsupport_opponent, "trp_npc16"), #klethi
		(troop_set_slot, "trp_npc2", slot_troop_town_with_contacts, "p_town_1"), #Sargoth
		(troop_set_slot, "trp_npc2", slot_troop_original_faction, 0), #ichamur
		(troop_set_slot, "trp_npc2", slot_lord_reputation_type, lrep_custodian), #

		        (troop_set_slot, "trp_npc2", slot_troop_original_faction, fac_kingdom_2),
        (troop_set_slot, "trp_npc2", slot_troop_honor_req, -100),
        (troop_set_slot, "trp_npc2", slot_troop_renown_req, 0),
		
		
#
        (troop_set_slot, "trp_npc3", slot_troop_morality_type, tmt_humanitarian), #Ymira -> Xerina
        (troop_set_slot, "trp_npc3", slot_troop_morality_value, 4),  
        (troop_set_slot, "trp_npc3", slot_troop_2ary_morality_type, tmt_aristocratic), 
        (troop_set_slot, "trp_npc3", slot_troop_2ary_morality_value, -1),
        (troop_set_slot, "trp_npc3", slot_troop_personalityclash_object, "trp_npc14"), #Ymira - artimenner
        (troop_set_slot, "trp_npc3", slot_troop_personalityclash2_object, "trp_npc8"), #Ymira - matheld
        (troop_set_slot, "trp_npc3", slot_troop_personalitymatch_object, "trp_npc9"), #Ymira - alayen
        (troop_set_slot, "trp_npc3", slot_troop_home, "p_town_3"), #Veluca
        (troop_set_slot, "trp_npc3", slot_troop_payment_request, 0), 
		(troop_set_slot, "trp_npc3", slot_troop_kingsupport_argument, argument_lords),
		(troop_set_slot, "trp_npc3", slot_troop_kingsupport_opponent, "trp_npc5"), #klethi
		(troop_set_slot, "trp_npc3", slot_troop_town_with_contacts, "p_town_15"), #yalen
		(troop_set_slot, "trp_npc3", slot_troop_original_faction, 0), #ichamur
		(troop_set_slot, "trp_npc3", slot_lord_reputation_type, lrep_benefactor), #

	    (troop_set_slot, "trp_npc3", slot_troop_payment_request, 12000), 
        (troop_set_slot, "trp_npc3", slot_troop_original_faction, fac_kingdom_1),
        (troop_set_slot, "trp_npc3", slot_troop_honor_req, 6),
        (troop_set_slot, "trp_npc3", slot_troop_renown_req, 0),	
		
        (troop_set_slot, "trp_npc4", slot_troop_morality_type, tmt_aristocratic), #Rolf
        (troop_set_slot, "trp_npc4", slot_troop_morality_value, 4),  
        (troop_set_slot, "trp_npc4", slot_troop_2ary_morality_type, tmt_honest), 
        (troop_set_slot, "trp_npc4", slot_troop_2ary_morality_value, -1),
        (troop_set_slot, "trp_npc4", slot_troop_personalityclash_object, "trp_npc10"), #Rolf - bunduk
        (troop_set_slot, "trp_npc4", slot_troop_personalityclash2_object, "trp_npc7"), #Rolf - deshavi
        (troop_set_slot, "trp_npc4", slot_troop_personalitymatch_object, "trp_npc5"), #Rolf - beheshtur
        (troop_set_slot, "trp_npc4", slot_troop_home, "p_village_34"), #Ehlerdah
        (troop_set_slot, "trp_npc4", slot_troop_payment_request, 300), 
		(troop_set_slot, "trp_npc4", slot_troop_kingsupport_argument, argument_claim),
		(troop_set_slot, "trp_npc4", slot_troop_kingsupport_opponent, "trp_npc6"), #firentis
		(troop_set_slot, "trp_npc4", slot_troop_town_with_contacts, "p_town_3"), #veluca
		(troop_set_slot, "trp_npc4", slot_troop_original_faction, 0), #ichamur
		(troop_set_slot, "trp_npc4", slot_lord_reputation_type, lrep_cunning), #
		
        (troop_set_slot, "trp_npc4", slot_troop_payment_request, 500), 
        (troop_set_slot, "trp_npc4", slot_troop_original_faction, fac_kingdom_4),
        (troop_set_slot, "trp_npc4", slot_troop_honor_req, -100),
        (troop_set_slot, "trp_npc4", slot_troop_renown_req, 0),
		
        (troop_set_slot, "trp_npc5", slot_troop_morality_type, tmt_egalitarian),  #beheshtur
        (troop_set_slot, "trp_npc5", slot_troop_morality_value, 3),  #beheshtur
        (troop_set_slot, "trp_npc5", slot_troop_2ary_morality_type, -1),
        (troop_set_slot, "trp_npc5", slot_troop_2ary_morality_value, 0),
        (troop_set_slot, "trp_npc5", slot_troop_personalityclash_object, "trp_npc2"),  #beheshtur - marnid
        (troop_set_slot, "trp_npc5", slot_troop_personalityclash2_object, "trp_npc11"),  #beheshtur- katrin
        (troop_set_slot, "trp_npc5", slot_troop_personalitymatch_object, "trp_npc4"),  #beheshtur - rolf
        (troop_set_slot, "trp_npc5", slot_troop_home, "p_town_14"), #Halmar
        (troop_set_slot, "trp_npc5", slot_troop_payment_request, 400),
		(troop_set_slot, "trp_npc5", slot_troop_kingsupport_argument, argument_ruler),
		(troop_set_slot, "trp_npc5", slot_troop_kingsupport_opponent, "trp_npc9"), #firentis
		(troop_set_slot, "trp_npc5", slot_troop_town_with_contacts, "p_town_10"), #tulga
		(troop_set_slot, "trp_npc5", slot_troop_original_faction, "fac_kingdom_3"), #khergit
		(troop_set_slot, "trp_npc5", slot_lord_reputation_type, lrep_cunning), #

        (troop_set_slot, "trp_npc5", slot_troop_honor_req, -100),
        (troop_set_slot, "trp_npc5", slot_troop_renown_req, 0),
		
		
		
        (troop_set_slot, "trp_npc6", slot_troop_morality_type, tmt_humanitarian), #firenz
        (troop_set_slot, "trp_npc6", slot_troop_morality_value, 2),  #beheshtur
        (troop_set_slot, "trp_npc6", slot_troop_2ary_morality_type, tmt_honest),
        (troop_set_slot, "trp_npc6", slot_troop_2ary_morality_value, 1),
        (troop_set_slot, "trp_npc6", slot_troop_personalityclash_object, "trp_npc11"), #firenz
        (troop_set_slot, "trp_npc6", slot_troop_personalityclash2_object, "trp_npc13"), #firenz - nizar
        (troop_set_slot, "trp_npc6", slot_troop_personalitymatch_object, "trp_npc12"),  #firenz - jeremus
        (troop_set_slot, "trp_npc6", slot_troop_home, "p_town_4"), #Suno
        (troop_set_slot, "trp_npc6", slot_troop_payment_request, 0),
		(troop_set_slot, "trp_npc6", slot_troop_kingsupport_argument, argument_victory),
		(troop_set_slot, "trp_npc6", slot_troop_kingsupport_opponent, "trp_npc8"), #firentis
		(troop_set_slot, "trp_npc6", slot_troop_town_with_contacts, "p_town_7"), #uxkhal
		(troop_set_slot, "trp_npc6", slot_troop_original_faction, "fac_kingdom_1"), #swadia
		(troop_set_slot, "trp_npc6", slot_lord_reputation_type, lrep_upstanding), #

        (troop_set_slot, "trp_npc6", slot_troop_honor_req, -100),
        (troop_set_slot, "trp_npc6", slot_troop_renown_req, 0),
		
        (troop_set_slot, "trp_npc7", slot_troop_morality_type, tmt_egalitarian),  #deshavi
        (troop_set_slot, "trp_npc7", slot_troop_morality_value, 3),  #beheshtur
        (troop_set_slot, "trp_npc7", slot_troop_2ary_morality_type, -1),
        (troop_set_slot, "trp_npc7", slot_troop_2ary_morality_value, 0),
        (troop_set_slot, "trp_npc7", slot_troop_personalityclash_object, "trp_npc1"),  #deshavi
        (troop_set_slot, "trp_npc7", slot_troop_personalityclash2_object, "trp_npc4"),  #deshavi - rolf
        (troop_set_slot, "trp_npc7", slot_troop_personalitymatch_object, "trp_npc16"),  #deshavi - klethi
        (troop_set_slot, "trp_npc7", slot_troop_home, "p_village_5"), #Kulum
#        (troop_set_slot, "trp_npc7", slot_troop_payment_request, 300),
		(troop_set_slot, "trp_npc7", slot_troop_kingsupport_argument, argument_victory),
		(troop_set_slot, "trp_npc7", slot_troop_kingsupport_opponent, "trp_npc3"), #ymira
		(troop_set_slot, "trp_npc7", slot_troop_town_with_contacts, "p_town_2"), #tihr
		(troop_set_slot, "trp_npc7", slot_troop_original_faction, 0), #swadia
		(troop_set_slot, "trp_npc7", slot_lord_reputation_type, lrep_custodian), #

        (troop_set_slot, "trp_npc7", slot_troop_original_faction, fac_kingdom_5),
        (troop_set_slot, "trp_npc7", slot_troop_honor_req, -100),
        (troop_set_slot, "trp_npc7", slot_troop_renown_req, 0),
		
		
        (troop_set_slot, "trp_npc8", slot_troop_morality_type, tmt_aristocratic), #matheld
        (troop_set_slot, "trp_npc8", slot_troop_morality_value, 3),  #beheshtur
        (troop_set_slot, "trp_npc8", slot_troop_2ary_morality_type, -1),
        (troop_set_slot, "trp_npc8", slot_troop_2ary_morality_value, 0),
        (troop_set_slot, "trp_npc8", slot_troop_personalityclash_object, "trp_npc12"), #matheld
        (troop_set_slot, "trp_npc8", slot_troop_personalityclash2_object, "trp_npc3"), #matheld - ymira
        (troop_set_slot, "trp_npc8", slot_troop_personalitymatch_object, "trp_npc13"),  #matheld - nizar
        (troop_set_slot, "trp_npc8", slot_troop_home, "p_sea_raider_spawn_point_2"), #Gundig's Point
       # (troop_set_slot, "trp_npc8", slot_troop_payment_request, 500),
		(troop_set_slot, "trp_npc8", slot_troop_kingsupport_argument, argument_lords),
		(troop_set_slot, "trp_npc8", slot_troop_kingsupport_opponent, "trp_npc2"), #marnid
		(troop_set_slot, "trp_npc8", slot_troop_town_with_contacts, "p_town_12"), #wercheg
		(troop_set_slot, "trp_npc8", slot_troop_original_faction, "fac_kingdom_4"), #nords
		(troop_set_slot, "trp_npc8", slot_lord_reputation_type, lrep_martial), #

		(troop_set_slot, "trp_npc8", slot_troop_payment_request, 700),
        (troop_set_slot, "trp_npc8", slot_troop_honor_req, 9),
        (troop_set_slot, "trp_npc8", slot_troop_renown_req, 0),
		
		
        (troop_set_slot, "trp_npc9", slot_troop_morality_type, tmt_aristocratic), #alayen
        (troop_set_slot, "trp_npc9", slot_troop_morality_value, 2),  #beheshtur
        (troop_set_slot, "trp_npc9", slot_troop_2ary_morality_type, tmt_honest),
        (troop_set_slot, "trp_npc9", slot_troop_2ary_morality_value, 1),
        (troop_set_slot, "trp_npc9", slot_troop_personalityclash_object, "trp_npc13"), #alayen vs nizar
        (troop_set_slot, "trp_npc9", slot_troop_personalityclash2_object, "trp_npc2"), #alayen vs marnid
        (troop_set_slot, "trp_npc9", slot_troop_personalitymatch_object, "trp_npc3"),  #alayen - ymira
        (troop_set_slot, "trp_npc9", slot_troop_home, "p_town_13"), #Rivacheg
        # (troop_set_slot, "trp_npc9", slot_troop_payment_request, 300),
		(troop_set_slot, "trp_npc9", slot_troop_kingsupport_argument, argument_lords),
		(troop_set_slot, "trp_npc9", slot_troop_kingsupport_opponent, "trp_npc1"), #borcha
		(troop_set_slot, "trp_npc9", slot_troop_town_with_contacts, "p_town_8"), #reyvadin
		(troop_set_slot, "trp_npc9", slot_troop_original_faction, "fac_kingdom_2"), #vaegirs
		(troop_set_slot, "trp_npc9", slot_lord_reputation_type, lrep_martial), #
		
        (troop_set_slot, "trp_npc9", slot_troop_payment_request, 16000),
        (troop_set_slot, "trp_npc9", slot_troop_honor_req, 6),
        (troop_set_slot, "trp_npc9", slot_troop_renown_req, 0),
		
        (troop_set_slot, "trp_npc10", slot_troop_morality_type, tmt_humanitarian), #bunduk
        (troop_set_slot, "trp_npc10", slot_troop_morality_value, 2),
        (troop_set_slot, "trp_npc10", slot_troop_2ary_morality_type, tmt_egalitarian),
        (troop_set_slot, "trp_npc10", slot_troop_2ary_morality_value, 1),
        (troop_set_slot, "trp_npc10", slot_troop_personalityclash_object, "trp_npc4"), #bunduk vs rolf
        (troop_set_slot, "trp_npc10", slot_troop_personalityclash2_object, "trp_npc14"), #bunduk vs lazalet
        (troop_set_slot, "trp_npc10", slot_troop_personalitymatch_object, "trp_npc11"),  #bunduk likes katrin
        (troop_set_slot, "trp_npc10", slot_troop_home, "p_castle_28"), #Grunwalder Castle
        (troop_set_slot, "trp_npc10", slot_troop_payment_request, 200),
		(troop_set_slot, "trp_npc10", slot_troop_kingsupport_argument, argument_ruler),
		(troop_set_slot, "trp_npc10", slot_troop_kingsupport_opponent, "trp_npc7"), #nizar
		(troop_set_slot, "trp_npc10", slot_troop_town_with_contacts, "p_town_5"), #jelkala
		(troop_set_slot, "trp_npc10", slot_troop_original_faction, "fac_kingdom_5"), #rhodoks
		(troop_set_slot, "trp_npc10", slot_lord_reputation_type, lrep_benefactor), #

        (troop_set_slot, "trp_npc10", slot_troop_honor_req, -100),
        (troop_set_slot, "trp_npc10", slot_troop_renown_req, 0),
		
		
        (troop_set_slot, "trp_npc11", slot_troop_morality_type, tmt_egalitarian),  #katrin
        (troop_set_slot, "trp_npc11", slot_troop_morality_value, 3),
        (troop_set_slot, "trp_npc11", slot_troop_2ary_morality_type, -1),
        (troop_set_slot, "trp_npc11", slot_troop_2ary_morality_value, 0),
        (troop_set_slot, "trp_npc11", slot_troop_personalityclash_object, "trp_npc6"),  #katrin vs firenz
        (troop_set_slot, "trp_npc11", slot_troop_personalityclash2_object, "trp_npc5"),  #katrin - beheshtur
        (troop_set_slot, "trp_npc11", slot_troop_personalitymatch_object, "trp_npc10"),  #katrin likes bunduk
        (troop_set_slot, "trp_npc11", slot_troop_home, "p_town_6"), #Praven
        (troop_set_slot, "trp_npc11", slot_troop_payment_request, 100),
		(troop_set_slot, "trp_npc11", slot_troop_kingsupport_argument, argument_claim),
		(troop_set_slot, "trp_npc11", slot_troop_kingsupport_opponent, "trp_npc15"), #borcha
		(troop_set_slot, "trp_npc11", slot_troop_town_with_contacts, "p_town_6"), #praven
		(troop_set_slot, "trp_npc11", slot_troop_original_faction, 0), #	
		(troop_set_slot, "trp_npc11", slot_lord_reputation_type, lrep_custodian), #
		
        (troop_set_slot, "trp_npc11", slot_troop_honor_req, -100),
        (troop_set_slot, "trp_npc11", slot_troop_renown_req, 0),
		
		
        (troop_set_slot, "trp_npc12", slot_troop_morality_type, tmt_humanitarian), #jeremus
        (troop_set_slot, "trp_npc12", slot_troop_morality_value, 3),
        (troop_set_slot, "trp_npc12", slot_troop_2ary_morality_type, -1),
        (troop_set_slot, "trp_npc12", slot_troop_2ary_morality_value, 0),
        (troop_set_slot, "trp_npc12", slot_troop_personalityclash_object, "trp_npc8"), #jerem
        (troop_set_slot, "trp_npc12", slot_troop_personalityclash2_object, "trp_npc15"), #jeremus - artimenner
        (troop_set_slot, "trp_npc12", slot_troop_personalitymatch_object, "trp_npc6"),  #jeremus - firenz
        (troop_set_slot, "trp_npc12", slot_troop_home, "p_castle_16"), #undetermined #University
        (troop_set_slot, "trp_npc12", slot_troop_payment_request, 0),
		(troop_set_slot, "trp_npc12", slot_troop_kingsupport_argument, argument_claim),
		(troop_set_slot, "trp_npc12", slot_troop_kingsupport_opponent, "trp_npc13"), #nizar
		(troop_set_slot, "trp_npc12", slot_troop_town_with_contacts, "p_town_14"), #halmar
		(troop_set_slot, "trp_npc12", slot_troop_original_faction, 0), #	
		(troop_set_slot, "trp_npc12", slot_lord_reputation_type, lrep_benefactor), #

        (troop_set_slot, "trp_npc12", slot_troop_honor_req, -100),
        (troop_set_slot, "trp_npc12", slot_troop_renown_req, 0),
		
		
        (troop_set_slot, "trp_npc13", slot_troop_morality_type, tmt_aristocratic), #nizar
        (troop_set_slot, "trp_npc13", slot_troop_morality_value, 3),
        (troop_set_slot, "trp_npc13", slot_troop_2ary_morality_type, -1),
        (troop_set_slot, "trp_npc13", slot_troop_2ary_morality_value, 0),
        (troop_set_slot, "trp_npc13", slot_troop_personalityclash_object, "trp_npc9"), #nizar
        (troop_set_slot, "trp_npc13", slot_troop_personalityclash2_object, "trp_npc6"), #nizar - firenz
        (troop_set_slot, "trp_npc13", slot_troop_personalitymatch_object, "trp_npc8"), #nizar - matheld
        (troop_set_slot, "trp_npc13", slot_troop_home, "p_castle_15"), #Ergellon Castle
        (troop_set_slot, "trp_npc13", slot_troop_payment_request, 300),
		(troop_set_slot, "trp_npc13", slot_troop_kingsupport_argument, argument_claim),
		(troop_set_slot, "trp_npc13", slot_troop_kingsupport_opponent, "trp_npc10"), #nizar
		(troop_set_slot, "trp_npc13", slot_troop_town_with_contacts, "p_town_4"), #suno
		(troop_set_slot, "trp_npc13", slot_troop_original_faction, 0), #	
		(troop_set_slot, "trp_npc13", slot_lord_reputation_type, lrep_roguish), #

		(troop_set_slot, "trp_npc13", slot_troop_honor_req, -100),
        (troop_set_slot, "trp_npc13", slot_troop_renown_req, 0),
		
        (troop_set_slot, "trp_npc14", slot_troop_morality_type, tmt_aristocratic), #lezalit
        (troop_set_slot, "trp_npc14", slot_troop_morality_value, 4),
        (troop_set_slot, "trp_npc14", slot_troop_2ary_morality_type, tmt_egalitarian),
        (troop_set_slot, "trp_npc14", slot_troop_2ary_morality_value, -1),
        (troop_set_slot, "trp_npc14", slot_troop_personalityclash_object, "trp_npc3"), #lezalit
        (troop_set_slot, "trp_npc14", slot_troop_personalityclash2_object, "trp_npc10"), #lezalit - bunduk
        (troop_set_slot, "trp_npc14", slot_troop_personalitymatch_object, "trp_npc15"), #lezalit - artimenner
        (troop_set_slot, "trp_npc14", slot_troop_home, "p_castle_18"), #Ismirala Castle
        (troop_set_slot, "trp_npc14", slot_troop_payment_request, 400),
		(troop_set_slot, "trp_npc14", slot_troop_kingsupport_argument, argument_victory),
		(troop_set_slot, "trp_npc14", slot_troop_kingsupport_opponent, "trp_npc11"), #nizar
		(troop_set_slot, "trp_npc14", slot_troop_town_with_contacts, "p_town_16"), #dhirim
		(troop_set_slot, "trp_npc14", slot_troop_original_faction, 0), #	
		(troop_set_slot, "trp_npc14", slot_lord_reputation_type, lrep_selfrighteous), #

        (troop_set_slot, "trp_npc14", slot_troop_payment_request, 14000),
        (troop_set_slot, "trp_npc14", slot_troop_original_faction, fac_kingdom_1),
        (troop_set_slot, "trp_npc14", slot_troop_honor_req, -100),
        (troop_set_slot, "trp_npc14", slot_troop_renown_req, 200),
		
		
        (troop_set_slot, "trp_npc15", slot_troop_morality_type, tmt_egalitarian),  #artimenner
        (troop_set_slot, "trp_npc15", slot_troop_morality_value, 2),
        (troop_set_slot, "trp_npc15", slot_troop_2ary_morality_type, tmt_honest),
        (troop_set_slot, "trp_npc15", slot_troop_2ary_morality_value, 1),
        (troop_set_slot, "trp_npc15", slot_troop_personalityclash_object, "trp_npc16"), #artimenner - klethi
        (troop_set_slot, "trp_npc15", slot_troop_personalityclash2_object, "trp_npc12"), #artimenner - jeremus
        (troop_set_slot, "trp_npc15", slot_troop_personalitymatch_object, "trp_npc14"), #lazalit - artimenner
        (troop_set_slot, "trp_npc15", slot_troop_home, "p_castle_1"), #Culmarr Castle
        (troop_set_slot, "trp_npc15", slot_troop_payment_request, 300),
		(troop_set_slot, "trp_npc15", slot_troop_kingsupport_argument, argument_ruler),
		(troop_set_slot, "trp_npc15", slot_troop_kingsupport_opponent, "trp_npc4"), #nizar
 		(troop_set_slot, "trp_npc15", slot_troop_town_with_contacts, "p_town_18"), #narra
		(troop_set_slot, "trp_npc15", slot_lord_reputation_type, lrep_custodian), #

		        (troop_set_slot, "trp_npc15", slot_troop_payment_request, 18000),
        (troop_set_slot, "trp_npc15", slot_troop_original_faction, fac_kingdom_1),
        (troop_set_slot, "trp_npc15", slot_troop_honor_req, -100),
        (troop_set_slot, "trp_npc15", slot_troop_renown_req, 200),
		
        (troop_set_slot, "trp_npc16", slot_troop_morality_type, tmt_aristocratic), #klethi
        (troop_set_slot, "trp_npc16", slot_troop_morality_value, 4),
        (troop_set_slot, "trp_npc16", slot_troop_2ary_morality_type, tmt_humanitarian),
        (troop_set_slot, "trp_npc16", slot_troop_2ary_morality_value, -1),
        (troop_set_slot, "trp_npc16", slot_troop_personalityclash_object, "trp_npc15"), #klethi
        (troop_set_slot, "trp_npc16", slot_troop_personalityclash2_object, "trp_npc1"), #klethi - borcha
        (troop_set_slot, "trp_npc16", slot_troop_personalitymatch_object, "trp_npc7"),  #deshavi - klethi
        (troop_set_slot, "trp_npc16", slot_troop_home, "p_village_20"), #Uslum
        (troop_set_slot, "trp_npc16", slot_troop_payment_request, 200),
		(troop_set_slot, "trp_npc16", slot_troop_kingsupport_argument, argument_lords),
		(troop_set_slot, "trp_npc16", slot_troop_kingsupport_opponent, "trp_npc12"), #nizar
 		(troop_set_slot, "trp_npc16", slot_troop_town_with_contacts, "p_town_9"), #khudan
		(troop_set_slot, "trp_npc16", slot_lord_reputation_type, lrep_roguish), #

        (troop_set_slot, "trp_npc16", slot_troop_original_faction, fac_kingdom_3),
        (troop_set_slot, "trp_npc16", slot_troop_honor_req, -100),
        (troop_set_slot, "trp_npc16", slot_troop_renown_req, 0),

        (store_sub, "$number_of_npc_slots", slot_troop_strings_end, slot_troop_intro),

        (try_for_range, ":npc", companions_begin, companions_end),


            (try_for_range, ":slot_addition", 0, "$number_of_npc_slots"),
                (store_add, ":slot", ":slot_addition", slot_troop_intro),

                (store_mul, ":string_addition", ":slot_addition", 16),
                (store_add, ":string", "str_npc1_intro", ":string_addition"), 
                (val_add, ":string", ":npc"),
                (val_sub, ":string", companions_begin),

                (troop_set_slot, ":npc", ":slot", ":string"),
            (try_end),
        (try_end),
		

#Post 0907 changes begin
        (call_script, "script_add_log_entry", logent_game_start, "trp_player", -1, -1, -1),
#Post 0907 changes end

#Rebellion changes begin
        (troop_set_slot, "trp_kingdom_1_pretender",  slot_troop_original_faction, "fac_kingdom_1"),
        (troop_set_slot, "trp_kingdom_2_pretender",  slot_troop_original_faction, "fac_kingdom_2"),
        (troop_set_slot, "trp_kingdom_3_pretender",  slot_troop_original_faction, "fac_kingdom_3"),
        (troop_set_slot, "trp_kingdom_4_pretender",  slot_troop_original_faction, "fac_kingdom_4"),
        (troop_set_slot, "trp_kingdom_5_pretender",  slot_troop_original_faction, "fac_kingdom_5"),
        (troop_set_slot, "trp_kingdom_6_pretender",  slot_troop_original_faction, "fac_kingdom_6"),

#        (troop_set_slot, "trp_kingdom_1_pretender", slot_troop_support_base,     "p_town_4"), #suno
#        (troop_set_slot, "trp_kingdom_2_pretender", slot_troop_support_base,     "p_town_11"), #curaw
#        (troop_set_slot, "trp_kingdom_3_pretender", slot_troop_support_base,     "p_town_18"), #town_18
#        (troop_set_slot, "trp_kingdom_4_pretender", slot_troop_support_base,     "p_town_12"), #wercheg
#        (troop_set_slot, "trp_kingdom_5_pretender", slot_troop_support_base,     "p_town_3"), #veluca
        (try_for_range, ":pretender", pretenders_begin, pretenders_end),
            (troop_set_slot, ":pretender", slot_lord_reputation_type, lrep_none),
        (try_end),
#Rebellion changes end
     ]),



  ("objectionable_action",
    [
        (store_script_param_1, ":action_type"),
        (store_script_param_2, ":action_string"),

        (assign, ":grievance_minimum", -2),
        (try_for_range, ":npc", companions_begin, companions_end),
            (main_party_has_troop, ":npc"),

###Primary morality check
            (try_begin),
                (troop_slot_eq, ":npc", slot_troop_morality_type, ":action_type"),
                (troop_get_slot, ":value", ":npc", slot_troop_morality_value),
                (try_begin),
                    (troop_slot_eq, ":npc", slot_troop_morality_state, tms_acknowledged),
# npc is betrayed, major penalty to player honor and morale
                    (troop_get_slot, ":grievance", ":npc", slot_troop_morality_penalties),
                    (val_mul, ":value", 2),
                    (val_add, ":grievance", ":value"),
                    (troop_set_slot, ":npc", slot_troop_morality_penalties, ":grievance"),
                (else_try),
                    (this_or_next|troop_slot_eq, ":npc", slot_troop_morality_state, tms_dismissed),
                        (eq, "$disable_npc_complaints", 1),
# npc is quietly disappointed
                    (troop_get_slot, ":grievance", ":npc", slot_troop_morality_penalties),
                    (val_add, ":grievance", ":value"),
                    (troop_set_slot, ":npc", slot_troop_morality_penalties, ":grievance"),
                (else_try),
# npc raises the issue for the first time
                    (troop_slot_eq, ":npc", slot_troop_morality_state, tms_no_problem),
                    (gt, ":value", ":grievance_minimum"),
                    (assign, "$npc_with_grievance", ":npc"),
                    (assign, "$npc_grievance_string", ":action_string"),
                    (assign, "$npc_grievance_slot", slot_troop_morality_state),
                    (assign, ":grievance_minimum", ":value"),
                    (assign, "$npc_praise_not_complaint", 0),
                    (try_begin),
                        (lt, ":value", 0),
                        (assign, "$npc_praise_not_complaint", 1),
                    (try_end),
                (try_end),

###Secondary morality check
            (else_try),
                (troop_slot_eq, ":npc", slot_troop_2ary_morality_type, ":action_type"),
                (troop_get_slot, ":value", ":npc", slot_troop_2ary_morality_value),
                (try_begin),
                    (troop_slot_eq, ":npc", slot_troop_2ary_morality_state, tms_acknowledged),
# npc is betrayed, major penalty to player honor and morale
                    (troop_get_slot, ":grievance", ":npc", slot_troop_morality_penalties),
                    (val_mul, ":value", 2),
                    (val_add, ":grievance", ":value"),
                    (troop_set_slot, ":npc", slot_troop_morality_penalties, ":grievance"),
                (else_try),
                    (this_or_next|troop_slot_eq, ":npc", slot_troop_2ary_morality_state, tms_dismissed),
                        (eq, "$disable_npc_complaints", 1),
# npc is quietly disappointed
                    (troop_get_slot, ":grievance", ":npc", slot_troop_morality_penalties),
                    (val_add, ":grievance", ":value"),
                    (troop_set_slot, ":npc", slot_troop_morality_penalties, ":grievance"),
                (else_try),
# npc raises the issue for the first time
                    (troop_slot_eq, ":npc", slot_troop_2ary_morality_state, tms_no_problem),
                    (gt, ":value", ":grievance_minimum"),
                    (assign, "$npc_with_grievance", ":npc"),
                    (assign, "$npc_grievance_string", ":action_string"),
                    (assign, "$npc_grievance_slot", slot_troop_2ary_morality_state),
                    (assign, ":grievance_minimum", ":value"),
                    (assign, "$npc_praise_not_complaint", 0),
                    (try_begin),
                        (lt, ":value", 0),
                        (assign, "$npc_praise_not_complaint", 1),
                    (try_end),
                (try_end),
            (try_end),

            (try_begin),
                (gt, "$npc_with_grievance", 0),
                (eq, "$npc_praise_not_complaint", 0),
                (str_store_troop_name, 4, "$npc_with_grievance"),
                (display_message, "@{s4} looks upset."),
            (try_end),
        (try_end),        
     ]),


  ("post_battle_personality_clash_check",
[
            (try_for_range, ":npc", companions_begin, companions_end),
                (eq, "$disable_npc_complaints", 0),

                (main_party_has_troop, ":npc"),
                (neg|troop_is_wounded, ":npc"),

                (troop_get_slot, ":other_npc", ":npc", slot_troop_personalityclash2_object),
                (main_party_has_troop, ":other_npc"),
                (neg|troop_is_wounded, ":other_npc"),

#                (store_random_in_range, ":random", 0, 3),
                (try_begin),
                    (troop_slot_eq, ":npc", slot_troop_personalityclash2_state, 0),
                    (try_begin),
#                        (eq, ":random", 0),
                        (assign, "$npc_with_personality_clash_2", ":npc"),
                    (try_end),
                (try_end),

            (try_end),

            (try_for_range, ":npc", companions_begin, companions_end),
                (troop_slot_eq, ":npc", slot_troop_personalitymatch_state, 0),
                (eq, "$disable_npc_complaints", 0),

                (main_party_has_troop, ":npc"),
                (neg|troop_is_wounded, ":npc"),

                (troop_get_slot, ":other_npc", ":npc", slot_troop_personalitymatch_object),
                (main_party_has_troop, ":other_npc"),
                (neg|troop_is_wounded, ":other_npc"),
                (assign, "$npc_with_personality_match", ":npc"),
            (try_end),


            (try_begin),
                (gt, "$npc_with_personality_clash_2", 0),
				(try_begin),
					(eq, "$cheat_mode", 1),
					(display_message, "str_personality_clash_conversation_begins"),
				(try_end),
				
				(try_begin),
					(main_party_has_troop, "$npc_with_personality_clash_2"),
					(assign, "$npc_map_talk_context", slot_troop_personalityclash2_state),
					(start_map_conversation, "$npc_with_personality_clash_2"),
				(else_try),
					(assign, "$npc_with_personality_clash_2", 0),
				(try_end),
            (else_try),
                (gt, "$npc_with_personality_match", 0),
				(try_begin),
					(eq, "$cheat_mode", 1),
					(display_message, "str_personality_match_conversation_begins"),
				(try_end),
								
				(try_begin),
					(main_party_has_troop, "$npc_with_personality_match"),
					(assign, "$npc_map_talk_context", slot_troop_personalitymatch_state),
					(start_map_conversation, "$npc_with_personality_match"),
				(else_try),
					(assign, "$npc_with_personality_match", 0),
				(try_end), 
			(try_end),
     ]),

  #script_event_player_defeated_enemy_party
  # INPUT: none
  # OUTPUT: none
  ("event_player_defeated_enemy_party",
    [(try_begin),
       (check_quest_active, "qst_raid_caravan_to_start_war"),
       (neg|check_quest_concluded, "qst_raid_caravan_to_start_war"),
       (party_slot_eq, "$g_enemy_party", slot_party_type, spt_kingdom_caravan),
       (store_faction_of_party, ":enemy_faction", "$g_enemy_party"),
       (quest_slot_eq, "qst_raid_caravan_to_start_war", slot_quest_target_faction, ":enemy_faction"),
       (quest_get_slot, ":cur_state", "qst_raid_caravan_to_start_war", slot_quest_current_state),
       (quest_get_slot, ":quest_target_amount", "qst_raid_caravan_to_start_war", slot_quest_target_amount),
       (val_add, ":cur_state", 1),
       (quest_set_slot, "qst_raid_caravan_to_start_war", slot_quest_current_state, ":cur_state"),
       (try_begin),
         (ge, ":cur_state", ":quest_target_amount"),
         (quest_get_slot, ":quest_target_faction", "qst_raid_caravan_to_start_war", slot_quest_target_faction),
         (quest_get_slot, ":quest_giver_troop", "qst_raid_caravan_to_start_war", slot_quest_giver_troop),
         (store_troop_faction, ":quest_giver_faction", ":quest_giver_troop"),
         (call_script, "script_diplomacy_start_war_between_kingdoms", ":quest_target_faction", ":quest_giver_faction", 1),
         (call_script, "script_succeed_quest", "qst_raid_caravan_to_start_war"),
       (try_end),
     (try_end),

     ]),

  #script_event_player_captured_as_prisoner
  # INPUT: none
  # OUTPUT: none
  ("event_player_captured_as_prisoner",
    [
        (try_begin),
          (check_quest_active, "qst_raid_caravan_to_start_war"),
          (neg|check_quest_concluded, "qst_raid_caravan_to_start_war"),
          (quest_get_slot, ":quest_target_faction", "qst_raid_caravan_to_start_war", slot_quest_target_faction),
          (store_faction_of_party, ":capturer_faction", "$capturer_party"),
          (eq, ":quest_target_faction", ":capturer_faction"),
          (call_script, "script_fail_quest", "qst_raid_caravan_to_start_war"),
        (try_end),
        #Removing followers of the player
        (try_for_range, ":troop_no", active_npcs_begin, active_npcs_end),
		  (troop_slot_eq, ":troop_no", slot_troop_occupation, slto_kingdom_hero),
          (troop_get_slot, ":party_no", ":troop_no", slot_troop_leaded_party),
          (gt, ":party_no", 0),
          (party_is_active, ":party_no"),
          (party_slot_eq, ":party_no", slot_party_ai_state, spai_accompanying_army),
          (party_slot_eq, ":party_no", slot_party_ai_object, "p_main_party"),
          (call_script, "script_party_set_ai_state", ":party_no", spai_undefined, -1),
#          (party_set_slot, ":party_no", slot_party_commander_party, -1),
          (assign, "$g_recalculate_ais", 1),
        (try_end),
     ]),

#NPC morale both returns a string and reg0 as the morale value
  ("npc_morale",
[
        (store_script_param_1, ":npc"),

        (troop_get_slot, ":morality_grievances", ":npc", slot_troop_morality_penalties),
        (troop_get_slot, ":personality_grievances", ":npc", slot_troop_personalityclash_penalties),
        (party_get_morale, ":party_morale", "p_main_party"),

        (store_sub, ":troop_morale", ":party_morale", ":morality_grievances"),
        (val_sub, ":troop_morale", ":personality_grievances"),
        (val_add, ":troop_morale", 50),

        (assign, reg8, ":troop_morale"),
        
        (val_mul, ":troop_morale", 3),
        (val_div, ":troop_morale", 4),
        (val_clamp, ":troop_morale", 0, 100),

        (assign, reg5, ":party_morale"),
        (assign, reg6, ":morality_grievances"),
        (assign, reg7, ":personality_grievances"),
        (assign, reg9, ":troop_morale"),

#        (str_store_troop_name, s11, ":npc"),
#        (display_message, "@{!}{s11}'s morale = PM{reg5} + 50 - MG{reg6} - PG{reg7} = {reg8} x 0.75 = {reg9}"),

        (try_begin),
            (lt, ":morality_grievances", 3),
            (str_store_string, 7, "str_happy"),
        (else_try),
            (lt, ":morality_grievances", 15),
            (str_store_string, 7, "str_content"),
        (else_try),
            (lt, ":morality_grievances", 30),
            (str_store_string, 7, "str_concerned"),
        (else_try),
            (lt, ":morality_grievances", 45),
            (str_store_string, 7, "str_not_happy"),
        (else_try),
            (str_store_string, 7, "str_miserable"),
        (try_end),


        (try_begin),
            (lt, ":personality_grievances", 3),
            (str_store_string, 6, "str_happy"),
        (else_try),
            (lt, ":personality_grievances", 15),
            (str_store_string, 6, "str_content"),
        (else_try),
            (lt, ":personality_grievances", 30),
            (str_store_string, 6, "str_concerned"),
        (else_try),
            (lt, ":personality_grievances", 45),
            (str_store_string, 6, "str_not_happy"),
        (else_try),
            (str_store_string, 6, "str_miserable"),
        (try_end),


        (try_begin),
            (gt, ":troop_morale", 80),
            (str_store_string, 8, "str_happy"),
            (str_store_string, 63, "str_bar_enthusiastic"),
        (else_try),
            (gt, ":troop_morale", 60),
            (str_store_string, 8, "str_content"),
            (str_store_string, 63, "str_bar_content"),
        (else_try),
            (gt, ":troop_morale", 40),
            (str_store_string, 8, "str_concerned"),
            (str_store_string, 63, "str_bar_weary"),
        (else_try),
            (gt, ":troop_morale", 20),
            (str_store_string, 8, "str_not_happy"),
            (str_store_string, 63, "str_bar_disgruntled"),
        (else_try),
            (str_store_string, 8, "str_miserable"),
            (str_store_string, 63, "str_bar_miserable"),
        (try_end),


        (str_store_string, 21, "str_npc_morale_report"),
        (assign, reg0, ":troop_morale"),

     ]),
#NPC morale both returns a string and reg0 as the morale value


#
  ("retire_companion",
[
    (store_script_param_1, ":npc"),
    (store_script_param_2, ":length"),

    (remove_member_from_party, ":npc", "p_main_party"),
    (troop_set_slot, ":npc", slot_troop_personalityclash_penalties, 0),
    (troop_set_slot, ":npc", slot_troop_morality_penalties, 0),
    (troop_get_slot, ":renown", "trp_player", slot_troop_renown),
    (store_add, ":return_renown", ":renown", ":length"),
    (troop_set_slot, ":npc", slot_troop_occupation, slto_retirement),
    (troop_set_slot, ":npc", slot_troop_return_renown, ":return_renown"),
    ]),

#NPC companion changes end

  #script_reduce_companion_morale_for_clash
  #script_calculate_ransom_amount_for_troop
  # INPUT: arg1 = troop_no for companion1 arg2 = troop_no for companion2 arg3 = slot_for_clash_state
  # slot_for_clash_state means: 1=give full penalty to companion1; 2=give full penalty to companion2; 3=give penalty equally
  ("reduce_companion_morale_for_clash",
   [
    (store_script_param, ":companion_1", 1),
    (store_script_param, ":companion_2", 2),
    (store_script_param, ":slot_for_clash_state", 3),

    (troop_get_slot, ":clash_state", ":companion_1", ":slot_for_clash_state"),
    (troop_get_slot, ":grievance_1", ":companion_1", slot_troop_personalityclash_penalties),
    (troop_get_slot, ":grievance_2", ":companion_2", slot_troop_personalityclash_penalties),
    (try_begin),
      (eq, ":clash_state", pclash_penalty_to_self),
      (val_add, ":grievance_1", 5),
    (else_try),
      (eq, ":clash_state", pclash_penalty_to_other),
      (val_add, ":grievance_2", 5),
    (else_try),
      (eq, ":clash_state", pclash_penalty_to_both),
      (val_add, ":grievance_1", 3),
      (val_add, ":grievance_2", 3),
    (try_end),
    (troop_set_slot, ":companion_1", slot_troop_personalityclash_penalties, ":grievance_1"),
    (troop_set_slot, ":companion_2", slot_troop_personalityclash_penalties, ":grievance_2"),
    ]),

#Hunting scripts end

  #script_calculate_ransom_amount_for_troop
  # INPUT: arg1 = troop_no
  # OUTPUT: reg0 = ransom_amount
  ("calculate_ransom_amount_for_troop",
    [(store_script_param, ":troop_no", 1),
     (store_troop_faction, ":faction_no", ":troop_no"),
     (assign, ":ransom_amount", 400),

	 (assign, ":male_relative", -9), #for kingdom ladies, otherwise a number otherwise unused in slot_town_lord
     (try_begin),
       (faction_slot_eq, ":faction_no", slot_faction_leader, ":troop_no"),
       (val_add, ":ransom_amount", 4000),
	 (else_try),  
       (troop_slot_eq, ":troop_no", slot_troop_occupation, slto_kingdom_lady),
       (val_add, ":ransom_amount", 2500), #as though a renown of 1250 -- therefore significantly higher than for roughly equivalent lords
	   (call_script, "script_get_kingdom_lady_social_determinants", ":troop_no"),
	   (assign, ":male_relative", reg0),
     (try_end),

     (assign, ":num_center_points", 0),
     (try_for_range, ":cur_center", centers_begin, centers_end),
       (this_or_next|party_slot_eq, ":cur_center", slot_town_lord, ":troop_no"),
		 (party_slot_eq, ":cur_center", slot_town_lord, ":male_relative"),
       (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),
     (val_mul, ":num_center_points", 500),
     (val_add, ":ransom_amount", ":num_center_points"),
     (troop_get_slot, ":renown", ":troop_no", slot_troop_renown),
     (val_mul, ":renown", 2),
     (val_add, ":ransom_amount", ":renown"),
     (store_mul, ":ransom_max_amount", ":ransom_amount", 3),
     (val_div, ":ransom_max_amount", 2),
     (store_random_in_range, ":random_ransom_amount", ":ransom_amount", ":ransom_max_amount"),
     (val_div, ":random_ransom_amount", 100),
     (val_mul, ":random_ransom_amount", 100),
     (assign, reg0, ":random_ransom_amount"),
     ]),  

  #script_offer_ransom_amount_to_player_for_prisoners_in_party
  # INPUT: arg1 = party_no
  # OUTPUT: reg0 = result (1 = offered, 0 = not offered)
  ("offer_ransom_amount_to_player_for_prisoners_in_party",
    [(store_script_param, ":party_no", 1),
     (assign, ":result", 0),
     (party_get_num_prisoner_stacks, ":num_stacks", ":party_no"),
     (try_for_range, ":i_stack", 0, ":num_stacks"),
       (eq, ":result", 0),
       (party_prisoner_stack_get_troop_id, ":stack_troop", ":party_no", ":i_stack"),
       (troop_is_hero, ":stack_troop"),
       (this_or_next|troop_slot_eq, ":stack_troop", slot_troop_occupation, slto_kingdom_hero),
		 (troop_slot_eq, ":stack_troop", slot_troop_occupation, slto_kingdom_lady),
       (store_troop_faction, ":stack_troop_faction", ":stack_troop"),
       (store_random_in_range, ":random_no", 0, 100),
       (try_begin),
         (faction_slot_eq, ":stack_troop_faction", slot_faction_state, sfs_active),
         (le, ":random_no", 5),
         (neq, "$g_ransom_offer_rejected", 1),
         (assign, ":num_stacks", 0), #break
         (assign, ":result", 1),
         (assign, "$g_ransom_offer_troop", ":stack_troop"),
         (assign, "$g_ransom_offer_party", ":party_no"),
         (jump_to_menu, "mnu_enemy_offer_ransom_for_prisoner"),
       (try_end),
     (try_end),
     (assign, reg0, ":result"),
     ]),

  # script_event_hero_taken_prisoner_by_player
  # Input: arg1 = troop_no
  # Output: none
  ("event_hero_taken_prisoner_by_player",
    [
      (store_script_param_1, ":troop_no"),
      (try_begin),
        (check_quest_active, "qst_persuade_lords_to_make_peace"),
        (try_begin),
          (quest_slot_eq, "qst_persuade_lords_to_make_peace", slot_quest_target_troop, ":troop_no"),
          (val_mul, ":troop_no", -1),
          (quest_set_slot, "qst_persuade_lords_to_make_peace", slot_quest_target_troop, ":troop_no"),
          (val_mul, ":troop_no", -1),
        (else_try),
          (quest_slot_eq, "qst_persuade_lords_to_make_peace", slot_quest_object_troop, ":troop_no"),
          (val_mul, ":troop_no", -1),
          (quest_set_slot, "qst_persuade_lords_to_make_peace", slot_quest_object_troop, ":troop_no"),
          (val_mul, ":troop_no", -1),
        (try_end),
        (neg|check_quest_concluded, "qst_persuade_lords_to_make_peace"),
        (neg|quest_slot_ge, "qst_persuade_lords_to_make_peace", slot_quest_target_troop, 0),
        (neg|quest_slot_ge, "qst_persuade_lords_to_make_peace", slot_quest_object_troop, 0),
        (call_script, "script_succeed_quest", "qst_persuade_lords_to_make_peace"),
      (try_end),
      (call_script, "script_update_troop_location_notes", ":troop_no", 0),
  ]),

  # script_cf_check_hero_can_escape_from_player
  # Input: arg1 = troop_no
  # Output: none (can fail)
  ("cf_check_hero_can_escape_from_player",
    [
      (store_script_param_1, ":troop_no"),
      (assign, ":quest_target", 0),
      (try_begin),
        (check_quest_active, "qst_persuade_lords_to_make_peace"),
        (this_or_next|quest_slot_eq, "qst_persuade_lords_to_make_peace", slot_quest_target_troop, ":troop_no"),
        (quest_slot_eq, "qst_persuade_lords_to_make_peace", slot_quest_object_troop, ":troop_no"),
        (assign, ":quest_target", 1),
      (else_try),
        (ge, ":troop_no", "trp_sea_raider_leader"),
        (lt, ":troop_no", "trp_bandit_leaders_end"),
        (try_begin),
          (check_quest_active, "qst_learn_where_merchant_brother_is"),
          (assign, ":quest_target", 1), #always catched
        (else_try),  
          (assign, ":quest_target", -1), #always run.
        (try_end),
      (try_end),
      
      (assign, ":continue", 0),
      (try_begin),
        (eq, ":quest_target", 0), #if not quest target
        (assign, ":escape_chance", hero_escape_after_defeat_chance),
        (store_skill_level, ":skill", "skl_pathfinding", ":troop_no"),
        (val_add, ":escape_chance", ":skill"),
        (party_get_skill_level, ":skill", "p_main_party", "skl_tracking"),
        (val_sub, ":escape_chance", ":skill"),
        (val_sub, ":escape_chance", ":skill"),
        (party_get_skill_level, ":skill", "p_main_party", "skl_spotting"),
        (val_sub, ":escape_chance", ":skill"),
        (store_random_in_range, ":rand", 0, 100),
        (lt, ":rand", ":escape_chance"),
        (assign, ":continue", 1),
      (else_try),  
        (eq, ":quest_target", -1), #if (always run) quest target
        (assign, ":continue", 1),
      (try_end),  
      
      (eq, ":continue", 1),
  ]),

  # script_cf_party_remove_random_regular_troop
  # Input: arg1 = party_no
  # Output: troop_id that has been removed (can fail)
  ("cf_party_remove_random_regular_troop",
    [(store_script_param_1, ":party_no"),
     (party_get_num_companion_stacks, ":num_stacks", ":party_no"),
     (assign, ":num_troops", 0),
     (try_for_range, ":i_stack", 0, ":num_stacks"),
       (party_stack_get_troop_id, ":stack_troop", ":party_no", ":i_stack"),
       (neg|troop_is_hero, ":stack_troop"),
       (party_stack_get_size, ":stack_size", ":party_no", ":i_stack"),
       (val_add, ":num_troops", ":stack_size"),
     (try_end),
     (assign, reg0, -1),
     (gt, ":num_troops", 0),
     (store_random_in_range, ":random_troop", 0, ":num_troops"),
     (try_for_range, ":i_stack", 0, ":num_stacks"),
       (party_stack_get_troop_id, ":stack_troop", ":party_no", ":i_stack"),
       (neg|troop_is_hero, ":stack_troop"),
       (party_stack_get_size, ":stack_size", ":party_no", ":i_stack"),
       (val_sub, ":random_troop", ":stack_size"),
       (lt, ":random_troop", 0),
       (assign, ":num_stacks", 0), #break
       (party_remove_members, ":party_no", ":stack_troop", 1),
       (assign, reg0, ":stack_troop"),
     (try_end),
     ]),

  # script_place_player_banner_near_inventory
  # Input: none
  # Output: none
  ("place_player_banner_near_inventory",
    [
    	#normal_banner_begin
    	(troop_get_slot, ":troop_banner_object", "trp_player", slot_troop_banner_scene_prop),
    	#custom_banner_begin
#    	(troop_get_slot, ":flag_spr", "trp_player", slot_troop_custom_banner_flag_type),

     (try_begin),
    	#normal_banner_begin
       (gt, ":troop_banner_object", 0),
       (scene_prop_get_instance, ":flag_object", ":troop_banner_object", 0),
    	#custom_banner_begin
#       (ge, ":flag_spr", 0),
#       (val_add, ":flag_spr", custom_banner_flag_scene_props_begin),
#       (scene_prop_get_instance, ":flag_object", ":flag_spr", 0),
       (try_begin),
         (ge, ":flag_object", 0),
         (get_player_agent_no, ":player_agent"),
         (agent_get_look_position, pos1, ":player_agent"),
         (position_move_y, pos1, -500),
         (position_rotate_z, pos1, 180),
         (position_set_z_to_ground_level, pos1),
         (position_move_z, pos1, 300),
         (prop_instance_set_position, ":flag_object", pos1),
       (try_end),
       (scene_prop_get_instance, ":pole_object", "spr_banner_pole", 0),
       (try_begin),
         (ge, ":pole_object", 0),
         (position_move_z, pos1, -320),
         (prop_instance_set_position, ":pole_object", pos1),
       (try_end),
     (else_try),
       (init_position, pos1),
       (position_move_z, pos1, -1000000),
       (scene_prop_get_instance, ":flag_object", banner_scene_props_begin, 0),
       (try_begin),
         (ge, ":flag_object", 0),
         (prop_instance_set_position, ":flag_object", pos1),
       (try_end),
       (scene_prop_get_instance, ":pole_object", "spr_banner_pole", 0),
       (try_begin),
         (ge, ":pole_object", 0),
         (prop_instance_set_position, ":pole_object", pos1),
       (try_end),
     (try_end),
     ]),

  # script_place_player_banner_near_inventory_bms
  # Input: none
  # Output: none
  ("place_player_banner_near_inventory_bms",
    [
    	    	#normal_banner_begin
    	(troop_get_slot, ":troop_banner_object", "trp_player", slot_troop_banner_scene_prop),
    	    	#custom_banner_begin
#      (troop_get_slot, ":flag_spr", "trp_player", slot_troop_custom_banner_flag_type),
     (try_begin),
    	    	#normal_banner_begin
       (gt, ":troop_banner_object", 0),
       (replace_scene_props, banner_scene_props_begin, ":troop_banner_object"),
    	    	#custom_banner_begin
#       (ge, ":flag_spr", 0),
#       (val_add, ":flag_spr", custom_banner_flag_scene_props_begin),
#       (replace_scene_props, banner_scene_props_begin, ":flag_spr"),
     (try_end),
     ]),
  
  # script_stay_captive_for_hours
  # Input: arg1 = num_hours
  # Output: none
  ("stay_captive_for_hours",
    [
      (store_script_param, ":num_hours", 1),
      (store_current_hours, ":cur_hours"),
      (val_add, ":cur_hours", ":num_hours"),
      (val_max, "$g_check_autos_at_hour", ":cur_hours"),
      (val_add, ":num_hours", 1),
      (rest_for_hours, ":num_hours", 0, 0),
    ]),

  # script_set_parties_around_player_ignore_player
  # Input: arg1 = ignore_range, arg2 = num_hours_to_ignore
  # Output: none
  ("set_parties_around_player_ignore_player",
    [(store_script_param, ":ignore_range", 1),
     (store_script_param, ":num_hours", 2),
     (try_for_parties, ":party_no"),
       (party_is_active, ":party_no"),
       (store_distance_to_party_from_party, ":dist", "p_main_party", ":party_no"),
       (lt, ":dist", ":ignore_range"),
       (party_ignore_player, ":party_no", ":num_hours"),
     (try_end),
     ]),

  # script_randomly_make_prisoner_heroes_escape_from_party
  # Input: arg1 = party_no, arg2 = escape_chance_mul_1000
  # Output: none
  ("randomly_make_prisoner_heroes_escape_from_party",
    [(store_script_param, ":party_no", 1),
     (store_script_param, ":escape_chance", 2),
     (assign, ":quest_troop_1", -1),
     (assign, ":quest_troop_2", -1),
     (try_begin),
       (check_quest_active, "qst_rescue_lord_by_replace"),
       (quest_get_slot, ":quest_troop_1", "qst_rescue_lord_by_replace", slot_quest_target_troop),
     (try_end),
     (try_begin),
       (check_quest_active, "qst_deliver_message_to_prisoner_lord"),
       (quest_get_slot, ":quest_troop_2", "qst_deliver_message_to_prisoner_lord", slot_quest_target_troop),
     (try_end),
     (party_get_num_prisoner_stacks, ":num_stacks", ":party_no"),
     (try_for_range_backwards, ":i_stack", 0, ":num_stacks"),
       (party_prisoner_stack_get_troop_id, ":stack_troop", ":party_no", ":i_stack"),
       (troop_is_hero, ":stack_troop"),
       (neq, ":stack_troop", ":quest_troop_1"),
       (neq, ":stack_troop", ":quest_troop_2"),
       (troop_slot_eq, ":stack_troop", slot_troop_occupation, slto_kingdom_hero),
       (store_random_in_range, ":random_no", 0, 1000),
       (lt, ":random_no", ":escape_chance"),
       (party_remove_prisoners, ":party_no", ":stack_troop", 1),
       (call_script, "script_remove_troop_from_prison", ":stack_troop"),
       (str_store_troop_name_link, s1, ":stack_troop"),
       (try_begin),
         (eq, ":party_no", "p_main_party"),
         (str_store_string, s2, "@your party"),
       (else_try),
         (str_store_party_name, s2, ":party_no"),
       (try_end),
       (assign, reg0, 0),
       (try_begin),
         (this_or_next|eq, ":party_no", "p_main_party"),
         (party_slot_eq, ":party_no", slot_town_lord, "trp_player"),
         (assign, reg0, 1),
       (try_end),
       (store_troop_faction, ":troop_faction", ":stack_troop"),
       (str_store_faction_name_link, s3, ":troop_faction"),
       (display_message, "@{reg0?One of your prisoners, :}{s1} of {s3} has escaped from captivity!"),
     (try_end),
     ]),


  # script_fill_tournament_participants_troop
  # Input: arg1 = center_no, arg2 = player_at_center
  # Output: none (fills trp_tournament_participants)
  ("fill_tournament_participants_troop",
    [(store_script_param, ":center_no", 1),
     (store_script_param, ":player_at_center", 2),
     (assign, ":cur_slot", 0),

     (try_begin),
       (eq, ":player_at_center", 1),
       (party_get_num_companion_stacks, ":num_stacks", "p_main_party"),
       (try_for_range, ":stack_no", 0, ":num_stacks"),
         (party_stack_get_troop_id, ":cur_troop", "p_main_party", ":stack_no"),
         (troop_is_hero, ":cur_troop"),
         (neq, ":cur_troop", "trp_kidnapped_girl"),
		 # NE quests
		 # v585 Josef kidnapped wife
		(neq, ":cur_troop", "trp_kidnapped_wife"),
#end v585 Josef
# NE end quests
         (troop_set_slot, "trp_tournament_participants", ":cur_slot", ":cur_troop"),
         (val_add, ":cur_slot", 1),
       (try_end),
     (try_end),

     (party_collect_attachments_to_party, ":center_no", "p_temp_party"),
     (party_get_num_companion_stacks, ":num_stacks", "p_temp_party"),
     (try_for_range, ":stack_no", 0, ":num_stacks"),
       (party_stack_get_troop_id, ":cur_troop", "p_temp_party", ":stack_no"),
       (troop_is_hero, ":cur_troop"),
       (troop_set_slot, "trp_tournament_participants", ":cur_slot", ":cur_troop"),
       (val_add, ":cur_slot", 1),
     (try_end),

     (try_begin),
       (store_random_in_range, ":random_no", 0, 100),
       (lt, ":random_no", 50),
       (troop_set_slot, "trp_tournament_participants", ":cur_slot", "trp_xerina"),
       (val_add, ":cur_slot", 1),
     (try_end),
     (try_begin),
       (store_random_in_range, ":random_no", 0, 100),
       (lt, ":random_no", 50),
       (troop_set_slot, "trp_tournament_participants", ":cur_slot", "trp_dranton"),
       (val_add, ":cur_slot", 1),
     (try_end),
     (try_begin),
       (store_random_in_range, ":random_no", 0, 100),
       (lt, ":random_no", 50),
       (troop_set_slot, "trp_tournament_participants", ":cur_slot", "trp_kradus"),
       (val_add, ":cur_slot", 1),
     (try_end),

     (assign, ":begin_slot", ":cur_slot"),
     (try_for_range, ":cur_slot", ":begin_slot", 64),
       (store_random_in_range, ":random_no", 0, 6),
       (try_begin),
         (eq, ":random_no", 0),
         (troop_set_slot, "trp_tournament_participants", ":cur_slot", "trp_regular_fighter"),
       (else_try),
         (eq, ":random_no", 1),
         (troop_set_slot, "trp_tournament_participants", ":cur_slot", "trp_veteran_fighter"),
       (else_try),
         (eq, ":random_no", 2),
         (troop_set_slot, "trp_tournament_participants", ":cur_slot", "trp_champion_fighter"),
       (else_try),
         (eq, ":random_no", 3),
         (troop_set_slot, "trp_tournament_participants", ":cur_slot", "trp_female_shield_sister"),
       (else_try),
         (eq, ":random_no", 4),
         (troop_set_slot, "trp_tournament_participants", ":cur_slot", "trp_hired_blade"),
       (else_try),
         (troop_set_slot, "trp_tournament_participants", ":cur_slot", "trp_mercenary_swordsman"),
       (try_end),
     (try_end),
     ]),
  
  # script_get_num_tournament_participants
  # Input: none
  # Output: reg0 = num_participants
  ("get_num_tournament_participants",
    [(assign, ":num_participants", 0),
     (try_for_range, ":cur_slot", 0, 64),
       (troop_slot_ge, "trp_tournament_participants", ":cur_slot", 0),
       (val_add, ":num_participants", 1),
     (try_end),
     (assign, reg0, ":num_participants"),
     ]),

  # script_get_random_tournament_participant
  # Input: none
  # Output: reg0 = troop_no
  ("get_random_tournament_participant",
    [(call_script, "script_get_num_tournament_participants"),
     (assign, ":num_participants", reg0),
     (store_random_in_range, ":random_troop", 0, ":num_participants"),
     (assign, ":continue", 1),
     (try_for_range, ":cur_slot", 0, 64),
       (eq, ":continue", 1),
       (troop_slot_ge, "trp_tournament_participants", ":cur_slot", 0),
       (val_sub, ":random_troop", 1),
       (lt, ":random_troop", 0),
       (assign, ":continue", 0),
       (troop_get_slot, ":troop_no", "trp_tournament_participants", ":cur_slot"),
       (troop_set_slot, "trp_tournament_participants", ":cur_slot", -1),
     (try_end),
     (assign, reg0, ":troop_no"),
     ]),

  # script_add_tournament_participant
  # Input: arg1 = troop_no
  # Output: none
  ("add_tournament_participant",
    [(store_script_param, ":troop_no", 1),
     (assign, ":continue", 1),
     (try_for_range, ":cur_slot", 0, 64),
       (eq, ":continue", 1),
       (troop_slot_eq, "trp_tournament_participants", ":cur_slot", -1),
       (troop_set_slot, "trp_tournament_participants", ":cur_slot", ":troop_no"),
       (assign, ":continue", 0),
     (try_end),
     ]),

  # script_get_random_tournament_team_amount_and_size
  # Input: none
  # Output: reg0 = number_of_teams, reg1 = team_size
  ("get_random_tournament_team_amount_and_size",
    [
        (call_script, "script_get_num_tournament_participants"),
        (assign, ":num_participants", reg0),
        (party_get_slot, ":town_max_teams", "$current_town", slot_town_tournament_max_teams),
        (val_add, ":town_max_teams", 1),
        (party_get_slot, ":town_max_team_size", "$current_town", slot_town_tournament_max_team_size),
        (val_add, ":town_max_team_size", 1),
        (assign, ":max_teams", ":num_participants"),
        (val_min, ":max_teams", ":town_max_teams"),
        (assign, ":max_size", ":num_participants"),
        (val_min, ":max_size", ":town_max_team_size"),
        (assign, ":min_size", 1),
        (try_begin),
          (ge, ":num_participants", 32),
          (assign, ":min_size", 2),
          (val_min, ":min_size", ":town_max_team_size"),
        (try_end),
        (assign, ":end_cond", 500),
        (try_for_range, ":unused", 0, ":end_cond"),
          (store_random_in_range, ":random_teams", 2, ":max_teams"),
          (store_random_in_range, ":random_size", ":min_size", ":max_size"),
          (store_mul, ":total_men", ":random_teams", ":random_size"),
          (le, ":total_men", ":num_participants"),
          (store_sub, ":left_men", ":num_participants", ":total_men"),
          (neq, ":left_men", 1),
          (assign, ":end_cond", 0),
        (try_end),
        (try_begin),
          (gt, ":end_cond", 0),
          (assign, ":random_teams", 2),
          (assign, ":random_size", 1),
        (try_end),
        (assign, reg0, ":random_teams"),
        (assign, reg1, ":random_size"),
     ]),

  # script_get_troop_priority_point_for_tournament
  # Input: arg1 = troop_no
  # Output: reg0 = troop_point
  ("get_troop_priority_point_for_tournament",
    [(store_script_param, ":troop_no", 1),
     (assign, ":troop_point", 0),
     (try_begin),
       (ge, ":troop_no", 0),
       (val_add, ":troop_point", 40000),
       (try_begin),
         (eq, ":troop_no", "trp_player"),
         (val_add, ":troop_point", 80000),
       (try_end),
       (try_begin),
         (troop_is_hero, ":troop_no"),
         (val_add, ":troop_point", 20000),
       (try_end),
       (try_begin),
         (troop_slot_eq, ":troop_no", slot_troop_occupation, slto_player_companion),
         (val_add, ":troop_point", 10000),
       (else_try),
         (troop_slot_eq, ":troop_no", slot_troop_occupation, slto_kingdom_hero),
         (troop_get_slot, ":renown", ":troop_no", slot_troop_renown),
         (val_add, ":troop_point", ":renown"),
         (val_add, ":troop_point", 1000), #in order to make it more prior than tournament heroes with higher levels
       (else_try),
         (store_character_level, ":level", ":troop_no"),
         (val_add, ":troop_point", ":level"),
       (try_end),
     (try_end),
     (assign, reg0, ":troop_point"),
     ]),

  # script_sort_tournament_participant_troops
  # Input: none
  # Output: none (sorts trp_tournament_participants)
  ("sort_tournament_participant_troops",
    [(try_for_range, ":cur_slot", 0, 63),
       (store_add, ":cur_slot_2_begin", ":cur_slot", 1),
       (try_for_range, ":cur_slot_2", ":cur_slot_2_begin", 64),
         (troop_get_slot, ":troop_1", "trp_tournament_participants", ":cur_slot"),
         (troop_get_slot, ":troop_2", "trp_tournament_participants", ":cur_slot_2"),
         (call_script, "script_get_troop_priority_point_for_tournament", ":troop_1"),
         (assign, ":troop_1_point", reg0),
         (call_script, "script_get_troop_priority_point_for_tournament", ":troop_2"),
         (assign, ":troop_2_point", reg0),
         (gt, ":troop_2_point", ":troop_1_point"),
         (troop_set_slot, "trp_tournament_participants", ":cur_slot", ":troop_2"),
         (troop_set_slot, "trp_tournament_participants", ":cur_slot_2", ":troop_1"),
       (try_end),
     (try_end),
     ]),

  # script_remove_tournament_participants_randomly
  # Input: arg1 = number_to_be_removed
  # Output: none
  ("remove_tournament_participants_randomly",
    [(store_script_param, ":number_to_be_removed", 1),
     (try_for_range, ":unused", 0, ":number_to_be_removed"),
       (assign, ":total_weight", 0),
       (try_for_range, ":cur_slot", 0, 64),
         (troop_get_slot, ":troop_no", "trp_tournament_participants", ":cur_slot"),
         (ge, ":troop_no", 0),
         (store_character_level, ":level", ":troop_no"),
         (val_min, ":level", 38),
         (store_sub, ":weight", 40, ":level"),
         (val_add, ":total_weight", ":weight"),
       (try_end),
       (store_random_in_range, ":random_weight", 0, ":total_weight"),
       (assign, ":continue", 1),
       (try_for_range, ":cur_slot", 0, 64),
         (eq, ":continue", 1),
         (troop_get_slot, ":troop_no", "trp_tournament_participants", ":cur_slot"),
         (ge, ":troop_no", 0),
         (store_character_level, ":level", ":troop_no"),
         (val_min, ":level", 38),
         (store_sub, ":weight", 40, ":level"),
         (val_sub, ":random_weight", ":weight"),
         (lt, ":random_weight", 0),
         (troop_set_slot, "trp_tournament_participants", ":cur_slot", -1),
         (assign, ":continue", 0),
       (try_end),
     (try_end),
     ]),
  
  # script_end_tournament_fight
  # Input: arg1 = player_team_won (1 or 0)
  # Output: none
  ("end_tournament_fight",
    [(store_script_param, ":player_team_won", 1),
     (call_script, "script_get_num_tournament_participants"),
     (assign, ":num_participants", reg0),
     (store_div, ":needed_to_remove_randomly", ":num_participants", 2),
     #Must remove other participants randomly earlier than adding the winners back to participants
     (call_script, "script_remove_tournament_participants_randomly", ":needed_to_remove_randomly"),

     (assign, ":num_needed", "$g_tournament_num_participants_for_fight"),
     (val_div, ":num_needed", 2),
     (get_player_agent_no, ":player_agent"),
     (agent_get_team, ":player_team", ":player_agent"),
     (try_for_agents, ":agent_no"),
       (agent_is_human, ":agent_no"),
       (agent_get_troop_id, ":troop_id", ":agent_no"),
       (neg|is_between, ":troop_id", arena_masters_begin, arena_masters_end),#omit tournament master
       (agent_get_team, ":agent_team", ":agent_no"),
       (assign, ":cur_point", 0),
       (try_begin),
         (eq, ":player_team_won", 1),
         (eq, ":agent_team", ":player_team"),
         (val_add, ":cur_point", 5000000),#Make sure that team members are chosen
       (try_end),
       (agent_get_kill_count, ":kill_count", ":agent_no", 1), #everyone is knocked unconscious
       (store_mul, ":kill_point", ":kill_count", 160000),#Make sure that kill count is the second most important variable
       (val_add, ":cur_point", ":kill_point"),
       (call_script, "script_get_troop_priority_point_for_tournament", ":troop_id"),
       (val_add, ":cur_point", reg0),
       (try_begin),#reset player's point if kill count is one after the first 2 rounds, or if it is zero
         (eq, ":agent_no", ":player_agent"),
         (eq, ":player_team_won", 0),
         (assign, ":not_passed", 1),
         (try_begin),
           (ge, ":kill_count", 2),
           (assign, ":not_passed", 0),
         (else_try),
           (eq, ":kill_count", 1),
           (le, "$g_tournament_cur_tier", 1),
           (assign, ":not_passed", 0),
         (try_end),
         (eq, ":not_passed", 1),
         (assign, ":cur_point", 0),
       (try_end),
       (agent_set_slot, ":agent_no", slot_agent_tournament_point, ":cur_point"),
     (try_end),
     (try_for_range, ":unused", 0, ":num_needed"),
       (assign, ":best_point", 0),
       (assign, ":best_agent_no", -1),
       (try_for_agents, ":agent_no"),
         (agent_is_human, ":agent_no"),
         (agent_get_slot, ":point", ":agent_no", slot_agent_tournament_point),
         (gt, ":point", ":best_point"),
         (assign, ":best_agent_no", ":agent_no"),
         (assign, ":best_point", ":point"),
       (try_end),
       (agent_set_slot, ":best_agent_no", slot_agent_tournament_point, 0),#Do not select the same agent again
       (agent_get_troop_id, ":troop_id", ":best_agent_no"),
       (call_script, "script_add_tournament_participant", ":troop_id"),
     (try_end),
     (assign, "$g_tournament_player_team_won", ":player_team_won"),
     (jump_to_menu, "mnu_town_tournament"),
     ]),


  # script_get_win_amount_for_tournament_bet
  # Input: none
  # Output: reg0 = win_amount_with_100_denars
  ("get_win_amount_for_tournament_bet",
    [
        (party_get_slot, ":player_odds", "$current_town", slot_town_player_odds),
        (try_begin),
          (eq, "$g_tournament_cur_tier", 0),
          (assign, ":win_amount", 120),
        (else_try),
          (eq, "$g_tournament_cur_tier", 1),
          (assign, ":win_amount", 90),
        (else_try),
          (eq, "$g_tournament_cur_tier", 2),
          (assign, ":win_amount", 60),
        (else_try),
          (eq, "$g_tournament_cur_tier", 3),
          (assign, ":win_amount", 40),
        (else_try),
          (eq, "$g_tournament_cur_tier", 4),
          (assign, ":win_amount", 20),
        (else_try),
          (assign, ":win_amount", 8),
        (try_end),
        (val_mul, ":win_amount", ":player_odds"),
        (val_div, ":win_amount", 100),
        (val_add, ":win_amount", 100), #win amount when 100 denars is placed
        (assign, reg0, ":win_amount"),
     ]),

  # script_tournament_place_bet
  # Input: arg1 = bet_amount
  # Output: none
  ("tournament_place_bet",
    [
        (store_script_param, ":bet_amount", 1),
        (call_script, "script_get_win_amount_for_tournament_bet"),
        (assign, ":win_amount", reg0),
        (val_mul, ":win_amount", ":bet_amount"),
        (val_div, ":win_amount", 100),
        (val_sub, ":win_amount", ":bet_amount"),
        (val_add, "$g_tournament_bet_placed", ":bet_amount"),
        (val_add, "$g_tournament_bet_win_amount", ":win_amount"),
        (troop_remove_gold, "trp_player", ":bet_amount"),
        (assign, "$g_tournament_last_bet_tier", "$g_tournament_cur_tier"),
		# Ne finances
		(val_mul,":bet_amount",-1),
        (call_script, "script_adjust_finances", slot_finance_tournament, ":bet_amount"),
		# NE end finances
     ]),

  # script_calculate_amount_of_cattle_can_be_stolen
  # Input: arg1 = village_no
  # Output: reg0 = max_amount
  ("calculate_amount_of_cattle_can_be_stolen",
    [
      (store_script_param, ":village_no", 1),
      (call_script, "script_get_max_skill_of_player_party", "skl_looting"),
      (assign, ":max_skill", reg0),
      (store_mul, ":can_steal", ":max_skill", 2),
      (call_script, "script_party_count_fit_for_battle", "p_main_party"),
      (store_add, ":num_men_effect", reg0, 10),
      (val_div, ":num_men_effect", 10),
      (val_add, ":can_steal", ":num_men_effect"),
      (party_get_slot, ":num_cattle", ":village_no", slot_village_number_of_cattle),
      (val_min, ":can_steal", ":num_cattle"),
      (assign, reg0, ":can_steal"),
     ]),


  # script_draw_banner_to_region
  # Input: arg1 = troop_no, arg2 = center_pos_x, arg3 = center_pos_y, arg4 = width, arg5 = height, arg6 = stretch_width, arg7 = stretch_height, arg8 = default_scale, arg9 = max_charge_scale, arg10 = drawn_item_type
  # drawn_item_type is 0 for banners, 1 for shields, 2 for heater shield, 3 for armor
  # arguments will be used as fixed point values
  # Output: none
  ("draw_banner_to_region",
    [
      (store_script_param, ":troop_no", 1),
      (store_script_param, ":center_pos_x", 2),
      (store_script_param, ":center_pos_y", 3),
      (store_script_param, ":width", 4),
      (store_script_param, ":height", 5),
      (store_script_param, ":stretch_width", 6),
      (store_script_param, ":stretch_height", 7),
      (store_script_param, ":default_scale", 8),
      (store_script_param, ":max_charge_scale", 9),
      (store_script_param, ":drawn_item_type", 10),

      (troop_get_slot, ":bg_type", ":troop_no", slot_troop_custom_banner_bg_type),
      (val_add, ":bg_type", custom_banner_backgrounds_begin),
      (troop_get_slot, ":bg_color_1", ":troop_no", slot_troop_custom_banner_bg_color_1),
      (troop_get_slot, ":bg_color_2", ":troop_no", slot_troop_custom_banner_bg_color_2),
      (troop_get_slot, ":num_charges", ":troop_no", slot_troop_custom_banner_num_charges),
      (troop_get_slot, ":positioning", ":troop_no", slot_troop_custom_banner_positioning),
      (call_script, "script_get_troop_custom_banner_num_positionings", ":troop_no"),
      (assign, ":num_positionings", reg0),
      (val_mod, ":positioning", ":num_positionings"),

      (init_position, pos2),
      (position_set_x, pos2, ":width"),
      (position_set_y, pos2, ":height"),
      (assign, ":default_value", 1),
      (convert_to_fixed_point, ":default_value"),
      (position_set_z, pos2, ":default_value"),

      (init_position, pos1),
      (position_set_x, pos1, ":center_pos_x"),
      (position_set_y, pos1, ":center_pos_y"),
      (position_move_z, pos1, -20),

      (init_position, pos3),
      (position_set_x, pos3, ":default_scale"),
      (position_set_y, pos3, ":default_scale"),
      (position_set_z, pos3, ":default_value"),

      (try_begin),
        (this_or_next|eq, ":bg_type", "mesh_custom_banner_bg"),
        (this_or_next|eq, ":bg_type", "mesh_custom_banner_fg01"),
        (this_or_next|eq, ":bg_type", "mesh_custom_banner_fg02"),
        (this_or_next|eq, ":bg_type", "mesh_custom_banner_fg03"),
        (this_or_next|eq, ":bg_type", "mesh_custom_banner_fg08"),
        (this_or_next|eq, ":bg_type", "mesh_custom_banner_fg09"),
        (this_or_next|eq, ":bg_type", "mesh_custom_banner_fg10"),
        (this_or_next|eq, ":bg_type", "mesh_custom_banner_fg11"),
        (this_or_next|eq, ":bg_type", "mesh_custom_banner_fg12"),
        (this_or_next|eq, ":bg_type", "mesh_custom_banner_fg13"),
        (this_or_next|eq, ":bg_type", "mesh_custom_banner_fg16"),
        (eq, ":bg_type", "mesh_custom_banner_fg17"),
        (cur_tableau_add_mesh_with_scale_and_vertex_color, ":bg_type", pos1, pos2, 0, ":bg_color_1"),
      (else_try),
        (cur_tableau_add_mesh_with_scale_and_vertex_color, ":bg_type", pos1, pos3, 0, ":bg_color_1"),
      (try_end),
      (position_move_z, pos1, -20),
      (position_move_x, pos2, ":width"),
      (position_move_y, pos2, ":height"),
      (cur_tableau_add_mesh_with_scale_and_vertex_color, "mesh_custom_banner_bg", pos1, pos2, 0, ":bg_color_2"),
      
      (assign, ":charge_stretch", ":stretch_width"),
      (val_min, ":charge_stretch", ":stretch_height"),
      (val_min, ":charge_stretch", ":max_charge_scale"),
      (call_script, "script_get_custom_banner_charge_type_position_scale_color", "trp_player", ":positioning"),

      (try_begin),
        (this_or_next|eq, ":drawn_item_type", 2), #heater shield
        (eq, ":drawn_item_type", 3), #armor
        (assign, ":change_center_pos", 0),
        (try_begin),
          (eq, ":num_charges", 1),
          (assign, ":change_center_pos", 1),
        (else_try),
          (eq, ":num_charges", 2),
          (eq, ":positioning", 1),
          (assign, ":change_center_pos", 1),
        (else_try),
          (eq, ":num_charges", 3),
          (eq, ":positioning", 1),
          (assign, ":change_center_pos", 1),
        (try_end),
        (try_begin),
          (eq, ":change_center_pos", 1),
          (val_add, ":center_pos_y", 30),
        (try_end),
      (try_end),
      
      (try_begin),
        (ge, ":num_charges", 1),
        (val_mul, reg1, ":charge_stretch"),
        (val_div, reg1, 10000),
        (position_get_x, ":x", pos0),
        (position_get_y, ":y", pos0),
        (val_mul, ":x", ":stretch_width"),
        (val_mul, ":y", ":stretch_height"),
        (val_div, ":x", 10000),
        (val_div, ":y", 10000),
        (val_add, ":x", ":center_pos_x"),
        (val_add, ":y", ":center_pos_y"),
        (position_set_x, pos0, ":x"),
        (position_set_y, pos0, ":y"),
        (assign, ":scale_value", reg1),
        (convert_to_fixed_point, ":scale_value"),
        (store_mul, ":scale_value_inverse", ":scale_value", -1),
        (init_position, pos4),
        (position_set_x, pos4, ":scale_value"),
        (position_set_y, pos4, ":scale_value"),
        (position_set_z, pos4, ":scale_value"),
        (store_div, ":orientation", reg0, 256), #orientation flags
        (try_begin),
          (this_or_next|eq, ":orientation", 1),
          (eq, ":orientation", 3),
          (position_set_x, pos4, ":scale_value_inverse"),
        (try_end),
        (try_begin),
          (this_or_next|eq, ":orientation", 2),
          (eq, ":orientation", 3),
          (position_set_y, pos4, ":scale_value_inverse"),
        (try_end),
        (val_mod, reg0, 256), #remove orientation flags
        (cur_tableau_add_mesh_with_scale_and_vertex_color, reg0, pos0, pos4, 0, reg2),
      (try_end),
      (try_begin),
        (ge, ":num_charges", 2),
        (val_mul, reg4, ":charge_stretch"),
        (val_div, reg4, 10000),
        (position_get_x, ":x", pos1),
        (position_get_y, ":y", pos1),
        (val_mul, ":x", ":stretch_width"),
        (val_mul, ":y", ":stretch_height"),
        (val_div, ":x", 10000),
        (val_div, ":y", 10000),
        (val_add, ":x", ":center_pos_x"),
        (val_add, ":y", ":center_pos_y"),
        (position_set_x, pos1, ":x"),
        (position_set_y, pos1, ":y"),

        (assign, ":scale_value", reg4),
        (convert_to_fixed_point, ":scale_value"),
        (store_mul, ":scale_value_inverse", ":scale_value", -1),
        (init_position, pos4),
        (position_set_x, pos4, ":scale_value"),
        (position_set_y, pos4, ":scale_value"),
        (position_set_z, pos4, ":scale_value"),
        (store_div, ":orientation", reg3, 256), #orientation flags
        (try_begin),
          (this_or_next|eq, ":orientation", 1),
          (eq, ":orientation", 3),
          (position_set_x, pos4, ":scale_value_inverse"),
        (try_end),
        (try_begin),
          (this_or_next|eq, ":orientation", 2),
          (eq, ":orientation", 3),
          (position_set_y, pos4, ":scale_value_inverse"),
        (try_end),
        (val_mod, reg3, 256), #remove orientation flags

        (cur_tableau_add_mesh_with_scale_and_vertex_color, reg3, pos1, pos4, 0, reg5),
      (try_end),
      (try_begin),
        (ge, ":num_charges", 3),
        (val_mul, reg7, ":charge_stretch"),
        (val_div, reg7, 10000),
        (position_get_x, ":x", pos2),
        (position_get_y, ":y", pos2),
        (val_mul, ":x", ":stretch_width"),
        (val_mul, ":y", ":stretch_height"),
        (val_div, ":x", 10000),
        (val_div, ":y", 10000),
        (val_add, ":x", ":center_pos_x"),
        (val_add, ":y", ":center_pos_y"),
        (position_set_x, pos2, ":x"),
        (position_set_y, pos2, ":y"),

        (assign, ":scale_value", reg7),
        (convert_to_fixed_point, ":scale_value"),
        (store_mul, ":scale_value_inverse", ":scale_value", -1),
        (init_position, pos4),
        (position_set_x, pos4, ":scale_value"),
        (position_set_y, pos4, ":scale_value"),
        (position_set_z, pos4, ":scale_value"),
        (store_div, ":orientation", reg6, 256), #orientation flags
        (try_begin),
          (this_or_next|eq, ":orientation", 1),
          (eq, ":orientation", 3),
          (position_set_x, pos4, ":scale_value_inverse"),
        (try_end),
        (try_begin),
          (this_or_next|eq, ":orientation", 2),
          (eq, ":orientation", 3),
          (position_set_y, pos4, ":scale_value_inverse"),
        (try_end),
        (val_mod, reg6, 256), #remove orientation flags

        (cur_tableau_add_mesh_with_scale_and_vertex_color, reg6, pos2, pos4, 0, reg8),
      (try_end),
      (try_begin),
        (ge, ":num_charges", 4),
        (val_mul, reg10, ":charge_stretch"),
        (val_div, reg10, 10000),
        (position_get_x, ":x", pos3),
        (position_get_y, ":y", pos3),
        (val_mul, ":x", ":stretch_width"),
        (val_mul, ":y", ":stretch_height"),
        (val_div, ":x", 10000),
        (val_div, ":y", 10000),
        (val_add, ":x", ":center_pos_x"),
        (val_add, ":y", ":center_pos_y"),
        (position_set_x, pos3, ":x"),
        (position_set_y, pos3, ":y"),

        (assign, ":scale_value", reg10),
        (convert_to_fixed_point, ":scale_value"),
        (store_mul, ":scale_value_inverse", ":scale_value", -1),
        (init_position, pos4),
        (position_set_x, pos4, ":scale_value"),
        (position_set_y, pos4, ":scale_value"),
        (position_set_z, pos4, ":scale_value"),
        (store_div, ":orientation", reg9, 256), #orientation flags
        (try_begin),
          (this_or_next|eq, ":orientation", 1),
          (eq, ":orientation", 3),
          (position_set_x, pos4, ":scale_value_inverse"),
        (try_end),
        (try_begin),
          (this_or_next|eq, ":orientation", 2),
          (eq, ":orientation", 3),
          (position_set_y, pos4, ":scale_value_inverse"),
        (try_end),
        (val_mod, reg9, 256), #remove orientation flags

        (cur_tableau_add_mesh_with_scale_and_vertex_color, reg9, pos3, pos4, 0, reg11),
      (try_end),
     ]),

  # script_get_troop_custom_banner_num_positionings
  # Input: arg1 = troop_no
  # Output: reg0 = num_positionings
  ("get_troop_custom_banner_num_positionings",
    [
      (store_script_param, ":troop_no", 1),
      (troop_get_slot, ":num_charges", ":troop_no", slot_troop_custom_banner_num_charges),
      (try_begin),
        (eq, ":num_charges", 1),
        (assign, ":num_positionings", 2),
      (else_try),
        (eq, ":num_charges", 2),
        (assign, ":num_positionings", 4),
      (else_try),
        (eq, ":num_charges", 3),
        (assign, ":num_positionings", 6),
      (else_try),
        (assign, ":num_positionings", 2),
      (try_end),
      (assign, reg0, ":num_positionings"),
     ]),

  # script_get_custom_banner_charge_type_position_scale_color
  # Input: arg1 = troop_no, arg2 = positioning_index
  # Output: reg0 = type_1
  #         reg1 = scale_1
  #         reg2 = color_1
  #         reg3 = type_2
  #         reg4 = scale_2
  #         reg5 = color_2
  #         reg6 = type_3
  #         reg7 = scale_3
  #         reg8 = color_3
  #         reg9 = type_4
  #         reg10 = scale_4
  #         reg11 = color_4
  ("get_custom_banner_charge_type_position_scale_color",
    [
      (store_script_param, ":troop_no", 1),
      (store_script_param, ":positioning", 2),
      (troop_get_slot, ":num_charges", ":troop_no", slot_troop_custom_banner_num_charges),
      (init_position, pos0),
      (init_position, pos1),
      (init_position, pos2),
      (init_position, pos3),

      (troop_get_slot, reg0, ":troop_no", slot_troop_custom_banner_charge_type_1),
      (val_add, reg0, custom_banner_charges_begin),
      (troop_get_slot, reg2, ":troop_no", slot_troop_custom_banner_charge_color_1),
      (troop_get_slot, reg3, ":troop_no", slot_troop_custom_banner_charge_type_2),
      (val_add, reg3, custom_banner_charges_begin),
      (troop_get_slot, reg5, ":troop_no", slot_troop_custom_banner_charge_color_2),
      (troop_get_slot, reg6, ":troop_no", slot_troop_custom_banner_charge_type_3),
      (val_add, reg6, custom_banner_charges_begin),
      (troop_get_slot, reg8, ":troop_no", slot_troop_custom_banner_charge_color_3),
      (troop_get_slot, reg9, ":troop_no", slot_troop_custom_banner_charge_type_4),
      (val_add, reg9, custom_banner_charges_begin),
      (troop_get_slot, reg11, ":troop_no", slot_troop_custom_banner_charge_color_4),

      (try_begin),
        (eq, ":num_charges", 1),
        (try_begin),
          (eq, ":positioning", 0),
          (assign, reg1, 100),
        (else_try),
          (assign, reg1, 50),
        (try_end),
      (else_try),
        (eq, ":num_charges", 2),
        (try_begin),
          (eq, ":positioning", 0),
          (position_set_y, pos0, 25),
          (position_set_y, pos1, -25),
          (assign, reg1, 40),
          (assign, reg4, 40),
        (else_try),
          (eq, ":positioning", 1),
          (position_set_x, pos0, -25),
          (position_set_x, pos1, 25),
          (assign, reg1, 40),
          (assign, reg4, 40),
        (else_try),
          (eq, ":positioning", 2),
          (position_set_x, pos0, -25),
          (position_set_y, pos0, 25),
          (position_set_x, pos1, 25),
          (position_set_y, pos1, -25),
          (assign, reg1, 50),
          (assign, reg4, 50),
        (else_try),
          (position_set_x, pos0, -25),
          (position_set_y, pos0, -25),
          (position_set_x, pos1, 25),
          (position_set_y, pos1, 25),
          (assign, reg1, 50),
          (assign, reg4, 50),
        (try_end),
      (else_try),
        (eq, ":num_charges", 3),
        (try_begin),
          (eq, ":positioning", 0),
          (position_set_y, pos0, 33),
          (position_set_y, pos2, -33),
          (assign, reg1, 30),
          (assign, reg4, 30),
          (assign, reg7, 30),
        (else_try),
          (eq, ":positioning", 1),
          (position_set_x, pos0, -33),
          (position_set_x, pos2, 33),
          (assign, reg1, 30),
          (assign, reg4, 30),
          (assign, reg7, 30),
        (else_try),
          (eq, ":positioning", 2),
          (position_set_x, pos0, -30),
          (position_set_y, pos0, 30),
          (position_set_x, pos2, 30),
          (position_set_y, pos2, -30),
          (assign, reg1, 35),
          (assign, reg4, 35),
          (assign, reg7, 35),
        (else_try),
          (eq, ":positioning", 3),
          (position_set_x, pos0, -30),
          (position_set_y, pos0, -30),
          (position_set_x, pos2, 30),
          (position_set_y, pos2, 30),
          (assign, reg1, 35),
          (assign, reg4, 35),
          (assign, reg7, 35),
        (else_try),
          (eq, ":positioning", 4),
          (position_set_x, pos0, -25),
          (position_set_y, pos0, -25),
          (position_set_y, pos1, 25),
          (position_set_x, pos2, 25),
          (position_set_y, pos2, -25),
          (assign, reg1, 50),
          (assign, reg4, 50),
          (assign, reg7, 50),
        (else_try),
          (position_set_x, pos0, -25),
          (position_set_y, pos0, 25),
          (position_set_y, pos1, -25),
          (position_set_x, pos2, 25),
          (position_set_y, pos2, 25),
          (assign, reg1, 50),
          (assign, reg4, 50),
          (assign, reg7, 50),
        (try_end),
      (else_try),
        (try_begin),
          (eq, ":positioning", 0),
          (position_set_x, pos0, -25),
          (position_set_y, pos0, 25),
          (position_set_x, pos1, 25),
          (position_set_y, pos1, 25),
          (position_set_x, pos2, -25),
          (position_set_y, pos2, -25),
          (position_set_x, pos3, 25),
          (position_set_y, pos3, -25),
          (assign, reg1, 50),
          (assign, reg4, 50),
          (assign, reg7, 50),
          (assign, reg10, 50),
        (else_try),
          (position_set_y, pos0, 30),
          (position_set_x, pos1, -30),
          (position_set_x, pos2, 30),
          (position_set_y, pos3, -30),
          (assign, reg1, 35),
          (assign, reg4, 35),
          (assign, reg7, 35),
          (assign, reg10, 35),
        (try_end),
      (try_end),
     ]),

  # script_get_random_custom_banner
  # Input: arg1 = troop_no
  # Output: none
  ("get_random_custom_banner",
    [
      (store_script_param, ":troop_no", 1),
      (store_random_in_range, ":num_charges", 1, 5),
      (troop_set_slot, ":troop_no", slot_troop_custom_banner_num_charges, ":num_charges"),
      (store_random_in_range, ":random_color_index", 0, 42),
      (call_script, "script_get_custom_banner_color_from_index", ":random_color_index"),
      (assign, ":color_1", reg0),
      (troop_set_slot, ":troop_no", slot_troop_custom_banner_bg_color_1, ":color_1"),
      (assign, ":end_cond", 1),
      (try_for_range, ":unused", 0, ":end_cond"),
        (store_random_in_range, ":random_color_index", 0, 42),
        (call_script, "script_get_custom_banner_color_from_index", ":random_color_index"),
        (assign, ":color_2", reg0),
        (try_begin),
          (call_script, "script_cf_check_color_visibility", ":color_1", ":color_2"),
          (troop_set_slot, ":troop_no", slot_troop_custom_banner_bg_color_2, ":color_2"),
        (else_try),
          (val_add, ":end_cond", 1),
        (try_end),
      (try_end),
      (assign, ":end_cond", 4),
      (assign, ":cur_charge", 0),
      (try_for_range, ":unused", 0, ":end_cond"),
        (store_random_in_range, ":random_color_index", 0, 42),
        (call_script, "script_get_custom_banner_color_from_index", ":random_color_index"),
        (assign, ":charge_color", reg0),
        (try_begin),
          (call_script, "script_cf_check_color_visibility", ":charge_color", ":color_1"),
          (call_script, "script_cf_check_color_visibility", ":charge_color", ":color_2"),
          (store_add, ":cur_slot", ":cur_charge", slot_troop_custom_banner_charge_color_1),
          (troop_set_slot, ":troop_no", ":cur_slot", ":charge_color"),
          (store_random_in_range, ":random_charge", custom_banner_charges_begin, custom_banner_charges_end),
          (val_sub, ":random_charge", custom_banner_charges_begin),
          (store_add, ":cur_slot", ":cur_charge", slot_troop_custom_banner_charge_type_1),
          (troop_set_slot, ":troop_no", ":cur_slot", ":random_charge"),
          (val_add, ":cur_charge", 1),
        (else_try),
          (val_add, ":end_cond", 1),
        (try_end),
      (try_end),
      (store_random_in_range, ":random_bg", custom_banner_backgrounds_begin, custom_banner_backgrounds_end),
      (val_sub, ":random_bg", custom_banner_backgrounds_begin),
      (troop_set_slot, ":troop_no", slot_troop_custom_banner_bg_type, ":random_bg"),
      (store_random_in_range, ":random_flag", custom_banner_flag_types_begin, custom_banner_flag_types_end),
      (val_sub, ":random_flag", custom_banner_flag_types_begin),
      (troop_set_slot, ":troop_no", slot_troop_custom_banner_flag_type, ":random_flag"),
      (store_random_in_range, ":random_positioning", 0, 4),
      (troop_set_slot, ":troop_no", slot_troop_custom_banner_positioning, ":random_positioning"),
     ]),

  # script_get_custom_banner_color_from_index
  # Input: arg1 = color_index
  # Output: reg0 = color
  ("get_custom_banner_color_from_index",
    [
      (store_script_param, ":color_index", 1),

      (assign, ":cur_color", 0xFF000000),
      (assign, ":red", 0x00),
      (assign, ":green", 0x00),
      (assign, ":blue", 0x00),
      (store_mod, ":mod_i_color", ":color_index", 7),
      (try_begin),
        (eq, ":mod_i_color", 0),
        (assign, ":blue", 0xFF),
      (else_try),
        (eq, ":mod_i_color", 1),
        (assign, ":red", 0xEE),
      (else_try),
        (eq, ":mod_i_color", 2),
        (assign, ":red", 0xFB),
        (assign, ":green", 0xAC),
      (else_try),
        (eq, ":mod_i_color", 3),
        (assign, ":red", 0x5F),
        (assign, ":blue", 0xFF),
      (else_try),
        (eq, ":mod_i_color", 4),
        (assign, ":red", 0x05),
        (assign, ":green", 0x44),
      (else_try),
        (eq, ":mod_i_color", 5),
        (assign, ":red", 0xEE),
        (assign, ":green", 0xEE),
        (assign, ":blue", 0xEE),
      (else_try),
        (assign, ":red", 0x22),
        (assign, ":green", 0x22),
        (assign, ":blue", 0x22),
      (try_end),
      (store_div, ":cur_tone", ":color_index", 7),
      (store_sub, ":cur_tone", 8, ":cur_tone"),
      (val_mul, ":red", ":cur_tone"),
      (val_div, ":red", 8),
      (val_mul, ":green", ":cur_tone"),
      (val_div, ":green", 8),
      (val_mul, ":blue", ":cur_tone"),
      (val_div, ":blue", 8),
      (val_mul, ":green", 0x100),
      (val_mul, ":red", 0x10000),
      (val_add, ":cur_color", ":blue"),
      (val_add, ":cur_color", ":green"),
      (val_add, ":cur_color", ":red"),
      (assign, reg0, ":cur_color"),
     ]),

  # script_cf_check_color_visibility
  # Input: arg1 = color_1, arg2 = color_2
  # Output: none
  ("cf_check_color_visibility",
    [
      (store_script_param, ":color_1", 1),
      (store_script_param, ":color_2", 2),
      (store_mod, ":blue_1", ":color_1", 256),
      (store_div, ":green_1", ":color_1", 256),
      (val_mod, ":green_1", 256),
      (store_div, ":red_1", ":color_1", 256 * 256),
      (val_mod, ":red_1", 256),
      (store_mod, ":blue_2", ":color_2", 256),
      (store_div, ":green_2", ":color_2", 256),
      (val_mod, ":green_2", 256),
      (store_div, ":red_2", ":color_2", 256 * 256),
      (val_mod, ":red_2", 256),
      (store_sub, ":red_dif", ":red_1", ":red_2"),
      (val_abs, ":red_dif"),
      (store_sub, ":green_dif", ":green_1", ":green_2"),
      (val_abs, ":green_dif"),
      (store_sub, ":blue_dif", ":blue_1", ":blue_2"),
      (val_abs, ":blue_dif"),
      (assign, ":max_dif", 0),
      (val_max, ":max_dif", ":red_dif"),
      (val_max, ":max_dif", ":green_dif"),
      (val_max, ":max_dif", ":blue_dif"),
      (ge, ":max_dif", 64),
     ]),
  
  # script_get_next_active_kingdom
  # Input: arg1 = faction_no
  # Output: reg0 = faction_no (does not choose player faction)
  ("get_next_active_kingdom",
    [
      (store_script_param, ":faction_no", 1),
      (assign, ":end_cond", kingdoms_end),
      (try_for_range, ":unused", kingdoms_begin, ":end_cond"),
        (val_add, ":faction_no", 1),
        (try_begin),
          (ge, ":faction_no", kingdoms_end),
          (assign, ":faction_no", kingdoms_begin),
        (try_end),
        (faction_slot_eq, ":faction_no", slot_faction_state, sfs_active),
        (neq, ":faction_no", "fac_player_supporters_faction"),
        (assign, ":end_cond", 0),
      (try_end),
      (assign, reg0, ":faction_no"),
     ]),

#  # script_store_average_center_value_per_faction
#  # Input: none
#  # Output: none (sets $g_average_center_value_per_faction)
#  ("store_average_center_value_per_faction",
#    [
#      (store_sub, ":num_towns", towns_end, towns_begin),
#      (store_sub, ":num_castles", castles_end, castles_begin),
#      (assign, ":num_factions", 0),
#      (try_for_range, ":faction_no", kingdoms_begin, kingdoms_end),
#        (faction_slot_eq, ":faction_no", slot_faction_state, sfs_active),
#        (val_add, ":num_factions", 1),
#      (try_end),
#      (val_max, ":num_factions", 1),
#      (store_mul, "$g_average_center_value_per_faction", ":num_towns", 2),
#      (val_add, "$g_average_center_value_per_faction", ":num_castles"),
#      (val_mul, "$g_average_center_value_per_faction", 10),
#      (val_div, "$g_average_center_value_per_faction", ":num_factions"),
#     ]),

  # script_remove_cattles_if_herd_is_close_to_party
  # Input: arg1 = party_no, arg2 = maximum_number_of_cattles_required
  # Output: reg0 = number_of_cattles_removed
  ("remove_cattles_if_herd_is_close_to_party",
    [
      (store_script_param, ":party_no", 1),
      (store_script_param, ":max_req", 2),
      (assign, ":cur_req", ":max_req"),
      (try_for_parties, ":cur_party"),
        (gt, ":cur_req", 0),
        (party_slot_eq, ":cur_party", slot_party_type, spt_cattle_herd),
        (store_distance_to_party_from_party, ":dist", ":cur_party", ":party_no"),
        (lt, ":dist", 3),
		
        #Do not use the quest herd for "move cattle herd"
        (assign, ":subcontinue", 1),
        (try_begin),
          (check_quest_active, "qst_move_cattle_herd"),
          (quest_slot_eq, "qst_move_cattle_herd", slot_quest_target_party, ":cur_party"),
          (assign, ":subcontinue", 0),
        (try_end),
        (eq, ":subcontinue", 1),
        #Do not use the quest herd for "move cattle herd" ends
		
        (party_count_companions_of_type, ":num_cattle", ":cur_party", "trp_cattle"),
        (try_begin),
          (le, ":num_cattle", ":cur_req"),
          (assign, ":num_added", ":num_cattle"),
          (remove_party, ":cur_party"),
        (else_try),
          (assign, ":num_added", ":cur_req"),
          (party_remove_members, ":cur_party", "trp_cattle", ":cur_req"),
        (try_end),
        (val_sub, ":cur_req", ":num_added"),
		
		
        (try_begin),
          (party_slot_eq, ":party_no", slot_party_type, spt_village),
          (party_get_slot, ":village_cattle_amount", ":party_no", slot_village_number_of_cattle),
          (val_add, ":village_cattle_amount", ":num_added"),
          (party_set_slot, ":party_no", slot_village_number_of_cattle, ":village_cattle_amount"),
        (try_end),
		
        (assign, reg3, ":num_added"),
        (str_store_party_name_link, s1, ":party_no"),
        (display_message, "@You brought {reg3} heads of cattle to {s1}."),
		(try_begin),
			(gt, "$cheat_mode", 0),
			(assign, reg4, ":village_cattle_amount"),
			(display_message, "@{!}Village now has {reg4}"),
		(try_end),
      (try_end),
      (store_sub, reg0, ":max_req", ":cur_req"),
     ]),  

  # script_get_rumor_to_s61
  # Input: rumor_id
  # Output: reg0 = 1 if rumor found, 0 otherwise; s61 will contain rumor string if found
  ("get_rumor_to_s61",
    [
     (store_script_param, ":base_rumor_id", 1), # the script returns the same rumor for the same rumor id, so that one cannot hear all rumors by
                                                # speaking to a single person.

     (store_current_hours, ":cur_hours"),
     (store_div, ":cur_day", ":cur_hours", 24),
     (assign, ":rumor_found", 0),
     (assign, ":num_tries", 3),
     (try_for_range, ":try_no", 0, ":num_tries"),
       (store_mul, ":rumor_id", ":try_no", 6781),
       (val_add, ":rumor_id", ":base_rumor_id"),
       (store_mod, ":rumor_type", ":rumor_id", 7),
       (val_add, ":rumor_id", ":cur_hours"),
       (try_begin),
         (eq,  ":rumor_type", 0),
         (try_begin),
           (store_sub, ":range", towns_end, towns_begin),
           (store_mod, ":random_center", ":rumor_id", ":range"),
           (val_add, ":random_center", towns_begin),
           (party_slot_ge, ":random_center", slot_town_has_tournament, 1),
           (neq, ":random_center", "$current_town"),
           (str_store_party_name, s62, ":random_center"),
           (str_store_string, s61, "@I heard that there will be a tournament in {s62} soon."),
           (assign, ":rumor_found", 1),
         (try_end),
       (else_try),
         (eq,  ":rumor_type", 1),
         (try_begin),
           (store_sub, ":range", active_npcs_end, original_kingdom_heroes_begin), #was reversed
           (store_mod, ":random_hero", ":rumor_id", ":range"),
           (val_add, ":random_hero", original_kingdom_heroes_begin),
		   (is_between, ":random_hero", active_npcs_begin, active_npcs_end),
           (troop_get_slot, ":personality", ":random_hero", slot_lord_reputation_type),
           (gt, ":personality", 0),
           (store_add, ":rumor_string", ":personality", "str_gossip_about_character_default"),
           (str_store_troop_name, s6, ":random_hero"),
           (str_store_string, s61, ":rumor_string"),
           (assign, ":rumor_found", 1),
         (try_end),
       (else_try),
         (eq,  ":rumor_type", 2),
         (try_begin),
           (store_sub, ":range", trade_goods_end, trade_goods_begin),
           (store_add, ":random_trade_good", ":rumor_id", ":cur_day"),
           (store_mod, ":random_trade_good", ":random_trade_good", ":range"),
           (store_add, ":random_trade_good_slot", ":random_trade_good", slot_town_trade_good_prices_begin),
           (val_add, ":random_trade_good", trade_goods_begin),
           (store_mul, ":min_price", average_price_factor, 3),
           (val_div, ":min_price", 4),
           (assign, ":min_price_center", -1),
           (try_for_range, ":sub_try_no", 0, 10),
             (store_sub, ":range", towns_end, towns_begin),
             (store_add, ":center_rumor_id", ":rumor_id", ":sub_try_no"),
             (store_mod, ":random_center", ":center_rumor_id", ":range"),
             (val_add, ":random_center", towns_begin),
             (neq, ":random_center", "$g_encountered_party"),
             (party_get_slot, ":cur_price", ":random_center", ":random_trade_good_slot"),
             (lt, ":cur_price", ":min_price"),
             (assign, ":min_price", ":cur_price"),
             (assign, ":min_price_center", ":random_center"),
           (try_end),
           (ge, ":min_price_center", 0),
           (str_store_item_name, s62, ":random_trade_good"),
           (str_store_party_name, s63, ":min_price_center"),
           (str_store_string, s61, "@I heard that one can buy {s62} very cheap at {s63}."),
           (assign, ":rumor_found", 1),
         (try_end),
       (else_try),
         (eq,  ":rumor_type", 3),
         (try_begin),
           (store_sub, ":range", trade_goods_end, trade_goods_begin),
           (store_add, ":random_trade_good", ":rumor_id", ":cur_day"),
           (store_mod, ":random_trade_good", ":random_trade_good", ":range"),
           (store_add, ":random_trade_good_slot", ":random_trade_good", slot_town_trade_good_prices_begin),
           (val_add, ":random_trade_good", trade_goods_begin),
           (store_mul, ":max_price", average_price_factor, 5),
           (val_div, ":max_price", 4),
           (assign, ":max_price_center", -1),
           (try_for_range, ":sub_try_no", 0, 10),
             (store_sub, ":range", towns_end, towns_begin),
             (store_add, ":center_rumor_id", ":rumor_id", ":sub_try_no"),
             (store_mod, ":random_center", ":center_rumor_id", ":range"),
             (val_add, ":random_center", towns_begin),
             (neq, ":random_center", "$g_encountered_party"),
             (party_get_slot, ":cur_price", ":random_center", ":random_trade_good_slot"),
             (gt, ":cur_price", ":max_price"),
             (assign, ":max_price", ":cur_price"),
             (assign, ":max_price_center", ":random_center"),
           (try_end),
           (ge, ":max_price_center", 0),
           (str_store_item_name, s62, ":random_trade_good"),
           (str_store_party_name, s63, ":max_price_center"),
           (str_store_string, s61, "@I heard that they pay a very high price for {s62} at {s63}."),
           (assign, ":rumor_found", 1),
         (try_end),
       (try_end),
       (try_begin),
         (gt, ":rumor_found", 0),
         (assign, ":num_tries", 0),
       (try_end),
     (try_end),
     (assign, reg0, ":rumor_found"),
     ]),

  ("lord_comment_to_s43",
    [(store_script_param, ":lord", 1),
     (store_script_param, ":default_string", 2),

    (troop_get_slot,":reputation", ":lord", slot_lord_reputation_type),

	(try_begin),
		#some default strings will have added comments for the added commons reputation types
		(try_begin),
			(eq, ":reputation", lrep_roguish),
			(assign, ":reputation", lrep_goodnatured),
		(else_try),	
			(eq, ":reputation", lrep_custodian),
			(assign, ":reputation", lrep_cunning),
		(else_try),	
			(eq, ":reputation", lrep_benefactor),
			(assign, ":reputation", lrep_goodnatured),
		(try_end),	
	(try_end),

    (store_add, ":result", ":reputation", ":default_string"),

    (str_store_string, 43, ":result"),
	(assign, reg0, ":result"),
	
	
	]),
  
#Troop Commentaries begin
  
  # script_add_log_entry
  # Input: arg1 = entry_type, arg2 = event_actor, arg3 = center_object, arg4 = troop_object, arg5 = faction_object
  # Output: none
  ("add_log_entry",
    [(store_script_param, ":entry_type", 1),
     (store_script_param, ":actor", 2),
     (store_script_param, ":center_object", 3),
     (store_script_param, ":troop_object", 4),
     (store_script_param, ":faction_object", 5),
     (assign, ":center_object_lord", -1),
     (assign, ":center_object_faction", -1),
     (assign, ":troop_object_faction", -1),
     
     (try_begin),
       (party_is_active, ":center_object", 0),
       (party_get_slot, ":center_object_lord", ":center_object", slot_town_lord),
       (store_faction_of_party, ":center_object_faction", ":center_object"),
	 (else_try),
	   (assign, ":center_object_lord", 0),	 
       (assign, ":center_object_faction", 0),	 
     (try_end),
     
     (try_begin),
       (is_between, ":troop_object", 0, "trp_local_merchant"),
       (store_troop_faction, ":troop_object_faction", ":troop_object"),
	 (else_try),
	   (assign, ":troop_object_faction", 0),
     (try_end),

     (val_add, "$num_log_entries", 1),
     
     (store_current_hours, ":entry_time"),
     (troop_set_slot, "trp_log_array_entry_type",            "$num_log_entries", ":entry_type"),
     (troop_set_slot, "trp_log_array_entry_time",            "$num_log_entries", ":entry_time"),
     (troop_set_slot, "trp_log_array_actor",                 "$num_log_entries", ":actor"),
     (troop_set_slot, "trp_log_array_center_object",         "$num_log_entries", ":center_object"),
     (troop_set_slot, "trp_log_array_center_object_lord",    "$num_log_entries", ":center_object_lord"),
     (troop_set_slot, "trp_log_array_center_object_faction", "$num_log_entries", ":center_object_faction"),
     (troop_set_slot, "trp_log_array_troop_object",          "$num_log_entries", ":troop_object"),
     (troop_set_slot, "trp_log_array_troop_object_faction",  "$num_log_entries", ":troop_object_faction"),
     (troop_set_slot, "trp_log_array_faction_object",        "$num_log_entries", ":faction_object"),

     (try_begin),
       (eq, "$cheat_mode", 1),
       (assign, reg3, "$num_log_entries"), 
       (assign, reg4, ":entry_type"),
       (display_message, "@{!}Log entry {reg3}: type {reg4}"), 
       (try_begin),
          (gt, ":center_object", 0),
		  (neq, ":entry_type", logent_traveller_attacked),
		  (neq, ":entry_type", logent_party_traded),
		  (party_is_active, ":center_object"), #sometimes is a troop
		  
          (str_store_party_name, s4, ":center_object"),
          (display_message, "@{!}Center: {s4}"), 
       (try_end),      
       (try_begin),
          (gt, ":troop_object", 0),
		  (neq, ":entry_type", logent_traveller_attacked),
		  (neq, ":entry_type", logent_party_traded),
		  
		  (str_store_troop_name, s4, ":troop_object"),
		  (display_message, "@{!}Troop: {s4}"), 
       (try_end),      
       (try_begin),
          (gt, ":center_object_lord", 0),
		  (neq, ":entry_type", logent_traveller_attacked),
		  (neq, ":entry_type", logent_party_traded),
		  
		  (str_store_troop_name, s4, ":center_object_lord"),
          (display_message, "@{!}Lord: {s4}"), 
       (try_end),
     (try_end),


     (try_begin),
	   (this_or_next|eq, ":entry_type", logent_lord_defeated_by_player),
       (this_or_next|eq, ":entry_type", logent_player_participated_in_major_battle),
		(eq, ":entry_type", logent_player_participated_in_siege),
		
       (try_begin),
         (eq, "$cheat_mode", 1),
         (display_message, "@{!}Ally party is present"),
       (try_end),
       (try_for_range, ":hero", active_npcs_begin, active_npcs_end),
         (party_count_companions_of_type, ":hero_present", "p_collective_friends", ":hero"),
         (gt, ":hero_present", 0),
         (troop_set_slot, ":hero", slot_troop_present_at_event, "$num_log_entries"),
#         (store_sub, ":skip_up_to_here", "$num_log_entries", 1),
#         (troop_set_slot, ":hero", slot_troop_last_comment_slot, ":skip_up_to_here"),
         (try_begin),
           (eq, "$cheat_mode", 1),
           (str_store_troop_name, s4, ":hero"),
           (display_message, "@{!}{s4} is present at event"),
         (try_end),
       (try_end),
     (try_end),
     ]),

  
  # script_get_relevant_comment_for_log_entry
  # Input: arg1 = log_entry_no, 
  # Output: reg0 = comment_id; reg1 = relevance
  # Notes: 50 is the default relevance.
  # A comment with relevance less than 30 will always be skipped.
  # A comment with relevance 75 or more will never be skipped.
  # A comment with relevance 50 has about 50% chance to be skipped.
  # If there is more than one comment that is not skipped, the system will randomize their relevance values, and then choose the highest one.
  # Also note that the relevance of events decreases as time passes. After three months, relevance reduces to 50%, after 6 months, 25%, etc...
  ("get_relevant_comment_for_log_entry",
    [(store_script_param, ":log_entry_no", 1),
     
     (troop_get_slot, ":entry_type",            "trp_log_array_entry_type",            ":log_entry_no"),
     (troop_get_slot, ":entry_time",            "trp_log_array_entry_time",            ":log_entry_no"),
     (troop_get_slot, ":actor",                 "trp_log_array_actor",                 ":log_entry_no"),
     (troop_get_slot, ":center_object",         "trp_log_array_center_object",         ":log_entry_no"),
     (troop_get_slot, ":center_object_lord",    "trp_log_array_center_object_lord",    ":log_entry_no"),
     (troop_get_slot, ":center_object_faction", "trp_log_array_center_object_faction", ":log_entry_no"),
     (troop_get_slot, ":troop_object",          "trp_log_array_troop_object",          ":log_entry_no"),
     (troop_get_slot, ":troop_object_faction",  "trp_log_array_troop_object_faction",  ":log_entry_no"),
     (troop_get_slot, ":faction_object",        "trp_log_array_faction_object",        ":log_entry_no"),

     (assign, ":relevance", 0),
     (assign, ":comment", -1), 
     (assign, ":rejoinder", -1), 
     (assign, ":suggested_relation_change", 0),

     (troop_get_slot, ":reputation", "$g_talk_troop", slot_lord_reputation_type),
     (store_current_hours, ":current_time"),
     (store_sub, ":entry_hours_elapsed", ":current_time", ":entry_time"),

#Post 0907 changes begin
     (assign, ":players_kingdom_relation", 0), ##the below is so that lords will not congratulate player on attacking neutrals
	 (try_begin),
        (gt, "$players_kingdom", 0),
		(store_relation, ":players_kingdom_relation", "$players_kingdom", ":troop_object_faction"),
	 (try_end),
	 
     (try_begin),
       (eq, "$cheat_mode", -1), #temporarily disabled
       (try_begin),
         (assign, reg5, ":log_entry_no"),
         (assign, reg6, ":entry_type"),
         (assign, reg8, ":entry_time"),

         (gt, "$players_kingdom", 0),
         (try_begin),
            (gt, ":troop_object_faction", 0),
            (assign, reg7, ":players_kingdom_relation"),
            (display_message, "@{!}Event #{reg5}, type {reg6}, time {reg8}: player's kingdom relation to troop object = {reg7}"),
         (else_try),
            (gt, ":center_object_faction", 0),
            (assign, reg7, ":players_kingdom_relation"),
            (display_message, "@{!}Event #{reg5}, type {reg6}, time {reg8}: player's kingdom relation to center object faction = {reg7}"),
         (else_try),
            (gt, ":faction_object", 0),
            (assign, reg7, ":players_kingdom_relation"),
            (display_message, "@{!}Event #{reg5}, type {reg6}, time {reg8}: player's kingdom relation to faction object = {reg7}"),
         (else_try),
            (display_message, "@{!}Event #{reg5}, type {reg6}, time {reg8}. No relevant kingdom relation"),
         (try_end),
       (else_try),
         (display_message, "@{!}Event #{reg5}, type {reg6}, time {reg8}. Player unaffiliated"),
       (try_end),
     (try_end),

     (try_begin),
       (eq, ":entry_type", logent_game_start),
       (eq, "$g_talk_troop_met", 0),
       (is_between, "$g_talk_troop_faction_relation", -5, 5),
       (is_between, "$g_talk_troop_relation", -5, 5),

       (assign, ":relevance", 25),
       (troop_get_slot, ":plyr_renown", "trp_player", slot_troop_renown),
#normal_banner_begin
       (troop_get_slot, ":banner", "trp_player", slot_troop_banner_scene_prop),
#custom_banner_begin
#       (troop_get_slot, ":banner", "trp_player", slot_troop_custom_banner_flag_type),
       (store_random_in_range, ":renown_check", 100, 200),
       (try_begin),
          (eq, ":reputation", lrep_none),
          (gt, "$players_kingdom", 0),
          (assign, ":comment", "str_comment_intro_liege_affiliated"),
		  (try_begin),
			(faction_slot_eq, "$players_kingdom", slot_faction_leader, "trp_player"),
			(assign, ":comment", "str_comment_intro_liege_affiliated_to_player"),
		  (try_end),
	   (else_try),
		  (eq, "$character_gender",tf_female),
		  
		  (call_script, "script_troop_get_romantic_chemistry_with_troop", "$g_talk_troop", "trp_player"),
		  (assign, ":attraction", reg0),
		  (store_random_in_range, ":random", 0, 2),
		  (this_or_next|eq, ":random", 0),
			  (gt, ":attraction", 10),
		  
		  (try_begin),
            (this_or_next|gt, ":plyr_renown", ":renown_check"), 
				(eq, "$g_disable_condescending_comments", 1),
            (assign, ":comment", "str_comment_intro_female_famous_liege"),
            (val_add, ":comment", ":reputation"),
		  (else_try),
		    (ge, ":attraction", 9),
			(assign, ":comment", "str_comment_intro_female_admiring_liege"),
			(val_add, ":comment", ":reputation"),
		  (else_try),	
            (gt, ":banner", 0), 
			(assign, ":comment", "str_comment_intro_female_noble_liege"),
			(val_add, ":comment", ":reputation"),
		  (else_try),
			(assign, ":comment", "str_comment_intro_female_common_liege"),
			(val_add, ":comment", ":reputation"),
		  (try_end),
		  
		  #Rejoinders for comments
		  (try_begin),
			(eq, ":comment", "str_comment_intro_female_common_badtempered"),
			(assign, ":rejoinder", "str_rejoinder_intro_female_common_badtempered"),
		  (else_try),
			(eq, ":comment", "str_comment_intro_female_noble_pitiless"),
			(assign, ":rejoinder", "str_rejoinder_intro_female_noble_pitiless"),
		  (else_try),
			(eq, ":comment", "str_comment_intro_female_common_pitiless"),
			(assign, ":rejoinder", "str_rejoinder_intro_female_common_pitiless"),
		  (else_try),
			(eq, ":comment", "str_comment_intro_female_noble_sadistic"),
			(assign, ":rejoinder", "str_rejoinder_intro_female_noble_sadistic"),
		  (else_try),
			(eq, ":comment", "str_comment_intro_female_common_sadistic"),
			(assign, ":rejoinder", "str_rejoinder_intro_female_common_sadistic"),			
		  (else_try),
			(eq, ":comment", "str_comment_intro_female_common_upstanding"),
			(assign, ":rejoinder", "str_rejoinder_intro_female_common_upstanding"),
		  (else_try),
			(eq, ":comment", "str_comment_intro_female_noble_upstanding"),
			(assign, ":rejoinder", "str_rejoinder_intro_female_noble_upstanding"),
		  (else_try),
			(eq, ":comment", "str_comment_intro_female_common_martial"),
			(assign, ":rejoinder", "str_rejoinder_intro_female_common_martial"),
		  (else_try),
			(eq, ":comment", "str_comment_intro_female_sadistic_admiring"),
			(assign, ":rejoinder", "str_rejoinder_intro_female_sadistic_admiring"),
		  (else_try),
			(eq, ":comment", "str_comment_intro_female_badtempered_admiring"),
			(assign, ":rejoinder", "str_rejoinder_intro_female_badtempered_admiring"),
		  (else_try),
			(eq, ":comment", "str_comment_intro_female_pitiless_admiring"),
			(assign, ":rejoinder", "str_rejoinder_intro_female_pitiless_admiring"),
		  (try_end),
		  
	   (else_try),
		  #Male character or non-gendered comment
		  (try_begin),
			(gt, ":plyr_renown", ":renown_check"),
            (assign, ":comment", "str_comment_intro_famous_liege"),
            (val_add, ":comment", ":reputation"),
		  (else_try),	
            (gt, ":banner", 0), 
			(assign, ":comment", "str_comment_intro_noble_liege"),
			(val_add, ":comment", ":reputation"),
			
			(try_begin),
				(eq, ":comment", "str_comment_intro_noble_sadistic"),
				(assign, ":rejoinder", "str_rejoinder_intro_noble_sadistic"),
			(try_end),
			
          (else_try),
            (assign, ":comment", "str_comment_intro_common_liege"),
            (val_add, ":comment", ":reputation"),									
		  (try_end),
       (try_end),
#Post 0907 changes end

     (else_try),
       (eq, ":entry_type", logent_village_raided),
       (eq, ":actor", "trp_player"),
       (try_begin),
         (eq, ":center_object_lord", "$g_talk_troop"),
         (assign, ":relevance", 200),
         (assign, ":suggested_relation_change", -1),
         (assign, ":comment", "str_comment_you_raided_my_village_default"),
         (try_begin),
            (lt, "$g_talk_troop_faction_relation", -5),
            (this_or_next|eq, ":reputation", lrep_goodnatured),
                (eq, ":reputation", lrep_upstanding),
            (assign, ":comment", "str_comment_you_raided_my_village_enemy_benevolent"),
         (else_try),
            (lt, "$g_talk_troop_faction_relation", -5),
            (this_or_next|eq, ":reputation", lrep_cunning),
                (eq, ":reputation", lrep_selfrighteous),
            (assign, ":comment", "str_comment_you_raided_my_village_enemy_coldblooded"),
         (else_try),
            (lt, "$g_talk_troop_faction_relation", -5),
            (this_or_next|eq, ":reputation", lrep_quarrelsome),
                (eq, ":reputation", lrep_debauched),
            (assign, ":comment", "str_comment_you_raided_my_village_enemy_spiteful"),
         (else_try),
            (lt, "$g_talk_troop_faction_relation", -5),
            (assign, ":comment", "str_comment_you_raided_my_village_enemy"),
         (else_try),
            (lt, "$g_talk_troop_relation", -5),
            (this_or_next|eq, ":reputation", lrep_quarrelsome),
                (eq, ":reputation", lrep_debauched),
            (assign, ":comment", "str_comment_you_raided_my_village_unfriendly_spiteful"),
         (else_try),
            (gt, "$g_talk_troop_relation", 5),
            (assign, ":comment", "str_comment_you_raided_my_village_friendly"),
         (try_end),
       (try_end),

     (else_try),
       (eq, ":entry_type", logent_village_extorted),
       (eq, ":actor", "trp_player"),
       (try_begin),
         (eq, ":center_object_lord", "$g_talk_troop"),
         (assign, ":relevance", 30),
         (assign, ":suggested_relation_change", -1),
         (assign, ":comment", "str_comment_you_robbed_my_village_default"),
         (try_begin),
            (lt, "$g_talk_troop_faction_relation", -5),
            (this_or_next|eq, ":reputation", lrep_cunning),
                (eq, ":reputation", lrep_selfrighteous),
            (assign, ":comment", "str_comment_you_robbed_my_village_enemy_coldblooded"),
         (else_try),
            (lt, "$g_talk_troop_faction_relation", -5),
            (assign, ":comment", "str_comment_you_robbed_my_village_enemy"),
         (else_try),
            (gt, "$g_talk_troop_relation", 5),
            (this_or_next|eq, ":reputation", lrep_quarrelsome),
                (eq, ":reputation", lrep_debauched),
            (assign, ":comment", "str_comment_you_robbed_my_village_friendly_spiteful"),
         (else_try),
            (gt, "$g_talk_troop_relation", 5),
            (assign, ":comment", "str_comment_you_robbed_my_village_friendly"),
         (try_end),
       (try_end),

     (else_try),
       (eq, ":entry_type", logent_caravan_accosted),
       (eq, ":actor", "trp_player"),
       (eq, ":faction_object", "$g_talk_troop_faction"),
	   (eq, ":center_object", -1),
	   (eq, ":troop_object", -1),
	   

	   
       (faction_slot_eq, "$g_talk_troop_faction", slot_faction_leader, "$g_talk_troop"),
       (assign, ":relevance", 30),
       (assign, ":suggested_relation_change", -1),
       (assign, ":comment", "str_comment_you_accosted_my_caravan_default"),
       (try_begin),
            (lt, "$g_talk_troop_faction_relation", -5),
            (assign, ":comment", "str_comment_you_accosted_my_caravan_enemy"),
       (try_end),

     (else_try),
       (eq, ":entry_type", logent_helped_peasants),
       (eq, ":actor", "trp_player"),
       (try_begin),
         (eq, ":center_object_lord", "$g_talk_troop"),
         (assign, ":relevance", 40),
         (assign, ":suggested_relation_change", 0),
         (try_begin),
            (this_or_next|eq, ":reputation", lrep_goodnatured),
                (eq, ":reputation", lrep_upstanding),
            (assign, ":comment", "str_comment_you_helped_villagers_benevolent"),
            (assign, ":suggested_relation_change", 1),
         (else_try),
            (gt, "$g_talk_troop_relation", 5),
            (this_or_next|eq, ":reputation", lrep_quarrelsome),
                (eq, ":reputation", lrep_debauched),
            (assign, ":comment", "str_comment_you_helped_villagers_friendly_cruel"),
            (assign, ":suggested_relation_change", -1),
         (else_try),
            (lt, "$g_talk_troop_relation", -5),
            (this_or_next|eq, ":reputation", lrep_quarrelsome),
                (eq, ":reputation", lrep_debauched),
            (assign, ":comment", "str_comment_you_helped_villagers_unfriendly_spiteful"),
            (assign, ":suggested_relation_change", -1),
         (else_try),
            (gt, "$g_talk_troop_relation", 5),
            (assign, ":comment", "str_comment_you_helped_villagers_friendly"),
         (else_try),
            (this_or_next|eq, ":reputation", lrep_selfrighteous),
                (eq, ":reputation", lrep_debauched),
            (assign, ":comment", "str_comment_you_helped_villagers_cruel"),
            (assign, ":suggested_relation_change", -1),
         (else_try),
             (assign, ":comment", "str_comment_you_helped_villagers_default"),
         (try_end),
       (try_end),

###Combat events
     (else_try),
       (eq, ":entry_type", logent_castle_captured_by_player),
       
       (try_begin),
         (eq, ":center_object_lord", "$g_talk_troop"),
		 (store_faction_of_party, ":current_center_faction", ":center_object"),
		 (eq, ":current_center_faction", "$players_kingdom"),
		 (neq, "$g_talk_troop_faction", "$players_kingdom"),
		 
         (this_or_next|eq, ":reputation", lrep_quarrelsome),
			(eq, ":reputation", lrep_debauched),
		 
         (assign, ":comment", "str_comment_you_captured_my_castle_enemy_spiteful"),
         (assign, ":relevance", 200),
       (else_try),
         (eq, ":center_object_lord", "$g_talk_troop"),
		 (store_faction_of_party, ":current_center_faction", ":center_object"),
		 (eq, ":current_center_faction", "$players_kingdom"),
		 (neq, "$g_talk_troop_faction", "$players_kingdom"),
		 
         (this_or_next|eq, ":reputation", lrep_martial),
			(eq, ":reputation", lrep_goodnatured),
			
         (assign, ":comment", "str_comment_you_captured_my_castle_enemy_chivalrous"),
         (assign, ":relevance", 200),
       (else_try),
         (eq, ":center_object_lord", "$g_talk_troop"),
		 (store_faction_of_party, ":current_center_faction", ":center_object"),
		 (eq, ":current_center_faction", "$players_kingdom"),
		 (neq, "$g_talk_troop_faction", "$players_kingdom"),
		 
         (assign, ":comment", "str_comment_you_captured_my_castle_enemy"),
         (assign, ":relevance", 200),
       (else_try),
         (eq, "$players_kingdom", "$g_talk_troop_faction"),
         (lt, ":players_kingdom_relation", 0),
         (this_or_next|eq, ":reputation", lrep_quarrelsome),
         (eq, ":reputation", lrep_debauched),
         (assign, ":comment", "str_comment_you_captured_a_castle_allied_spiteful"),
         (assign, ":relevance", 75),
       (else_try),
         (eq, "$players_kingdom", "$g_talk_troop_faction"),
         (lt, ":players_kingdom_relation", 0),
         (gt, "$g_talk_troop_relation", 5),
         (assign, ":comment", "str_comment_you_captured_a_castle_allied_friendly"),
         (assign, ":relevance", 75),
       (else_try),
         (eq, "$players_kingdom", "$g_talk_troop_faction"),
         (lt, ":players_kingdom_relation", 0),
         (lt, "$g_talk_troop_relation", -5),
         (this_or_next|eq, ":reputation", lrep_quarrelsome),
         (eq, ":reputation", lrep_debauched),
         (assign, ":comment", "str_comment_you_captured_a_castle_allied_unfriendly_spiteful"),
         (assign, ":relevance", 75),
       (else_try),
         (eq, "$players_kingdom", "$g_talk_troop_faction"),
         (lt, ":players_kingdom_relation", 0),
         (lt, "$g_talk_troop_relation", -5),
         (assign, ":comment", "str_comment_you_captured_a_castle_allied_unfriendly"),
         (assign, ":relevance", 75),
       (else_try),
         (eq, "$players_kingdom", "$g_talk_troop_faction"),
         (lt, ":players_kingdom_relation", 0),
         (assign, ":comment", "str_comment_you_captured_a_castle_allied"),
         (assign, ":relevance", 75),
       (try_end),
       
     (else_try),
       (eq, ":entry_type", logent_player_claims_throne_1),
       (eq, "$players_kingdom", "$g_talk_troop_faction"),
	   (faction_slot_eq, "$g_talk_troop_faction", slot_faction_leader, "$g_talk_troop"),
       (assign, ":comment", "str_comment_you_claimed_the_throne_1_player_liege"),
       (assign, ":relevance", 500),
       (lt, "$g_talk_troop_relation", -10),
	   
     (else_try),
       (eq, ":entry_type", logent_player_claims_throne_2),
       (eq, "$players_kingdom", "$g_talk_troop_faction"),
	   (faction_slot_eq, "$g_talk_troop_faction", slot_faction_leader, "$g_talk_troop"),
       (assign, ":comment", "str_comment_you_claimed_the_throne_2_player_liege"),
       (assign, ":relevance", 500),
       (lt, "$g_talk_troop_relation", -10),

     (else_try), #player appointed a commoner
       (eq, ":entry_type", logent_liege_grants_fief_to_vassal),
	   (eq, ":actor", "trp_player"),
	   (troop_slot_ge, ":troop_object", slot_lord_reputation_type, lrep_roguish),
       (try_begin),
           (this_or_next|eq, ":reputation", lrep_quarrelsome),
               (eq, ":reputation", lrep_debauched),        
           (assign, ":comment", "str_comment_you_enfiefed_a_commoner_nasty"),
           (assign, ":relevance", 100),
		   (assign, ":suggested_relation_change", -3),

       (else_try),
		   (eq, ":reputation", lrep_upstanding),
           (assign, ":comment", "str_comment_you_enfiefed_a_commoner_hesitant"),
           (assign, ":relevance", 100),
		   (assign, ":suggested_relation_change", -2),
		   
       (else_try),
           (this_or_next|eq, ":reputation", lrep_selfrighteous),
			   (eq, ":reputation", lrep_martial),
           (assign, ":comment", "str_comment_you_enfiefed_a_commoner_derisive"),
           (assign, ":relevance", 100),
		   (assign, ":suggested_relation_change", -4),
		   
       (try_end),
   	   	   
#Post 0907 changes begin
     (else_try),
       (this_or_next|eq, ":entry_type", logent_lord_defeated_by_player),
            (eq, ":entry_type", logent_lord_helped_by_player),
       (troop_slot_eq, "$g_talk_troop", slot_troop_present_at_event, ":log_entry_no"),
       (try_begin),
           (lt, "$g_talk_troop_relation", -5),
           (this_or_next|eq, ":reputation", lrep_quarrelsome),
               (eq, ":reputation", lrep_debauched),        
           (assign, ":comment", "str_comment_we_defeated_a_lord_unfriendly_spiteful"),
           (assign, ":relevance", 150),
       (else_try),
           (lt, "$g_talk_troop_relation", -5),
           (assign, ":comment", "str_comment_we_defeated_a_lord_unfriendly"),
           (assign, ":relevance", 150),
       (else_try),
           (this_or_next|eq, ":reputation", lrep_selfrighteous),
               (eq, ":reputation", lrep_debauched),        
           (assign, ":comment", "str_comment_we_defeated_a_lord_cruel"),
           (assign, ":relevance", 150),
       (else_try),
           (eq, ":reputation", lrep_quarrelsome),        
           (assign, ":comment", "str_comment_we_defeated_a_lord_cruel"),
           (assign, ":relevance", 150),
       (else_try),
           (eq, ":reputation", lrep_upstanding),
           (assign, ":comment", "str_comment_we_defeated_a_lord_upstanding"),
           (assign, ":relevance", 150),
       (else_try),
           (assign, ":comment", "str_comment_we_defeated_a_lord_default"),
           (assign, ":relevance", 150),
       (try_end),

     (else_try),
       (this_or_next|eq, ":entry_type", logent_castle_captured_by_player),
       (eq, ":entry_type", logent_player_participated_in_siege),       
    
       (troop_slot_eq, "$g_talk_troop", slot_troop_present_at_event, ":log_entry_no"),
       
       (try_begin),
           (lt, "$g_talk_troop_relation", -5),
           (this_or_next|eq, ":reputation", lrep_quarrelsome),
           (eq, ":reputation", lrep_debauched),        
           (assign, ":comment", "str_comment_we_fought_in_siege_unfriendly_spiteful"),
           (assign, ":relevance", 150),
       (else_try),
           (lt, "$g_talk_troop_relation", -5),
           (assign, ":comment", "str_comment_we_fought_in_siege_unfriendly"),
           (assign, ":relevance", 150),
       (else_try),
           (this_or_next|eq, ":reputation", lrep_selfrighteous),
           (eq, ":reputation", lrep_debauched),        
           (assign, ":comment", "str_comment_we_fought_in_siege_cruel"),
           (assign, ":relevance", 150),
		   (assign, ":suggested_relation_change", 1),		   
       (else_try),
           (eq, ":reputation", lrep_quarrelsome),        
           (assign, ":comment", "str_comment_we_fought_in_siege_quarrelsome"),
           (assign, ":relevance", 150),
		   (assign, ":suggested_relation_change", 1),		   
       (else_try),
           (eq, ":reputation", lrep_upstanding),
           (assign, ":comment", "str_comment_we_fought_in_siege_upstanding"),
           (assign, ":relevance", 150),
		   (assign, ":suggested_relation_change", 1),		   
       (else_try),
           (eq, ":reputation", lrep_martial),
           (assign, ":comment", "str_comment_we_fought_in_siege_default"),
           (assign, ":relevance", 150),
		   (assign, ":suggested_relation_change", 2),
       (else_try),
           (faction_slot_eq, "$players_kingdom", slot_faction_leader, "$g_talk_troop"),
           (assign, ":comment", "str_comment_we_fought_in_siege_default"),
           (assign, ":relevance", 150),
		   (assign, ":suggested_relation_change", 1),
		(else_try),
           (assign, ":comment", "str_comment_we_fought_in_siege_default"),
           (assign, ":relevance", 150),
		   (assign, ":suggested_relation_change", 1),
       (try_end),
       
     (else_try),     
       (eq, ":entry_type", logent_castle_given_to_lord_by_player),
            
       (try_begin),
         (eq, ":troop_object", "$g_talk_troop"),         
         (this_or_next|eq, ":reputation", lrep_quarrelsome),
         (eq, ":reputation", lrep_debauched),         
         (assign, ":comment", "str_comment_you_give_castle_in_my_control"),
         (assign, ":relevance", 200),
       (else_try),
         (eq, ":troop_object", "$g_talk_troop"),         
         (this_or_next|eq, ":reputation", lrep_martial),
         (eq, ":reputation", lrep_goodnatured),         
         (assign, ":comment", "str_comment_you_give_castle_in_my_control"),
         (assign, ":relevance", 200),
       (else_try),
         (eq, ":troop_object", "$g_talk_troop"),
         (assign, ":comment", "str_comment_you_give_castle_in_my_control"),
         (assign, ":relevance", 200),
       (try_end),

     (else_try),
       (eq, ":entry_type", logent_player_participated_in_major_battle),
       (troop_slot_eq, "$g_talk_troop", slot_troop_present_at_event, ":log_entry_no"),
       (try_begin),
           (lt, "$g_talk_troop_relation", -5),
           (this_or_next|eq, ":reputation", lrep_quarrelsome),
               (eq, ":reputation", lrep_debauched),        
           (assign, ":comment", "str_comment_we_fought_in_major_battle_unfriendly_spiteful"),
           (assign, ":relevance", 150),
       (else_try),
           (lt, "$g_talk_troop_relation", -5),
           (assign, ":comment", "str_comment_we_fought_in_major_battle_unfriendly"),
           (assign, ":relevance", 150),
       (else_try),
           (this_or_next|eq, ":reputation", lrep_selfrighteous),
               (eq, ":reputation", lrep_debauched),        
           (assign, ":comment", "str_comment_we_fought_in_major_battle_cruel"),
           (assign, ":relevance", 150),
		   (assign, ":suggested_relation_change", 1),		   
       (else_try),
           (eq, ":reputation", lrep_quarrelsome),        
           (assign, ":comment", "str_comment_we_fought_in_major_battle_cruel"),
           (assign, ":relevance", 150),
		   (assign, ":suggested_relation_change", 1),		   
       (else_try),
           (eq, ":reputation", lrep_upstanding),
           (assign, ":comment", "str_comment_we_fought_in_major_battle_upstanding"),
           (assign, ":relevance", 150),
		   (assign, ":suggested_relation_change", 1),		   
       (else_try),
           (faction_slot_eq, "$players_kingdom", slot_faction_leader, "$g_talk_troop"),
           (assign, ":comment", "str_comment_we_fought_in_major_battle_default"),
           (assign, ":relevance", 150),
		   (assign, ":suggested_relation_change", 1),
       (else_try),
           (eq, ":reputation", lrep_martial),
           (assign, ":comment", "str_comment_we_fought_in_major_battle_default"),
           (assign, ":relevance", 150),
		   (assign, ":suggested_relation_change", 2),
	   (else_try),
           (assign, ":comment", "str_comment_we_fought_in_major_battle_default"),
           (assign, ":relevance", 150),
		   (assign, ":suggested_relation_change", 1),		   
       (try_end),

     (else_try),
       (eq, ":entry_type", logent_player_suggestion_succeeded),
       (try_begin),
         (eq, ":troop_object", "$g_talk_troop"),
         (assign, ":comment", "str_comment_player_suggestion_succeeded"),
         (assign, ":relevance", 200),
		 (assign, ":suggested_relation_change", 3),

	   (try_end),
     (else_try),
       (eq, ":entry_type", logent_player_suggestion_failed),
       (try_begin),
         (eq, ":troop_object", "$g_talk_troop"),
         (assign, ":comment", "str_comment_player_suggestion_failed"),
         (assign, ":relevance", 200),
		 (assign, ":suggested_relation_change", -5),

	   (try_end),
	   
#Post 0907 changes end

     (else_try),
       (eq, ":entry_type", logent_lord_defeated_by_player),
       (try_begin),
         (eq, ":troop_object", "$g_talk_troop"),
         (this_or_next|eq, ":reputation", lrep_martial),
             (eq, ":reputation", lrep_goodnatured),
         (assign, ":comment", "str_comment_you_defeated_me_enemy_chivalrous"),
         (assign, ":relevance", 200),
       (else_try),
         (eq, ":troop_object", "$g_talk_troop"),
         (this_or_next|eq, ":reputation", lrep_debauched),
             (eq, ":reputation", lrep_quarrelsome),
         (assign, ":comment", "str_comment_you_defeated_me_enemy_spiteful"),
         (assign, ":relevance", 200),
       (else_try),
         (eq, ":troop_object", "$g_talk_troop"),
         (assign, ":comment", "str_comment_you_defeated_me_enemy"),
         (assign, ":relevance", 200),
       (else_try),
         (eq, ":troop_object_faction", "$g_talk_troop_faction"),
         (this_or_next|eq, ":reputation", lrep_upstanding),
             (eq, ":reputation", lrep_cunning),
         (assign, ":comment", "str_comment_you_defeated_my_friend_enemy_pragmatic"),
         (assign, ":relevance", 85),
       (else_try),
         (eq, ":troop_object_faction", "$g_talk_troop_faction"),
         (this_or_next|eq, ":reputation", lrep_martial),
             (eq, ":reputation", lrep_goodnatured),
         (assign, ":comment", "str_comment_you_defeated_my_friend_enemy_chivalrous"),
         (assign, ":relevance", 85),
       (else_try),
         (eq, ":troop_object_faction", "$g_talk_troop_faction"),
         (this_or_next|eq, ":reputation", lrep_quarrelsome),
             (eq, ":reputation", lrep_debauched),
         (assign, ":comment", "str_comment_you_defeated_my_friend_enemy_spiteful"),
         (assign, ":relevance", 85),
       (else_try),
         (eq, ":troop_object_faction", "$g_talk_troop_faction"),
         (assign, ":comment", "str_comment_you_defeated_my_friend_enemy"),
         (assign, ":relevance", 85),
       (else_try),
         (eq, "$players_kingdom", "$g_talk_troop_faction"),
         (lt, ":players_kingdom_relation", 0),
         (faction_slot_eq, "$players_kingdom", slot_faction_leader, "$g_talk_troop"),
         (assign, ":comment", "str_comment_you_defeated_a_lord_allied_liege"),
         (assign, ":relevance", 150),
		 (assign, ":suggested_relation_change", 1),
		 
       (else_try),
         (eq, "$players_kingdom", "$g_talk_troop_faction"),
         (lt, ":players_kingdom_relation", 0),
         (lt, "$g_talk_troop_relation", -5),
         (this_or_next|eq, ":reputation", lrep_quarrelsome),
             (eq, ":reputation", lrep_debauched),
         (assign, ":comment", "str_comment_you_defeated_a_lord_allied_unfriendly_spiteful"),
         (assign, ":relevance", 65),
       (else_try),
         (eq, "$players_kingdom", "$g_talk_troop_faction"),
         (lt, ":players_kingdom_relation", 0),
         (this_or_next|eq, ":reputation", lrep_quarrelsome),
             (eq, ":reputation", lrep_debauched),
         (assign, ":comment", "str_comment_you_defeated_a_lord_allied_spiteful"),
         (assign, ":relevance", 65),
       (else_try),
         (eq, "$players_kingdom", "$g_talk_troop_faction"),
         (lt, ":players_kingdom_relation", 0),
         (lt, "$g_talk_troop_relation", -5),
         (this_or_next|eq, ":reputation", lrep_upstanding),
             (eq, ":reputation", lrep_martial),
         (assign, ":comment", "str_comment_you_defeated_a_lord_allied_unfriendly_chivalrous"),
         (assign, ":relevance", 65),
       (else_try),
         (eq, "$players_kingdom", "$g_talk_troop_faction"),
         (lt, ":players_kingdom_relation", 0),
         (assign, ":comment", "str_comment_you_defeated_a_lord_allied"),
         (assign, ":relevance", 65),
       (try_end),

     (else_try),
       (eq, ":entry_type", logent_lord_defeated_by_player),
       (try_begin),
         (eq, ":troop_object", "$g_talk_troop"),
         (this_or_next|eq, ":reputation", lrep_martial),
             (eq, ":reputation", lrep_goodnatured),
         (assign, ":comment", "str_comment_you_defeated_me_enemy_chivalrous"),
         (assign, ":relevance", 200),
       (else_try),
         (eq, ":troop_object", "$g_talk_troop"),
         (this_or_next|eq, ":reputation", lrep_debauched),
             (eq, ":reputation", lrep_quarrelsome),
         (assign, ":comment", "str_comment_you_defeated_me_enemy_spiteful"),
         (assign, ":relevance", 200),
       (else_try),
         (eq, ":troop_object", "$g_talk_troop"),
         (assign, ":comment", "str_comment_you_defeated_me_enemy"),
         (assign, ":relevance", 200),
       (else_try),
         (eq, ":troop_object_faction", "$g_talk_troop_faction"),
         (this_or_next|eq, ":reputation", lrep_upstanding),
             (eq, ":reputation", lrep_cunning),
         (assign, ":comment", "str_comment_you_defeated_my_friend_enemy_pragmatic"),
         (assign, ":relevance", 85),
       (else_try),
         (eq, ":troop_object_faction", "$g_talk_troop_faction"),
         (this_or_next|eq, ":reputation", lrep_martial),
             (eq, ":reputation", lrep_goodnatured),
         (assign, ":comment", "str_comment_you_defeated_my_friend_enemy_chivalrous"),
         (assign, ":relevance", 85),
       (else_try),
         (eq, ":troop_object_faction", "$g_talk_troop_faction"),
         (this_or_next|eq, ":reputation", lrep_quarrelsome),
             (eq, ":reputation", lrep_debauched),
         (assign, ":comment", "str_comment_you_defeated_my_friend_enemy_spiteful"),
         (assign, ":relevance", 85),
       (else_try),
         (eq, ":troop_object_faction", "$g_talk_troop_faction"),
         (assign, ":comment", "str_comment_you_defeated_my_friend_enemy"),
         (assign, ":relevance", 85),
       (else_try),
         (eq, "$players_kingdom", "$g_talk_troop_faction"),
         (lt, ":players_kingdom_relation", 0),
         (faction_slot_eq, "$players_kingdom", slot_faction_leader, "$g_talk_troop"),
         (assign, ":comment", "str_comment_you_defeated_a_lord_allied_liege"),
         (assign, ":relevance", 70),
       (else_try),
         (eq, "$players_kingdom", "$g_talk_troop_faction"),
         (lt, ":players_kingdom_relation", 0),
         (lt, "$g_talk_troop_relation", -5),
         (this_or_next|eq, ":reputation", lrep_quarrelsome),
             (eq, ":reputation", lrep_debauched),
         (assign, ":comment", "str_comment_you_defeated_a_lord_allied_unfriendly_spiteful"),
         (assign, ":relevance", 65),
       (else_try),
         (eq, "$players_kingdom", "$g_talk_troop_faction"),
         (lt, ":players_kingdom_relation", 0),
         (this_or_next|eq, ":reputation", lrep_quarrelsome),
             (eq, ":reputation", lrep_debauched),
         (assign, ":comment", "str_comment_you_defeated_a_lord_allied_spiteful"),
         (assign, ":relevance", 65),
       (else_try),
         (eq, "$players_kingdom", "$g_talk_troop_faction"),
         (lt, ":players_kingdom_relation", 0),
         (lt, "$g_talk_troop_relation", -5),
         (this_or_next|eq, ":reputation", lrep_upstanding),
             (eq, ":reputation", lrep_martial),
         (assign, ":comment", "str_comment_you_defeated_a_lord_allied_unfriendly_chivalrous"),
         (assign, ":relevance", 65),
       (else_try),
         (eq, "$players_kingdom", "$g_talk_troop_faction"),
         (lt, ":players_kingdom_relation", 0),
         (assign, ":comment", "str_comment_you_defeated_a_lord_allied"),
         (assign, ":relevance", 65),
       (try_end),

#Post 0907 changes begin
     (else_try),
       (eq, ":entry_type", logent_lord_helped_by_player),
       (neq, ":troop_object", "$g_talk_troop"),
       (eq, ":troop_object_faction", "$g_talk_troop_faction"),
       (try_begin),
         (lt, "$g_talk_troop_relation", -5),
         (this_or_next|eq, ":reputation", lrep_upstanding),
             (eq, ":reputation", lrep_martial),
         (assign, ":comment", "str_comment_you_helped_my_ally_unfriendly_chivalrous"),
         (assign, ":relevance", 65),
         (assign, ":suggested_relation_change", 2),
       (else_try),
         (lt, "$g_talk_troop_relation", -5),
         (assign, ":comment", "str_comment_you_helped_my_ally_unfriendly"),
         (assign, ":relevance", 0),
       (else_try),
         (eq, ":reputation", lrep_none),
         (assign, ":comment", "str_comment_you_helped_my_ally_liege"),
         (assign, ":relevance", 65),
         (assign, ":suggested_relation_change", 3),
       (else_try),
         (lt, "$g_talk_troop_relation", -5),
         (this_or_next|eq, ":reputation", lrep_quarrelsome),
             (eq, ":reputation", lrep_debauched),
         (assign, ":comment", "str_comment_you_helped_my_ally_unfriendly_spiteful"),
         (assign, ":relevance", 65),
       (else_try),
         (this_or_next|eq, ":reputation", lrep_quarrelsome),
             (eq, ":reputation", lrep_debauched),
         (assign, ":comment", "str_comment_you_helped_my_ally_spiteful"),
         (assign, ":relevance", 65),
       (else_try),
         (this_or_next|eq, ":reputation", lrep_martial),
             (eq, ":reputation", lrep_upstanding),
         (assign, ":comment", "str_comment_you_helped_my_ally_chivalrous"),
         (assign, ":relevance", 65),
         (assign, ":suggested_relation_change", 2),
       (else_try),
         (eq, ":troop_object", "$g_talk_troop"),
         (assign, ":comment", "str_comment_you_helped_my_ally_default"),
       (try_end),

#Post 0907 changes begin
     (else_try),
       (eq, ":entry_type", logent_player_defeated_by_lord),
       (troop_slot_eq, "$g_talk_troop", slot_troop_present_at_event, ":log_entry_no"),
       (try_begin),
           (lt, "$g_talk_troop_relation", -5),
           (this_or_next|eq, ":reputation", lrep_quarrelsome),
               (eq, ":reputation", lrep_debauched),        
           (assign, ":comment", "str_comment_we_were_defeated_unfriendly_spiteful"),
           (assign, ":relevance", 150),
       (else_try),
           (lt, "$g_talk_troop_relation", -5),
           (assign, ":comment", "str_comment_we_were_defeated_unfriendly"),
           (assign, ":relevance", 150),
       (else_try),
           (this_or_next|eq, ":reputation", lrep_selfrighteous),
               (eq, ":reputation", lrep_debauched),        
           (assign, ":comment", "str_comment_we_were_defeated_cruel"),
           (assign, ":relevance", 150),
       (else_try),
           (assign, ":comment", "str_comment_we_were_defeated_default"),
           (assign, ":relevance", 150),
       (try_end),

     (else_try),
       (eq, ":entry_type", logent_player_defeated_by_lord),
       (try_begin),
         (eq, ":troop_object", "$g_talk_troop"),
         (this_or_next|eq, ":reputation", lrep_quarrelsome),
                (eq, ":reputation", lrep_debauched),
         (assign, ":comment", "str_comment_I_defeated_you_enemy_spiteful"),
         (assign, ":relevance", 200),
       (else_try),
         (eq, ":troop_object", "$g_talk_troop"),
         (eq, ":reputation", lrep_martial),
         (assign, ":comment", "str_comment_I_defeated_you_enemy_chivalrous"),
         (assign, ":relevance", 200),
       (else_try),
         (eq, ":troop_object", "$g_talk_troop"),
         (this_or_next|eq, ":reputation", lrep_goodnatured),
                (eq, ":reputation", lrep_upstanding),
         (assign, ":comment", "str_comment_I_defeated_you_enemy_benevolent"),
         (assign, ":relevance", 200),
       (else_try),
         (eq, ":troop_object", "$g_talk_troop"),
         (this_or_next|eq, ":reputation", lrep_selfrighteous),
             (eq, ":reputation", lrep_cunning),
         (assign, ":comment", "str_comment_I_defeated_you_enemy_coldblooded"),
         (assign, ":relevance", 200),
       (else_try),
         (eq, ":troop_object", "$g_talk_troop"),
         (assign, ":comment", "str_comment_I_defeated_you_enemy"),
         (assign, ":relevance", 200),
       (else_try),
         (eq, ":troop_object", "$g_talk_troop"),
         (assign, ":comment", "str_comment_I_defeated_you_enemy"),
         (assign, ":relevance", 200),
       (else_try),
         (eq, "$players_kingdom", "$g_talk_troop_faction"),
         (this_or_next|eq, ":reputation", lrep_quarrelsome),
                (eq, ":reputation", lrep_debauched),
         (gt, "$g_talk_troop_relation", 5),
         (assign, ":comment", "str_comment_you_were_defeated_allied_friendly_spiteful"),
         (assign, ":relevance", 80),
       (else_try),
         (eq, "$players_kingdom", "$g_talk_troop_faction"),
         (this_or_next|eq, ":reputation", lrep_selfrighteous),
                (eq, ":reputation", lrep_debauched),
         (lt, "$g_talk_troop_relation", -5),
         (assign, ":comment", "str_comment_you_were_defeated_allied_unfriendly_cruel"),
         (assign, ":relevance", 80),
       (else_try),
         (eq, "$players_kingdom", "$g_talk_troop_faction"),
         (this_or_next|eq, ":reputation", lrep_quarrelsome),
                (eq, ":reputation", lrep_debauched),
         (le, "$g_talk_troop_relation", 5),
         (assign, ":comment", "str_comment_you_were_defeated_allied_spiteful"),
         (assign, ":relevance", 80),
       (else_try),
         (eq, "$players_kingdom", "$g_talk_troop_faction"),
         (eq, ":reputation", lrep_selfrighteous),
         (assign, ":comment", "str_comment_you_were_defeated_allied_pitiless"),
         (assign, ":relevance", 65),
       (else_try),
         (eq, "$players_kingdom", "$g_talk_troop_faction"),
         (eq, ":reputation", lrep_upstanding),
         (lt, "$g_talk_troop_relation", -15),
         (assign, ":comment", "str_comment_you_were_defeated_allied_unfriendly_upstanding"),
         (assign, ":relevance", 65),
       (else_try),
         (eq, "$players_kingdom", "$g_talk_troop_faction"),
         (lt, "$g_talk_troop_relation", -10),
         (assign, ":comment", "str_comment_you_were_defeated_allied_unfriendly"),
         (assign, ":relevance", 65),
       (else_try),
         (eq, "$players_kingdom", "$g_talk_troop_faction"),
         (assign, ":comment", "str_comment_you_were_defeated_allied"),
         (assign, ":relevance", 65),
       (try_end),
#Post 0907 changes end

#Post 0907 changes begin
     (else_try),
       (eq, ":entry_type", logent_player_retreated_from_lord),
       (troop_slot_eq, "$g_talk_troop", slot_troop_present_at_event, ":log_entry_no"),
       (try_begin),
           (lt, "$g_talk_troop_relation", -5),
           (this_or_next|eq, ":reputation", lrep_quarrelsome),
               (eq, ":reputation", lrep_debauched),        
           (assign, ":comment", "str_comment_you_abandoned_us_unfriendly_spiteful"),
           (assign, ":relevance", 150),
           (assign, ":suggested_relation_change", -5),
       (else_try),
           (lt, "$g_talk_troop_relation", -5),
           (eq, ":reputation", lrep_selfrighteous),        
           (assign, ":comment", "str_comment_you_abandoned_us_unfriendly_pitiless"),
           (assign, ":relevance", 150),
           (assign, ":suggested_relation_change", -5),
       (else_try),
           (lt, "$g_talk_troop_relation", -5),
           (this_or_next|eq, ":reputation", lrep_quarrelsome),
               (eq, ":reputation", lrep_debauched),        
           (assign, ":comment", "str_comment_you_abandoned_us_spiteful"),
           (assign, ":suggested_relation_change", -5),
       (else_try),
           (eq, ":reputation", lrep_martial),
           (assign, ":comment", "str_comment_you_abandoned_us_chivalrous"),
           (assign, ":relevance", 150),
           (assign, ":suggested_relation_change", -2),
       (else_try),
           (this_or_next|eq, ":reputation", lrep_upstanding),
               (eq, ":reputation", lrep_goodnatured),        
           (assign, ":comment", "str_comment_you_abandoned_us_benefitofdoubt"),
           (assign, ":relevance", 150),
           (assign, ":suggested_relation_change", -1),
       (else_try),
           (assign, ":comment", "str_comment_you_abandoned_us_default"),
           (assign, ":relevance", 150),
           (assign, ":suggested_relation_change", -2),
       (try_end),


#Post 0907 changes end

     (else_try),
       (this_or_next|eq, ":entry_type", logent_player_retreated_from_lord),
            (eq, ":entry_type", logent_player_retreated_from_lord_cowardly),
			
       (eq, ":troop_object", "$g_talk_troop"),
       (try_begin),
         (eq, "$cheat_mode", 1),
         (assign, reg7, ":entry_hours_elapsed"),
         (display_message, "@{!}Elapsed hours: {reg7}"),
       (try_end),
       (gt, ":entry_hours_elapsed", 2),
       (try_begin),
         (this_or_next|eq, ":reputation", lrep_selfrighteous),
                (eq, ":reputation", lrep_debauched),
         (assign, ":comment", "str_comment_you_ran_from_me_enemy_spiteful"),
         (assign, ":relevance", 25),
       (else_try),
         (eq, ":reputation", lrep_martial),
         (assign, ":comment", "str_comment_you_ran_from_me_enemy_chivalrous"),
         (assign, ":relevance", 25),
       (else_try),
         (this_or_next|eq, ":reputation", lrep_goodnatured),
                (eq, ":reputation", lrep_upstanding),
         (assign, ":comment", "str_comment_you_ran_from_me_enemy_benevolent"),
         (assign, ":relevance", 25),
       (else_try),
         (eq, ":reputation", lrep_cunning),
         (assign, ":comment", "str_comment_you_ran_from_me_enemy_coldblooded"),
         (assign, ":relevance", 25),
       (else_try),
         (assign, ":comment", "str_comment_you_ran_from_me_enemy"),
         (assign, ":relevance", 25),
       (try_end),

     (else_try),
       (eq, ":entry_type", logent_player_retreated_from_lord_cowardly),
       (try_begin),
         (eq, "$players_kingdom", "$g_talk_troop_faction"),
         (neq, ":troop_object", "$g_talk_troop"),
         (lt, "$g_talk_troop_relation", 5),
         (eq, ":reputation", lrep_martial),
         (assign, ":comment", "str_comment_you_ran_from_foe_allied_chivalrous"),
         (assign, ":relevance", 80),
         (assign, ":suggested_relation_change", -3),
       (else_try),
         (eq, "$players_kingdom", "$g_talk_troop_faction"),
         (neq, ":troop_object", "$g_talk_troop"),
         (eq, ":reputation", lrep_upstanding),
         (assign, ":comment", "str_comment_you_ran_from_foe_allied_upstanding"),
         (assign, ":relevance", 80),
         (assign, ":suggested_relation_change", -1),
       (else_try),
         (eq, "$players_kingdom", "$g_talk_troop_faction"),
         (neq, ":troop_object", "$g_talk_troop"),
         (lt, "$g_talk_troop_relation", 5),
         (this_or_next|eq, ":reputation", lrep_quarrelsome),
             (eq, ":reputation", lrep_debauched),
         (assign, ":comment", "str_comment_you_ran_from_foe_allied_spiteful"),
         (assign, ":relevance", 80),
       (try_end),

     (else_try),
       (eq, ":entry_type", logent_lord_defeated_but_let_go_by_player),
       (try_begin),
         (eq, ":troop_object", "$g_talk_troop"),
         (this_or_next|eq, ":reputation", lrep_quarrelsome),
             (eq, ":reputation", lrep_debauched),
         (assign, ":comment", "str_comment_you_let_me_go_spiteful"),
         (assign, ":relevance", 300),
         (assign, ":suggested_relation_change", -15),
       (else_try),
         (eq, ":troop_object", "$g_talk_troop"),
         (ge, "$g_talk_troop_faction_relation", 0),
         (assign, ":comment", "str_comment_you_let_me_go_default"),
         (assign, ":relevance", 300),
         (assign, ":suggested_relation_change", 2),
       (else_try),
         (eq, ":troop_object", "$g_talk_troop"),
         (lt, "$g_talk_troop_faction_relation", 0),
         (this_or_next|eq, ":reputation", lrep_martial),
             (eq, ":reputation", lrep_upstanding),
         (assign, ":suggested_relation_change", 5),
         (assign, ":relevance", 300),
         (assign, ":comment", "str_comment_you_let_me_go_enemy_chivalrous"),
       (else_try),
         (eq, ":troop_object", "$g_talk_troop"),
         (lt, "$g_talk_troop_faction_relation", 0),
         (this_or_next|eq, ":reputation", lrep_selfrighteous),
             (eq, ":reputation", lrep_cunning),
         (assign, ":relevance", 300),
         (assign, ":comment", "str_comment_you_let_me_go_enemy_coldblooded"),
       (else_try),
         (eq, ":troop_object", "$g_talk_troop"),
         (lt, "$g_talk_troop_faction_relation", 0),
         (assign, ":relevance", 300),
         (assign, ":comment", "str_comment_you_let_me_go_enemy"),
         (assign, ":suggested_relation_change", 1),
       (else_try),
         (eq, "$players_kingdom", "$g_talk_troop_faction"),
         (lt, ":players_kingdom_relation", 0),
         (neq, ":troop_object", "$g_talk_troop"),
         (this_or_next|eq, ":reputation", lrep_martial),
             (eq, ":reputation", lrep_goodnatured),
         (assign, ":comment", "str_comment_you_let_go_a_lord_allied_chivalrous"),
         (assign, ":relevance", 80),
       (else_try),
         (eq, "$players_kingdom", "$g_talk_troop_faction"),
         (lt, ":players_kingdom_relation", 0),
         (neq, ":troop_object", "$g_talk_troop"),
         (eq, ":reputation", lrep_upstanding),
         (assign, ":comment", "str_comment_you_let_go_a_lord_allied_upstanding"),
         (assign, ":relevance", 80),
       (else_try),
         (eq, "$players_kingdom", "$g_talk_troop_faction"),
         (lt, ":players_kingdom_relation", 0),
         (neq, ":troop_object", "$g_talk_troop"),
         (this_or_next|eq, ":reputation", lrep_cunning),
             (eq, ":reputation", lrep_selfrighteous),
         (assign, ":comment", "str_comment_you_let_go_a_lord_allied_coldblooded"),
         (assign, ":relevance", 80),
       (else_try),
         (eq, "$players_kingdom", "$g_talk_troop_faction"),
         (lt, ":players_kingdom_relation", 0),
         (neq, ":troop_object", "$g_talk_troop"),
         (lt, "$g_talk_troop_relation", -5),
         (this_or_next|eq, ":reputation", lrep_quarrelsome),
             (eq, ":reputation", lrep_debauched),
         (assign, ":comment", "str_comment_you_let_go_a_lord_allied_unfriendly_spiteful"),
         (assign, ":relevance", 80),
       (else_try),
         (eq, "$players_kingdom", "$g_talk_troop_faction"),
         (lt, ":players_kingdom_relation", 0),
         (neq, ":troop_object", "$g_talk_troop"),
         (assign, ":comment", "str_comment_you_let_go_a_lord_allied"),
         (assign, ":relevance", 80),
       (try_end),

#Internal faction relations

     (else_try),
       (eq, ":entry_type", logent_pledged_allegiance),
       (eq, ":actor", "trp_player"),
       (try_begin),
         (eq, ":faction_object", "$g_talk_troop_faction"),
         (neq, ":troop_object", "$g_talk_troop"),
		 (eq, ":faction_object", "$players_kingdom"), #Ie, no switch of kingdoms
         (assign, ":relevance", 200),
         (try_begin),
            (lt, "$g_talk_troop_relation", -5),
            (eq, ":reputation", lrep_martial),
            (assign, ":comment", "str_comment_pledged_allegiance_allied_martial_unfriendly"),
         (else_try),
            (eq, ":reputation", lrep_martial),
            (assign, ":comment", "str_comment_pledged_allegiance_allied_martial"),
         (else_try),
            (lt, "$g_talk_troop_relation", -5),
            (eq, ":reputation", lrep_quarrelsome),
            (assign, ":comment", "str_comment_pledged_allegiance_allied_quarrelsome_unfriendly"),
         (else_try),
            (eq, ":reputation", lrep_quarrelsome),
            (assign, ":comment", "str_comment_pledged_allegiance_allied_quarrelsome"),
         (else_try),
            (lt, "$g_talk_troop_relation", -5),
            (eq, ":reputation", lrep_selfrighteous),
            (assign, ":comment", "str_comment_pledged_allegiance_allied_selfrighteous_unfriendly"),
         (else_try),
            (eq, ":reputation", lrep_selfrighteous),
            (assign, ":comment", "str_comment_pledged_allegiance_allied_selfrighteous"),
         (else_try),
            (lt, "$g_talk_troop_relation", -5),
            (eq, ":reputation", lrep_cunning),
            (assign, ":comment", "str_comment_pledged_allegiance_allied_cunning_unfriendly"),
         (else_try),
            (eq, ":reputation", lrep_cunning),
            (assign, ":comment", "str_comment_pledged_allegiance_allied_cunning"),
         (else_try),
            (lt, "$g_talk_troop_relation", -5),
            (eq, ":reputation", lrep_debauched),
            (assign, ":comment", "str_comment_pledged_allegiance_allied_debauched_unfriendly"),
         (else_try),
            (eq, ":reputation", lrep_debauched),
            (assign, ":comment", "str_comment_pledged_allegiance_allied_debauched"),
         (else_try),
            (lt, "$g_talk_troop_relation", -5),
            (eq, ":reputation", lrep_goodnatured),
            (assign, ":comment", "str_comment_pledged_allegiance_allied_goodnatured_unfriendly"),
         (else_try),
            (eq, ":reputation", lrep_goodnatured),
            (assign, ":comment", "str_comment_pledged_allegiance_allied_goodnatured"),
         (else_try),
            (lt, "$g_talk_troop_relation", -5),
            (eq, ":reputation", lrep_upstanding),
            (assign, ":comment", "str_comment_pledged_allegiance_allied_upstanding_unfriendly"),
         (else_try),
            (eq, ":reputation", lrep_upstanding),
            (assign, ":comment", "str_comment_pledged_allegiance_allied_upstanding"),
         (try_end),
       (try_end),


     (else_try),
       (eq, ":entry_type", logent_liege_grants_fief_to_vassal),
       (eq, ":troop_object", "trp_player"),
       (try_begin),
         (eq, ":faction_object", "$g_talk_troop_faction"),
         (neq, ":actor", "$g_talk_troop"),
         (eq, ":faction_object", "$players_kingdom"),
         (assign, ":relevance", 110),
         (try_begin),
            (gt, "$g_talk_troop_relation", 5),
            (this_or_next|eq, ":reputation", lrep_selfrighteous),
                (eq, ":reputation", lrep_debauched),
            (assign, ":comment", "str_comment_our_king_granted_you_a_fief_allied_friendly_cruel"),
         (else_try),
            (gt, "$g_talk_troop_relation", 5),
            (this_or_next|eq, ":reputation", lrep_quarrelsome),
                (eq, ":reputation", lrep_cunning),
            (assign, ":comment", "str_comment_our_king_granted_you_a_fief_allied_friendly_cynical"),
         (else_try),
            (gt, "$g_talk_troop_relation", 5),
            (assign, ":comment", "str_comment_our_king_granted_you_a_fief_allied_friendly"),
         (else_try),
            (is_between, "$g_talk_troop_relation", -5, 5),
            (this_or_next|eq, ":reputation", lrep_quarrelsome),
                (eq, ":reputation", lrep_debauched),
            (assign, ":comment", "str_comment_our_king_granted_you_a_fief_allied_spiteful"),
            (assign, ":suggested_relation_change", -2),
         (else_try),
            (lt, "$g_talk_troop_relation", -5),
            (eq, ":reputation", lrep_upstanding),
            (assign, ":comment", "str_comment_our_king_granted_you_a_fief_allied_unfriendly_upstanding"),
         (else_try),
            (lt, "$g_talk_troop_relation", -5),
            (this_or_next|eq, ":reputation", lrep_quarrelsome),
                (eq, ":reputation", lrep_debauched),
            (assign, ":comment", "str_comment_our_king_granted_you_a_fief_allied_unfriendly_spiteful"),
         (else_try),
            (assign, ":comment", "str_comment_our_king_granted_you_a_fief_allied"),
         (try_end),
       (try_end),

     (else_try),
       (eq, ":entry_type", logent_renounced_allegiance),
       (eq, ":actor", "trp_player"),
       (try_begin),
         (eq, ":faction_object", "$g_talk_troop_faction"),
         (neq, ":troop_object", "$g_talk_troop"),
         (try_begin),
           (ge, "$g_talk_troop_faction_relation", 0),
           (neq, "$g_talk_troop_faction", "$players_kingdom"),
           (assign, ":relevance", 180),
           (try_begin),
             (gt, "$g_talk_troop_relation", 5),
             (assign, ":comment", "str_comment_you_renounced_your_alliegance_friendly"),
           (else_try),
             (ge, "$g_talk_troop_relation", 0),
             (eq, ":reputation", lrep_goodnatured),
             (assign, ":comment", "str_comment_you_renounced_your_alliegance_friendly"),
		   (else_try),
		     (assign, ":comment", "str_comment_you_renounced_your_alliegance_default"),
           (try_end),
         (else_try),
           (lt, "$g_talk_troop_faction_relation", 0),
           (assign, ":relevance", 300),
           (try_begin),
              (ge, "$g_talk_troop_relation", 0),
              (this_or_next|eq, ":reputation", lrep_selfrighteous),
                  (eq, ":reputation", lrep_debauched),
              (assign, ":comment", "str_comment_you_renounced_your_alliegance_unfriendly_moralizing"),
           (else_try),
              (gt, "$g_talk_troop_relation", 5),
              (this_or_next|eq, ":reputation", lrep_goodnatured),
                (eq, ":reputation", lrep_upstanding),
              (assign, ":comment", "str_comment_you_renounced_your_alliegance_enemy_friendly"),
           (else_try),
              (gt, "$g_talk_troop_relation", 5),
              (assign, ":comment", "str_comment_you_renounced_your_alliegance_enemy"),
           (else_try),
              (is_between, "$g_talk_troop_relation", -5, 5),
              (this_or_next|eq, ":reputation", lrep_quarrelsome),
                  (eq, ":reputation", lrep_debauched),
              (assign, ":comment", "str_comment_you_renounced_your_alliegance_unfriendly_spiteful"),
              (assign, ":suggested_relation_change", -2),
           (else_try),
              (lt, "$g_talk_troop_relation", -5),
              (this_or_next|eq, ":reputation", lrep_quarrelsome),
              (this_or_next|eq, ":reputation", lrep_selfrighteous),
                (eq, ":reputation", lrep_debauched),
              (assign, ":comment", "str_comment_you_renounced_your_alliegance_unfriendly_spiteful"),
           (else_try),
              (assign, ":comment", "str_comment_you_renounced_your_alliegance_default"),
           (try_end),
         (try_end),
       (try_end),

     (else_try), 
       (eq, ":entry_type", logent_lady_marries_lord),
	   (eq, ":troop_object", "trp_player"),
	   (try_begin),
		  (this_or_next|eq, ":reputation", lrep_quarrelsome),
			(eq, ":reputation", lrep_debauched),
		  (lt, "$g_talk_troop_relation", -5),	
          (assign, ":relevance", 200),
		  (assign, ":comment", "str_comment_marriage_normal_nasty"),
	   (else_try),
		  (call_script, "script_troop_get_family_relation_to_troop", ":actor", "$g_talk_troop"),
		  (ge, reg0, 5),
		  (assign, ":comment", "str_comment_marriage_normal_family"),
          (assign, ":relevance", 300),
		  (assign, ":suggested_relation_change", reg0),
		  (val_div, ":suggested_relation_change", 3),
	   (else_try),
		  (store_faction_of_troop, ":bride_faction", ":actor"),
		  (eq, ":bride_faction", "$g_talk_troop_faction"),
		  (assign, ":comment", "str_comment_marriage_normal"),
          (assign, ":relevance", 100),
	   (try_end),
     (else_try), 
       (eq, ":entry_type", logent_lady_elopes_with_lord),
	   (eq, ":troop_object", "trp_player"),
	   (try_begin),
		  (call_script, "script_troop_get_family_relation_to_troop", ":actor", "$g_talk_troop"),
		  (ge, reg0, 5),
		  (assign, ":comment", "str_comment_marriage_elopement_family"),
          (assign, ":relevance", 300),
		  (store_sub, ":suggested_relation_change", 0, reg0),
		  (val_div, ":suggested_relation_change", 3),
	   (else_try),
		  (store_faction_of_troop, ":bride_faction", ":actor"),
		  (eq, ":bride_faction", "$g_talk_troop_faction"),
		  (faction_slot_eq, ":bride_faction", slot_faction_leader, "$g_talk_troop"),
		  (assign, ":comment", "str_comment_marriage_elopement_liege"),
          (assign, ":relevance", 300),
		  (assign, ":suggested_relation_change", -10),
	   (try_end),
     (else_try), #this is specific to quarrels with the player 
       (eq, ":entry_type", logent_lords_quarrel_over_woman),
 	   (eq, ":actor", "$g_talk_troop"),
 	   (eq, ":center_object", "trp_player"),

	   (neg|troop_slot_ge, ":troop_object", slot_troop_spouse, "trp_player"),
	   
	   (str_store_troop_name, s54, ":troop_object"),

	   (try_begin),
	       (this_or_next|eq, ":reputation", lrep_selfrighteous),
	       (this_or_next|eq, ":reputation", lrep_quarrelsome),
				(eq, ":reputation", lrep_debauched),
		   
	       (assign, ":comment", "str_comment_i_quarreled_with_you_over_woman_derisive"),
		   (assign, ":relevance", 200),
	       (assign, ":suggested_relation_change", -20),
	   (else_try),
	       (assign, ":comment", "str_comment_i_quarreled_with_you_over_woman_default"),
		   (assign, ":relevance", 200),
	       (assign, ":suggested_relation_change", -20),
	   (try_end),
	 
     (else_try), 
       (eq, ":entry_type", logent_border_incident_troop_breaks_truce),
 	   (eq, ":actor", "trp_player"),
 	   (faction_slot_eq, ":faction_object", slot_faction_leader, "$g_talk_troop"),
	   (eq, "$players_kingdom", ":faction_object"),
	   
	   (assign, ":suggested_relation_change", -10),
	   (assign, ":comment", "str_comment_you_broke_truce_as_my_vassal"),
	   (assign, ":relevance", 300),

     (else_try), 
       (eq, ":entry_type", logent_border_incident_troop_attacks_neutral),
 	   (eq, ":actor", "trp_player"),
 	   (faction_slot_eq, ":faction_object", slot_faction_leader, "$g_talk_troop"),
	   (eq, "$players_kingdom", ":faction_object"),

	   (assign, ":suggested_relation_change", -3),
	   (assign, ":comment", "str_comment_you_attacked_neutral_as_my_vassal"),
	   (assign, ":relevance", 200),

	 #THE FOLLOWING ARE ALL COMPLAINTS SPOKEN BY LORDS WITHIN CONVERATIONS, RATHER THAN COMMENTS WHEN THE PLAYER FIRST SPEAKS TO A LORD
	 (else_try), #these need to have the actor and object strings added because they are used outside of "script_get_relevant_comment_to_s42"
       (eq, ":entry_type", logent_ruler_intervenes_in_quarrel),
 	   (eq, ":center_object", "$g_talk_troop"), #actor is liege lord, center object is loser lord, troop object is winner lord
	   (str_store_troop_name, s50, ":actor"), 
	   (str_store_troop_name, s51, ":center_object"), #s50 is actor, s51 is center object, s54 is troop object
	   (str_store_troop_name, s54, ":troop_object"), #s50 is actor, s51 is center object, s54 is troop object
       (assign, ":comment", "str_comment_lord_intervened_against_me"),
	   (assign, ":relevance", -1),

	 (else_try),
       (eq, ":entry_type", logent_lord_protests_marshall_appointment),
 	   (eq, ":actor", "$g_talk_troop"),

	   (str_store_troop_name, s51, ":center_object"), #s51 is center object (marshall), s54 is troop object (liege lord), 
	   (str_store_troop_name, s54, ":troop_object"), 

       (assign, ":comment", "str_comment_i_protested_marshall_appointment"),
	   (assign, ":relevance", -1),
	   
	 (else_try),
       (eq, ":entry_type", logent_lord_blames_defeat),
 	   (eq, ":actor", "$g_talk_troop"),

	   (str_store_troop_name, s51, ":center_object"), #s51 is center object (marshall), s54 is troop object (liege lord), 
	   (str_store_troop_name, s54, ":troop_object"),  
	   (str_store_troop_name, s56, ":faction_object"), #faction object is unusual in this circumstance
	   
       (assign, ":comment", "str_comment_i_blamed_defeat"),
	   (assign, ":relevance", -1),

	 (else_try),
       (eq, ":entry_type", logent_troop_feels_cheated_by_troop_over_land),
 	   (eq, ":actor", "$g_talk_troop"),

           (str_store_party_name, s51, ":center_object"),  
	   (str_store_troop_name, s54, ":troop_object"),  
	   (str_store_troop_name, s56, ":faction_object"), #faction object is unusual in this circumstance
	   
       (assign, ":comment", "str_comment_i_was_entitled_to_fief"),
	   (assign, ":relevance", -1),
	   
	 (else_try),
       (eq, ":entry_type", logent_lords_quarrel_over_woman),
 	   (eq, ":actor", "$g_talk_troop"),

	   (str_store_troop_name, s51, ":center_object"), 
	   (str_store_troop_name, s54, ":troop_object"),  
	   
       (assign, ":comment", "str_comment_i_quarreled_with_troop_over_woman"),
	   (assign, ":relevance", -1),

	 (else_try),
       (eq, ":entry_type", logent_lords_quarrel_over_woman),
 	   (eq, ":center_object", "$g_talk_troop"),

	   (str_store_troop_name, s51, ":actor"), 
	   (str_store_troop_name, s54, ":troop_object"),  
	   
       (assign, ":comment", "str_comment_i_quarreled_with_troop_over_woman"),
	   (assign, ":relevance", -1),
	   
	 (else_try),	 
       (eq, ":entry_type", logent_player_stole_cattles_from_village),
       
       (eq, ":actor", "trp_player"),
       (try_begin),
         (eq, ":center_object_lord", "$g_talk_troop"),
         (assign, ":relevance", 200),
         (assign, ":suggested_relation_change", -1),
         (assign, ":comment", "str_comment_you_stole_cattles_from_my_village_default"),
         (try_begin),
            (lt, "$g_talk_troop_faction_relation", -3),
            (this_or_next|eq, ":reputation", lrep_goodnatured),
            (eq, ":reputation", lrep_upstanding),
            (assign, ":comment", "str_comment_you_stole_cattles_from_my_village_enemy_benevolent"),
         (else_try),
            (lt, "$g_talk_troop_faction_relation", -3),
            (this_or_next|eq, ":reputation", lrep_cunning),
                (eq, ":reputation", lrep_selfrighteous),
            (assign, ":comment", "str_comment_you_stole_cattles_from_my_village_enemy_coldblooded"),
         (else_try),
            (lt, "$g_talk_troop_faction_relation", -3),
            (this_or_next|eq, ":reputation", lrep_quarrelsome),
                (eq, ":reputation", lrep_debauched),
            (assign, ":comment", "str_comment_you_stole_cattles_from_my_village_enemy_spiteful"),
         (else_try),
            (lt, "$g_talk_troop_faction_relation", -3),
            (assign, ":comment", "str_comment_you_stole_cattles_from_my_village_enemy"),
         (else_try),
            (lt, "$g_talk_troop_relation", -3),
            (this_or_next|eq, ":reputation", lrep_quarrelsome),
                (eq, ":reputation", lrep_debauched),
            (assign, ":comment", "str_comment_you_stole_cattles_from_my_village_unfriendly_spiteful"),
         (else_try),
            (gt, "$g_talk_troop_relation", 6),
            (assign, ":comment", "str_comment_you_stole_cattles_from_my_village_friendly"),
         (try_end),
       (try_end),
             	   
     (try_end),

     (assign, reg0, ":comment"),
	 (assign, reg1, ":relevance"),
     (assign, reg2, ":suggested_relation_change"),
     (assign, reg3, ":rejoinder"),
	]),

  # script_get_relevant_comment_to_s42
  # Input: none
  # Output: reg0 = 1 if comment found, 0 otherwise; s61 will contain comment string if found
  ("get_relevant_comment_to_s42",
    [

	 (troop_get_slot, ":reputation", "$g_talk_troop", slot_lord_reputation_type),
     (try_begin),
	   (eq, "$cheat_mode", 1),
       (store_add, ":rep_string", ":reputation", "str_personality_archetypes"),
       (str_store_string, s15, ":rep_string"),
       (display_message, "@{!}Reputation type: {s15}"),
     (try_end),

	 
     (assign, ":highest_score_so_far", 50),
     (assign, ":best_comment_so_far", -1),
     (assign, ":rejoinder_to_best_comment_so_far", -1),
     (assign, ":comment_found", 0),
     (assign, ":best_log_entry", -1),
     (assign, ":comment_relation_change", 0),
     (store_current_hours, ":current_time"),

#prevents multiple comments in conversations in same hour

#     (troop_get_slot, ":talk_troop_last_comment_time", "$g_talk_troop", slot_troop_last_comment_time),
#"$num_log_entries should also be set to one, not zero. This is included in the initialize npcs script, although could be moved to game_start
     (troop_get_slot, ":talk_troop_last_comment_slot", "$g_talk_troop", slot_troop_last_comment_slot),
     (troop_set_slot, "$g_talk_troop", slot_troop_last_comment_slot, "$num_log_entries"),

     (store_add, ":log_entries_plus_one", "$num_log_entries", 1),
     (try_for_range, ":log_entry_no", 1, ":log_entries_plus_one"),
#      It should be log entries plus one, so that the try_ sequence does not stop short of the last log entry
#      $Num_log_entries is now the number of the last log entry, which begins at "1" rather than "0"
#      This is so that (le, ":log_entry_no", ":talk_troop_last_comment_slot") works properly
     
       (troop_get_slot, ":entry_time",           "trp_log_array_entry_time",           ":log_entry_no"),
#      (val_max, ":entry_time", 1), #This is needed for pre-game events to be commented upon, if hours are used rather than the order of events
       (store_sub, ":entry_hours_elapsed", ":current_time", ":entry_time"),
       (try_begin),
         (le, ":log_entry_no", ":talk_troop_last_comment_slot"),
#         (le, ":entry_time", ":talk_troop_last_comment_time"),
         (try_begin),
           (eq, ":log_entry_no", ":talk_troop_last_comment_slot"),
           (eq, "$cheat_mode", 1),
           (assign, reg5, ":log_entry_no"),
           (display_message, "@{!}Entries up to #{reg5} skipped"),
         (try_end),
#       I suggest using the log entry number as opposed to time so that events in the same hour can be commented upon
#       This feels more natural, for example, if there are other lords in the court when the player pledges allegiance     
       (else_try),
#         (le, ":entry_hours_elapsed", 3), #don't comment on really fresh events 
#       (else_try),
         (call_script, "script_get_relevant_comment_for_log_entry", ":log_entry_no"),
         (gt, reg1, 10),
         (assign, ":score", reg1),
         (assign, ":comment", reg0),
		 #reg2 is what
		 (assign, ":rejoinder", reg3),
		 
         (store_random_in_range, ":rand", 70, 140),
         (val_mul, ":score", ":rand"),
         (store_add, ":entry_time_score", ":entry_hours_elapsed", 500), #approx. one month 
         (val_mul, ":score", 1000),
         (val_div, ":score", ":entry_time_score"), ###Relevance decreases over time - halved after one month, one-third after two, etc
         (try_begin),
           (gt, ":score", ":highest_score_so_far"),
           (assign, ":highest_score_so_far", ":score"),
           (assign, ":best_comment_so_far",  ":comment"),
           (assign, ":rejoinder_to_best_comment_so_far",  ":rejoinder"),
           (assign, ":best_log_entry", ":log_entry_no"),
           (assign, ":comment_relation_change", reg2),
         (try_end),
       (try_end),
     (try_end),

     (try_begin),
       (gt, ":best_comment_so_far", 0),
       (assign, ":comment_found", 1), #comment found print it to s61 now. 
       (troop_get_slot, ":actor",                 "trp_log_array_actor",                 ":best_log_entry"),
       (troop_get_slot, ":center_object",         "trp_log_array_center_object",         ":best_log_entry"),
       (troop_get_slot, ":center_object_lord",    "trp_log_array_center_object_lord",    ":best_log_entry"),
       (troop_get_slot, ":center_object_faction", "trp_log_array_center_object_faction", ":best_log_entry"),
       (troop_get_slot, ":troop_object",          "trp_log_array_troop_object",          ":best_log_entry"),
       (troop_get_slot, ":troop_object_faction",  "trp_log_array_troop_object_faction",  ":best_log_entry"),
       (troop_get_slot, ":faction_object",        "trp_log_array_faction_object",        ":best_log_entry"),
       (try_begin),
         (ge, ":actor", 0),
         (str_store_troop_name,   s50, ":actor"),
       (try_end),
       (try_begin),
         (ge, ":center_object", 0),
         (str_store_party_name,   s51, ":center_object"),
       (try_end),
       (try_begin),
         (ge, ":center_object_lord", 0),
         (str_store_troop_name,   s52, ":center_object_lord"),
       (try_end),
       (try_begin),
         (ge, ":center_object_faction", 0),
         (str_store_faction_name, s53, ":center_object_faction"),
       (try_end),
       (try_begin),
         (ge, ":troop_object", 0),
         (str_store_troop_name,   s54, ":troop_object"),
       (try_end),
       (try_begin),
         (is_between, ":troop_object_faction", kingdoms_begin, kingdoms_end),
         (str_store_faction_name, s55, ":troop_object_faction"),
         (str_store_string, s55, "str_the_s55"),
	   (else_try), 
		 (is_between, ":troop_object", bandits_begin, bandits_end),
         (str_store_string, s55, "str_bandits"),
	   (else_try),
	     (eq, ":troop_object_faction", "fac_deserters"),
         (str_store_string, s55, "str_deserters"),
       (else_try),
         (str_store_string, s55, "str_travellers_on_the_road"),
	   (else_try),
	   
       (try_end),
	   
       (try_begin),
         (ge, ":faction_object", 0),
         (str_store_faction_name, s56, ":faction_object"),
       (try_end),
	   (assign, "$g_last_comment_copied_to_s42", ":best_comment_so_far"), #maybe deprecate
	   (assign, "$g_rejoinder_to_last_comment", ":rejoinder_to_best_comment_so_far"),
	   
       (str_store_string, s42, ":best_comment_so_far"),
     (try_end),
     
     (assign, reg0, ":comment_found"),
	 
     (assign, "$log_comment_relation_change", ":comment_relation_change"),
     ]),

#	 
  ("merchant_road_info_to_s42", #also does itemss to s32
    [
	(store_script_param, ":center", 1),
	
	(assign, ":last_bandit_party_found", -1),
	(assign, ":last_bandit_party_origin", -1),
	(assign, ":last_bandit_party_destination", -1),
	(assign, ":last_bandit_party_hours_ago", -1),
	
	(str_clear, s32),
	
	(str_clear, s42), 
	(str_clear, s47), #safe roads
	
	(try_for_range, ":center_to_reset", centers_begin, centers_end),
		(party_set_slot, ":center_to_reset", slot_party_temp_slot_1, 0),
	(try_end),

	(assign, ":road_attacks", 0),
	(assign, ":trades", 0),
	
#first mention all attacks	
    (try_for_range, ":log_entry_iterator", 0, "$num_log_entries"),
		(store_sub, ":log_entry_no", "$num_log_entries", ":log_entry_iterator"),
#how long ago?
        (this_or_next|troop_slot_eq, "trp_log_array_entry_type", ":log_entry_no", logent_traveller_attacked),
			(troop_slot_eq, "trp_log_array_entry_type", ":log_entry_no", logent_party_traded),

#       reference - (call_script, "script_add_log_entry", logent_traveller_attacked, ":winner_party" (actor),  ":origin" (center object), ":destination" (troop_object), ":winner_faction"),
			
        (troop_get_slot, ":origin",         "trp_log_array_center_object",         ":log_entry_no"),
        (troop_get_slot, ":destination",    "trp_log_array_troop_object",          ":log_entry_no"),
		
		(this_or_next|eq, ":origin", ":center"),
			(eq, ":destination", ":center"),
		
	
        (troop_get_slot, ":event_time",            "trp_log_array_entry_time",              ":log_entry_no"),
		(store_current_hours, ":cur_hour"),
		(store_sub, ":hours_ago", ":cur_hour", ":event_time"),
		(assign, reg3, ":hours_ago"),

		(lt, ":hours_ago", 672), #four weeks
		
		(try_begin),
			(eq, "$cheat_mode", 1),
			(troop_slot_eq, "trp_log_array_entry_type", ":log_entry_no", logent_traveller_attacked),
			(display_message, "str_attack_on_travellers_found_reg3_hours_ago"),
		(else_try),	
			(eq, "$cheat_mode", 1),
			(troop_slot_eq, "trp_log_array_entry_type", ":log_entry_no", logent_party_traded),
			(display_message, "str_trade_event_found_reg3_hours_ago"),
		(try_end),

		(try_begin), #possibly make script -- get_colloquial_for_time
			(lt, ":hours_ago", 24),
			(str_store_string, s46, "str_a_short_while_ago"),
		(else_try),
			(lt, ":hours_ago", 48),
			(str_store_string, s46, "str_one_day_ago"),
		(else_try),	
			(lt, ":hours_ago", 72),
			(str_store_string, s46, "@two days ago"),
		(else_try),	
			(lt, ":hours_ago", 154),
			(str_store_string, s46, "str_earlier_this_week"),
		(else_try),
			(lt, ":hours_ago", 240),
			(str_store_string, s46, "str_about_a_week_ago"),
		(else_try),
			(lt, ":hours_ago", 480),
			(str_store_string, s46, "str_about_two_weeks_ago"),
		(else_try),
			(str_store_string, s46, "str_several_weeks_ago"),
		(try_end),


			
        (troop_get_slot, ":actor", "trp_log_array_actor", ":log_entry_no"),
        (troop_get_slot, ":faction_object", "trp_log_array_faction_object", ":log_entry_no"),
	 
		(str_store_string, s39, "str_unknown_assailants"),
		(assign, ":assailants_known", -1),
		(try_begin),
			(party_is_active, ":actor"),
			(store_faction_of_party, ":actor_faction", ":actor"),
			(eq, ":faction_object", ":actor_faction"),
			(assign, ":assailants_known", ":actor"),
			(str_store_party_name, s39, ":assailants_known"),
			(assign, "$g_bandit_party_for_bounty", -1),
			(try_begin), #possibly make script -- get_colloquial_for_faction
				(eq, ":faction_object", "fac_kingdom_1"),
				(str_store_string, s39, "str_swadians"),
			(else_try),	
				(eq, ":faction_object", "fac_kingdom_2"),
				(str_store_string, s39, "str_vaegirs"),
			(else_try),	
				(eq, ":faction_object", "fac_kingdom_3"),
				(str_store_string, s39, "str_khergits"),
			(else_try),	
				(eq, ":faction_object", "fac_kingdom_4"),
				(str_store_string, s39, "str_nords"),
			(else_try),	
				(eq, ":faction_object", "fac_kingdom_5"),
				(str_store_string, s39, "str_rhodoks"),
			(else_try),	
				(eq, ":faction_object", "fac_kingdom_6"),
				(str_store_string, s39, "str_sarranids"),
			(else_try),
				(eq, ":faction_object", "fac_player_supporters_faction"),
				(str_store_string, s39, "str_your_followers"),
			(else_try), #bandits	
				(assign, ":last_bandit_party_found", ":assailants_known"),
				(assign, ":last_bandit_party_origin", ":origin"),
				(assign, ":last_bandit_party_destination", ":destination"),
				(assign, ":last_bandit_party_hours_ago", ":hours_ago"),
			(try_end),
		(try_end),
	 
		(try_begin),
			(eq, ":origin", ":center"),
			(troop_slot_eq, "trp_log_array_entry_type", ":log_entry_no", logent_traveller_attacked),
			(party_slot_eq, ":destination", slot_party_temp_slot_1, 0),

			(party_set_slot, ":destination", slot_party_temp_slot_1, 1),
			(str_store_party_name, s40, ":destination"),
			(str_store_string, s44, "str_we_have_heard_that_travellers_heading_to_s40_were_attacked_on_the_road_s46_by_s39"),
			(str_store_string, s43, "str_s42"),
			(str_store_string, s42, "str_s43_s44"),

			(val_add, ":road_attacks", 1),
			#travellers were attacked on the road to...			
		(else_try),
			(eq, ":destination", ":center"),
			(troop_slot_eq, "trp_log_array_entry_type", ":log_entry_no", logent_traveller_attacked),
			(party_slot_eq, ":origin", slot_party_temp_slot_1, 0),

			(party_set_slot, ":origin", slot_party_temp_slot_1, 1),
			(str_store_party_name, s40, ":origin"),
			(str_store_string, s44, "str_we_have_heard_that_travellers_coming_from_s40_were_attacked_on_the_road_s46_by_s39"),

			(str_store_string, s43, "str_s42"),
			(str_store_string, s42, "str_s43_s44"),

			(val_add, ":road_attacks", 1),

		#travellers from here traded at...
#		(else_try),
#			(eq, ":origin", ":center"),
#			(troop_slot_eq, "trp_log_array_entry_type", ":log_entry_no", logent_party_traded),
#			(party_slot_eq, ":destination", slot_party_temp_slot_1, 0),

#			(party_set_slot, ":destination", slot_party_temp_slot_1, 1),
#			(str_store_party_name, s40, ":destination"),
#			(str_store_string, s44, "@Travellers headed to {s40} traded there {s46}"),
#			(str_store_string, s43, "@{s42"),
#			(str_store_string, s42, "str_s43_s44"),

			#caravan from traded at...
		(else_try),
			(eq, ":destination", ":center"),
			(troop_slot_eq, "trp_log_array_entry_type", ":log_entry_no", logent_party_traded),
			(party_slot_eq, ":origin", slot_party_temp_slot_1, 0),

			(party_set_slot, ":origin", slot_party_temp_slot_1, 1),
			(str_store_party_name, s40, ":origin"),
			(str_store_string, s44, "str_travellers_coming_from_s40_traded_here_s46"),
			(str_store_string, s43, "str_s42"),
			(str_store_string, s42, "str_s43_s44"),

			(val_add, ":trades", 1),

			#caravan from traded at...
		(try_end),
		
	(try_end),

	
	(try_begin),
		(le, ":trades", 2),
		(eq, ":road_attacks", 0),
		(store_current_hours, ":hours"),
		(lt, ":hours", 168),
		(str_store_string, s42, "str_it_is_still_early_in_the_caravan_season_so_we_have_seen_little_tradings42"),
	(else_try),
		(eq, ":trades", 0),
		(eq, ":road_attacks", 0),
		(str_store_string, s42, "str_there_has_been_very_little_trading_activity_here_recentlys42"),
	(else_try),
		(le, ":trades", 2),
		(eq, ":road_attacks", 0),
		(str_store_string, s42, "str_there_has_some_trading_activity_here_recently_but_not_enoughs42"),
	(else_try),	
		(le, ":trades", 2),
		(le, ":road_attacks", 2),
		(str_store_string, s42, "str_there_has_some_trading_activity_here_recently_but_the_roads_are_dangerouss42"),
	(else_try),	
		(ge, ":road_attacks", 3),
		(str_store_string, s42, "str_the_roads_around_here_are_very_dangerouss42"),
	(else_try),	
		(ge, ":road_attacks", 1),
		(str_store_string, s42, "str_we_have_received_many_traders_in_town_here_although_there_is_some_danger_on_the_roadss42"),
	(else_try),
		(str_store_string, s42, "str_we_have_received_many_traders_in_town_heres42"),
	(try_end),
	
#do safe roads
	(assign, ":unused_trade_route_found", 0),
	(try_for_range, ":trade_route_slot", slot_town_trade_routes_begin, slot_town_trade_routes_end),
		(party_get_slot, ":trade_center", ":center", ":trade_route_slot"),
		(is_between, ":trade_center", centers_begin, centers_end),

		(party_slot_eq, ":trade_center", slot_party_temp_slot_1, 0),

#		(party_get_slot, ":town_lord", ":trade_center", slot_town_lord),
				
		(str_store_party_name, s41, ":trade_center"),
		(try_begin),
			(eq, ":unused_trade_route_found", 1),
			(str_store_string, s44, "str_s44_s41"),
		(else_try),
			(str_store_string, s44, "str_s41"),
		(try_end),
		(assign, ":unused_trade_route_found", 1),
	(try_end),
	(try_begin),
		(eq, ":unused_trade_route_found", 1),
		(str_store_string, s47, "str_there_is_little_news_about_the_caravan_routes_to_the_towns_of_s44_and_nearby_parts_but_no_news_is_good_news_and_those_are_therefore_considered_safe"),
	(try_end),

	(assign, ":safe_village_road_found", 0),
	(try_for_range, ":village", villages_begin, villages_end),
		(party_slot_eq, ":village", slot_village_market_town, ":center"),
		(party_slot_eq, ":village", slot_party_temp_slot_1, 0),

#		(party_get_slot, ":town_lord", ":village", slot_town_lord),
		(str_store_party_name, s41, ":village"),
		(try_begin),
			(eq, ":safe_village_road_found", 1),
			(str_store_string, s44, "str_s44_s41"),
		(else_try),
			(str_store_string, s44, "str_s41"),
		(try_end),
		(assign, ":safe_village_road_found", 1),
	(try_end),

	(try_begin),
		(eq, ":safe_village_road_found", 1),
		(eq, ":unused_trade_route_found", 1),
		(str_store_string, s47, "str_s47_also_the_roads_to_the_villages_of_s44_and_other_outlying_hamlets_are_considered_safe"),
	(else_try),	
		(eq, ":safe_village_road_found", 1),
		(str_store_string, s47, "str_however_the_roads_to_the_villages_of_s44_and_other_outlying_hamlets_are_considered_safe"),
	(try_end),

	(str_store_string, s33, "str_we_have_shortages_of"),
	(assign, ":some_shortages_found", 0),
	(try_for_range, ":cur_good", trade_goods_begin, trade_goods_end),
        (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, ":price", ":center", ":cur_good_price_slot"),
		(gt, ":price", 1100),

        (str_store_item_name, s34, ":cur_good"),
        (assign, reg1, ":price"),
        (str_store_string, s33, "str_s33_s34_reg1"),

		(assign, ":some_shortages_found", 1),	
	(try_end),

	(try_begin),
		(eq, ":some_shortages_found", 0),
		(str_store_string, s32, "str_we_have_adequate_stores_of_all_commodities"),
	(else_try),
		(str_store_string, s32, "str_s33_and_some_other_commodities"),
	(try_end),

	(assign, reg0, ":last_bandit_party_found"),
	(assign, reg1, ":last_bandit_party_origin"),
	(assign, reg2, ":last_bandit_party_destination"),
	(assign, reg3, ":last_bandit_party_hours_ago"),
	
	
	] 
	),

  ("get_manhunt_information_to_s15", 
    [
     (store_script_param, ":quest", 1),

	(str_store_string, s15, "str_the_roads_are_full_of_brigands_friend_but_that_name_in_particular_does_not_sound_familiar_good_hunting_to_you_nonetheless"),
    (quest_get_slot, ":quarry", ":quest", slot_quest_target_party),
	(try_begin),
		(is_between, "$g_talk_troop", active_npcs_begin, active_npcs_end),
		(troop_get_slot, ":talk_party", "$g_talk_troop", slot_troop_leaded_party),
	(else_try),
		(gt, "$g_encountered_party", "p_spawn_points_end"),
		(assign, ":talk_party", "$g_encountered_party"),
	(else_try),	
		(assign, ":talk_party", -1),
	(try_end),
	
    (try_for_range, ":log_entry", 0, "$num_log_entries"),
		(gt, ":talk_party", -1),
		(troop_get_slot, ":party", "trp_log_array_actor", ":log_entry"),
		(eq, ":party", ":talk_party"),
		(troop_get_slot, ":bandit_party", "trp_log_array_troop_object", ":log_entry"),
		(eq, ":bandit_party", ":quarry"),
		(store_current_hours, ":hours_ago"),
		(troop_get_slot, ":sighting_time", "trp_log_array_entry_time",  ":log_entry"),
		(val_sub, ":hours_ago", ":sighting_time"), 
		(try_begin),
			(le, ":hours_ago", 1),
			(str_store_string, s16, "str_less_than_an_hour_ago"),
		(else_try),
			(le, ":hours_ago", 48),
			(assign, reg3, ":hours_ago"),
			(str_store_string, s16, "str_maybe_reg3_hours_ago"),
		(else_try),
			(val_div, ":hours_ago", 24),
			(assign, reg3, ":hours_ago"),
			(str_store_string, s16, "str_reg3_days_ago"),
		(try_end),
		
		(troop_get_slot, ":center", "trp_log_array_center_object", ":log_entry"),
		(str_store_party_name, s17, ":center"),
		(troop_get_slot, ":entry_type", "trp_log_array_entry_type", ":log_entry"),
		(eq, ":entry_type", logent_party_spots_wanted_bandits),
		(str_store_string, s15, "str_youre_in_luck_we_sighted_those_bastards_s16_near_s17_hurry_and_you_might_be_able_to_pick_up_their_trail_while_its_still_hot"),
		
#		(try_begin),
#			(eq, ":entry_type", logent_party_chases_wanted_bandits),
#			(str_store_string, s15, "@You're in luck. We gave chase to those bastards {s16} near {s17}. They have eluded us so far -- but perhaps you will do better..."),
#		(else_try),
#			(eq, ":entry_type", logent_party_runs_from_wanted_bandits),
#			(str_store_string, s15, "@As it happens, they tried to run us down near {s17} {s16}. By the heavens, I hope you teach them a lesson."),
#		(try_end),
	(try_end),
	]),

	
#Troop Commentaries end



  ("rebellion_arguments", #Right now, called only in one place. This is only used when for player overtures, and will need some changes if this script is called when NPCs try to suborn lords
    [
     (store_script_param, ":lord", 1),
     (store_script_param, ":argument", 2),
     (store_script_param, ":candidate", 3),

     (assign, ":argument_appeal", 0),
     (assign, ":argument_strength", 0),

     (troop_get_slot, ":reputation", ":lord", slot_lord_reputation_type),

	 (store_faction_of_troop, ":lord_faction", ":candidate"),
	 (store_faction_of_troop, ":candidate_faction", ":candidate"),
	 
	 (try_begin),
		(eq, ":candidate", "trp_player"),
		(assign, ":right_to_rule", "$player_right_to_rule"),
	 (else_try), #default right to rule of 75 for pretenders claiming throne
		(is_between, ":candidate", pretenders_begin, pretenders_end),
		(troop_slot_eq, ":candidate", slot_troop_original_faction, ":lord_faction"),
		(assign, ":right_to_rule", 75),
	 (else_try), #default right to rule of 60 for all other lords
		(assign, ":right_to_rule", 60),
	 (try_end),
	 
	 (try_begin),
		(eq, ":argument", argument_claim),					
		(store_sub, ":argument_strength", ":right_to_rule", 30),				
	 (else_try),
		(eq, ":argument", argument_ruler),		
		(store_sub, ":argument_strength", "$player_honor", 20),
	 (else_try),
		(eq, ":argument", argument_lords),		
		(store_sub, ":argument_strength", "$player_honor", 20),		
	 (else_try),
	    #argument_strength is ((5 * number of centers player have) - 40) if argument type is argument_victory
		(eq, ":argument", argument_victory),		
		(assign, ":argument_strength", 0),
		(try_for_range, ":center", centers_begin, centers_end),
			(store_faction_of_party, ":center_faction", ":center"),
			(assign, ":argument_strength", -40),
			(try_begin),
				(eq, "$players_kingdom", ":candidate_faction"),
				(this_or_next|eq, ":center_faction", "fac_player_faction"),
				(eq, ":center_faction", "fac_player_supporters_faction"),
				(val_add, ":argument_strength", 5),
			(else_try),
				(eq, ":center_faction", ":candidate_faction"),
				(val_add, ":argument_strength", 5),
			(try_end),
		(try_end),		
	 (else_try),
	    #argument_strength is (20 - 20 * (number of lords in player's faction which not awareded fief by player although there is a fief awarding in future promise))
		(eq, ":argument", argument_benefit),
		(assign, ":argument_strength", 20),
		(try_for_range, ":lord_promised_fief", active_npcs_begin, active_npcs_end),
			(store_faction_of_troop, ":other_faction", ":lord_promised_fief"),
			(neq, ":lord", "$g_talk_troop"),
			(this_or_next|eq, ":other_faction", "fac_player_supporters_faction"),
			(eq, ":other_faction", "$players_kingdom"),
			(troop_slot_eq, ":lord_promised_fief", slot_troop_promised_fief, 1),
			(val_sub, ":argument_strength", 20),
		(try_end),
	 (try_end),
	 (val_clamp, ":argument_strength", -40, 41),
	 	 
     (try_begin),
         (eq, ":reputation", lrep_martial),
         (try_begin),
             (eq, ":argument", argument_claim),
             (assign, ":argument_appeal", 30),			 
			 (try_begin),
				(gt, ":argument_strength", 0),
				(str_store_string, s15, "str_you_speak_of_claims_to_the_throne_good_there_is_nothing_id_rather_do_than_fight_for_a_good_cause"),
			 (else_try),
				(str_store_string, s15, "str_you_speak_of_claims_to_the_throne_well_there_is_nothing_id_rather_do_than_fight_for_a_good_cause_but_the_claim_you_make_seems_somewhat_weak"),
		     (try_end),
         (else_try),
             (eq, ":argument", argument_lords),
             (assign, ":argument_appeal", 10),			 
			 (try_begin),
				(gt, ":argument_strength", 0),
				(str_store_string, s15, "str_i_am_pleased_that_you_speak_of_upholding_my_ancient_rights_which_are_sometimes_trod_upon_in_these_sorry_days"),
			 (else_try),
				(str_store_string, s15, "str_i_am_pleased_that_you_speak_of_upholding_my_ancient_rights_but_sometimes_men_make_pledges_before_they_are_king_which_they_cannot_keep_once_they_take_the_throne"),
			 (try_end),
         (else_try),
             (eq, ":argument", argument_ruler),
             (assign, ":argument_appeal", 0),			 
			 (try_begin),
				(str_store_string, s15, "str_you_speak_of_protecting_the_commons_well_i_supposed_thats_good_but_sometimes_the_commons_overstep_their_boundaries_im_more_concerned_that_your_claim_be_legal_so_i_can_swing_my_sword_with_a_good_conscience"),
			 (try_end),			 
         (else_try),
             (eq, ":argument", argument_benefit),
             (assign, ":argument_appeal", -10),			 
			 (try_begin),
				(gt, ":argument_strength", 0),
				(str_store_string, s15, "str_you_speak_of_giving_me_land_good_i_ask_for_no_more_than_my_due"),
			 (else_try),
				(str_store_string, s15, "str_you_speak_of_giving_me_land_unfortunately_you_are_not_wellknown_for_rewarding_those_to_whom_you_have_made_such_offers"),
			 (try_end),
         (else_try),
             (eq, ":argument", argument_victory),
             (assign, ":argument_appeal", -30),			 
			 (str_store_string, s15, "str_you_speak_of_unifying_calradia_well_i_believe_that_well_always_be_fighting__its_important_that_we_fight_for_a_rightful_cause"),
         (try_end),
     (else_try),
        (eq, ":reputation", lrep_quarrelsome),
        (try_begin),
             (eq, ":argument", argument_claim),
             (assign, ":argument_appeal", -20),
 			 (str_store_string, s15, "str_you_talk_of_claims_to_the_throne_but_i_leave_bickering_about_legalities_to_the_lawyers_and_clerks"),
		(else_try),
             (eq, ":argument", argument_ruler),
             (assign, ":argument_appeal", -30),
			 (str_store_string, s15, "str_you_speak_of_ruling_justly_hah_ill_believe_theres_such_a_thing_as_a_just_king_when_i_see_one"),
		(else_try),
             (eq, ":argument", argument_lords),
             (assign, ":argument_appeal", 0),
			 (str_store_string, s15, "str_you_spoke_of_protecting_the_rights_of_the_nobles_if_you_did_youd_be_the_first_king_to_do_so_in_a_very_long_time"),
		(else_try),
             (eq, ":argument", argument_benefit),
             (assign, ":argument_appeal", 30),
			 (try_begin),
				(gt, ":argument_strength", 0),
				(str_store_string, s15, "str_you_speak_of_giving_me_land_ay_well_lets_see_if_you_deliver"),
			 (else_try),
				(str_store_string, s15, "str_you_speak_of_giving_me_land_bah_youre_not_known_for_delivering_on_your_pledges"),
			 (try_end),
	    (else_try),
             (eq, ":argument", argument_victory),
             (assign, ":argument_appeal", 10),			 
			 (try_begin),
				(gt, ":argument_strength", 0),
				(str_store_string, s15, "str_you_speak_of_unifying_calradia_well_youve_done_a_good_job_at_making_calradia_bend_its_knee_to_you_so_maybe_thats_not_just_talk"),
			 (else_try),
				(str_store_string, s15, "str_you_speak_of_unifying_calradia_id_be_impressed_if_i_thought_you_could_do_it_but_unfortunately_you_dont"),
			 (try_end),
		(try_end),
     (else_try),
         (eq, ":reputation", lrep_selfrighteous),
         (try_begin),
             (eq, ":argument", argument_claim),
             (assign, ":argument_appeal", -20),
			 (str_store_string, s15, "str_you_speak_of_claims_to_the_throne_well_any_peasant_can_claim_to_be_a_kings_bastard"),
		 (else_try),
             (eq, ":argument", argument_ruler),
             (assign, ":argument_appeal", -30),			 
			 (str_store_string, s15, "str_well_its_a_fine_thing_to_court_the_commons_with_promises_but_what_do_you_have_to_offer_me"),
		 (else_try),
             (eq, ":argument", argument_lords),
             (assign, ":argument_appeal", 0),			 
			 (try_begin),
				(gt, ":argument_strength", 0),
				(str_store_string, s15, "str_you_speak_of_protecting_the_rights_of_lords_that_would_make_a_fine_change_if_my_rights_as_lord_would_be_respected"),
			 (else_try),
				(str_store_string, s15, "str_you_speak_of_protecting_the_rights_of_lords_that_would_make_a_fine_change_if_my_rights_as_lord_would_be_respected_however_it_is_easy_for_you_to_make_promises_while_you_are_weak_that_you_have_no_intention_of_keeping_when_you_are_strong"),
			 (try_end),			 
         (else_try),
             (eq, ":argument", argument_benefit),
             (assign, ":argument_appeal", 20),
			 (try_begin),
				(gt, ":argument_strength", 0),
				(str_store_string, s15, "str_you_speak_of_giving_me_land_well_my_family_is_of_ancient_and_noble_lineage_so_you_promise_me_no_more_than_my_due_still_your_gesture_is_appreciated"),
			 (else_try),
				(str_store_string, s15, "str_you_speak_of_giving_me_land_well_you_make_that_pledge_but_i_am_not_impressed"),
			 (try_end),
		 (else_try),
             (eq, ":argument", argument_victory),
             (assign, ":argument_appeal", 20),			 
			 (try_begin),
				(gt, ":argument_strength", 0),
				(str_store_string, s15, "str_you_speak_of_unifying_calradia_well_much_of_this_land_now_bends_its_knee_to_you_so_perhaps_that_is_not_just_talk"),
			 (else_try),
				(str_store_string, s15, "str_you_speak_of_unifying_calradia_but_right_now_yours_is_just_one_squabbling_faction_among_many"),
			 (try_end),			 			 
         (try_end),
     (else_try),
         (eq, ":reputation", lrep_cunning),
         (try_begin),
             (eq, ":argument", argument_claim),
             (assign, ":argument_appeal", -30),
			 (str_store_string, s15, "str_you_speak_of_claims_well_no_offense_but_a_claim_unsupported_by_might_rarely_prospers"),			 			 
         (else_try),
             (eq, ":argument", argument_ruler),
             (assign, ":argument_appeal", 10),			 
			 (try_begin),
				(gt, ":argument_strength", 0),
				(str_store_string, s15, "str_you_speak_of_protecting_the_commons_well_i_suppose_that_will_make_for_a_more_prosperous_realm_ive_always_tried_to_treat_my_peasants_decently_saves_going_to_bed_worrying_about_whether_youll_wake_up_with_the_roof_on_fire"),
			 (else_try),
				(str_store_string, s15, "str_you_speak_of_protecting_the_commons_very_well_but_remember_that_peasants_are_more_likely_to_cause_trouble_if_you_make_promises_then_dont_deliver_than_if_you_never_made_the_promise_in_the_first_place"),
			 (try_end),
         (else_try),
             (eq, ":argument", argument_lords),
             (assign, ":argument_appeal", 15),			 
			 (try_begin),
				(gt, ":argument_strength", 0),
				(str_store_string, s15, "str_you_speak_of_protecting_the_rights_of_lords_good_youd_be_well_advised_to_do_that__men_fight_better_for_a_king_wholl_respect_their_rights"),
			 (else_try),
				(str_store_string, s15, "str_you_speak_of_protecting_the_rights_of_lords_very_well_but_remember__failing_to_keep_promises_which_you_made_while_scrambling_up_the_throne_is_the_quickest_way_to_topple_off_of_it_once_you_get_there"),
			 (try_end),			 			 			 			 
         (else_try),
             (eq, ":argument", argument_benefit),
             (assign, ":argument_appeal", -20),			 
			 (str_store_string, s15, "str_you_speak_of_giving_me_land_very_good_but_often_i_find_that_when_a_man_makes_too_many_promises_trying_to_get_to_the_top_he_has_trouble_keeping_them_once_he_reaches_it"),
         (else_try),
             (eq, ":argument", argument_victory),
             (assign, ":argument_appeal", 20),			 
			 (try_begin),
				(gt, ":argument_strength", 0),
				(str_store_string, s15, "str_you_speak_of_unifying_calradia_well_many_have_said_that_you_might_very_well_be_the_one_to_do_it"),
			 (else_try),
				(str_store_string, s15, "str_you_speak_of_unifying_calradia_well_all_the_kings_say_that_im_not_sure_that_you_will_succeed_while_they_fail"),
			 (try_end),			 			 
         (try_end),
     (else_try),
         (eq, ":reputation", lrep_debauched),
         (try_begin),
             (eq, ":argument", argument_claim),
             (assign, ":argument_appeal", -20),			 
			 (str_store_string, s15, "str_you_speak_of_claims_do_you_think_i_care_for_the_nattering_of_lawyers"),			 
         (else_try),
             (eq, ":argument", argument_ruler),
             (assign, ":argument_appeal", -20),			 
			 (str_store_string, s15, "str_you_speak_of_protecting_the_commons_how_kind_of_you_i_shall_tell_my_swineherd_all_about_your_sweet_promises_no_doubt_he_will_become_your_most_faithful_vassal"),
         (else_try),
             (eq, ":argument", argument_lords),
             (assign, ":argument_appeal", -10),			 
			 (str_store_string, s15, "str_you_speak_of_protecing_the_rights_of_lords_such_sweet_words_but_ill_tell_you_this__the_only_rights_that_are_respected_in_this_world_are_the_rights_to_dominate_whoever_is_weaker_and_to_submit_to_whoever_is_stronger"),			 
         (else_try),
             (eq, ":argument", argument_benefit),
             (assign, ":argument_appeal", 20),			 
			 (try_begin),
				(gt, ":argument_strength", 0),
				(str_store_string, s15, "str_you_speak_of_giving_me_land_yes_very_good__but_you_had_best_deliver"),
			 (else_try),
				(str_store_string, s15, "str_you_speak_of_giving_me_land_hah_perhaps_all_those_others_to_whom_you_promised_lands_will_simply_step_aside"),
			 (try_end),			 			 
         (else_try),
             (eq, ":argument", argument_victory),
             (assign, ":argument_appeal", 10),			 
			 (try_begin),
				(gt, ":argument_strength", 0),
				(str_store_string, s15, "str_you_speak_of_unifying_calradia_you_may_indeed_humble_the_other_kings_of_this_land_and_in_that_case_i_would_hope_that_you_would_remember_me_as_your_faithful_servant"),
			 (else_try),
				(str_store_string, s15, "str_you_speak_of_unifying_calradia_but_you_are_weak_and_i_think_that_you_will_remain_weak"),
			 (try_end),			 
         (try_end),
	 (else_try),
         (eq, ":reputation", lrep_goodnatured),
         (try_begin),
             (eq, ":argument", argument_claim),
             (assign, ":argument_appeal", 10),
			 (try_begin),
				(gt, ":argument_strength", 0),
				(str_store_string, s15, "str_you_speak_of_claims_its_good_for_a_king_to_have_a_strong_claim_although_admittedly_im_more_concerned_that_he_rules_just_ly_than_with_legalities_anyway_your_claim_seems_wellfounded_to_me"),
			 (else_try),
				(str_store_string, s15, "str_you_speak_of_claims_but_your_claim_seems_a_bit_weak_to_me"),
			 (try_end),
         (else_try),
             (eq, ":argument", argument_ruler),
             (assign, ":argument_appeal", 20),
			 (try_begin),
				(gt, ":argument_strength", 0),
				(str_store_string, s15, "str_you_speak_of_protecting_the_commons_i_like_that_my_tenants_are_a_happy_lot_i_think_but_i_hear_of_others_in_other_estates_that_arent_so_fortunate"),
			 (else_try),
				(str_store_string, s15, "str_you_speak_of_protecting_the_commons_im_glad_to_hear_you_say_that_but_do_me_a_favor__dont_promise_the_commons_anything_you_cant_deliver_thats_a_sure_way_to_get_them_to_rebel_and_it_breaks_my_heart_to_have_to_put_them_down"),
			 (try_end),
         (else_try),
             (eq, ":argument", argument_lords),
			 (assign, ":argument_appeal", 0),
			 (str_store_string, s15, "str_you_speak_of_protecting_the_rights_of_lords_well_very_good_i_suppose_but_you_know__we_lords_can_take_of_ourselves_its_the_common_folk_who_need_a_strong_king_to_look_out_for_them_to_my_mind"),			 
         (else_try),
             (eq, ":argument", argument_benefit),
             (assign, ":argument_appeal", -15),
			 (str_store_string, s15, "str_you_speak_of_giving_me_land_its_kind_of_you_really_though_that_is_not_necessary"),			 			 
         (else_try),
             (eq, ":argument", argument_victory),
             (assign, ":argument_appeal", -25),
			 (str_store_string, s15, "str_you_speak_of_unifying_calradia_well_maybe_you_can_unite_this_land_by_the_sword_but_im_not_sure_that_this_will_make_you_a_good_ruler"),			 			 
         (try_end),
     (else_try),
         (eq, ":reputation", lrep_upstanding),
         (try_begin),
             (eq, ":argument", argument_claim),
             (assign, ":argument_appeal", 10),
			 (try_begin),
				(gt, ":argument_strength", 0),
				(str_store_string, s15, "str_you_speak_of_claims_a_king_must_have_a_strong_legal_claim_for_there_not_to_be_chaos_in_the_realm_and_yours_is_wellestablished"),
			 (else_try),
				(str_store_string, s15, "str_you_speak_of_claims_a_king_must_have_a_strong_legal_claim_for_there_not_to_be_chaos_in_the_realm_but_your_claim_is_not_so_strong"),
			 (try_end),
		 (else_try),
             (eq, ":argument", argument_lords),
             (assign, ":argument_appeal", -5),
			 (try_begin),
				(gt, ":argument_strength", 0),
				(str_store_string, s15, "str_you_speak_of_protecting_the_rights_of_lords_it_is_of_course_important_that_a_king_respect_the_rights_of_his_vassals_although_i_worry_that_a_king_who_took_a_throne_without_proper_cause_would_not_rule_with_justice"),
			 (else_try),
				(str_store_string, s15, "str_you_speak_of_protecting_the_rights_of_lords_it_is_of_course_important_that_a_king_respect_the_rights_of_his_vassals_however_i_would_like_to_know_that_you_would_indeed_deliver_on_your_promises"),
			 (try_end),
		 (else_try),
             (eq, ":argument", argument_ruler),
             (assign, ":argument_appeal", 5),			 
			 (try_begin),
				(gt, ":argument_strength", 0),
				(str_store_string, s15, "str_you_speak_of_protecting_the_commons_i_would_be_pleased_to_serve_a_king_who_respected_the_rights_of_his_subjects_although_i_worry_that_a_king_who_took_a_throne_without_proper_cause_would_not_rule_with_justice"),
			 (else_try),
				(str_store_string, s15, "str_you_speak_of_protecting_the_commons_i_would_be_pleased_to_serve_a_king_who_respected_the_rights_of_his_subjects_however_i_would_like_to_know_that_you_would_indeed_deliver_on_your_promises"),
			 (try_end),			 
         (else_try),
             (eq, ":argument", argument_benefit),
             (assign, ":argument_appeal", -40),
			 (str_store_string, s15, "str_i_am_not_swayed_by_promises_of_reward"),
		 (else_try),
             (eq, ":argument", argument_victory),
             (assign, ":argument_appeal", 10),			 
			 (try_begin),
				(gt, ":argument_strength", 0),
				(str_store_string, s15, "str_you_speak_of_unifying_calradia_it_would_be_good_to_bring_peace_to_the_realm_and_i_believe_that_you_are_strong_enough_to_do_so"),
			 (else_try),
				(str_store_string, s15, "str_you_speak_of_unifying_calradia_it_would_be_good_to_bring_peace_the_realm_but_with_your_kingdom_in_its_current_state_i_worry_that_you_are_just_bringing_more_discord"),
			 (try_end),			 			 
         (try_end),
     (try_end),
	 
	 (str_store_string, s14, "str_s15"),
	 	 
     (assign, reg0, ":argument_appeal"),
     (assign, reg1, ":argument_strength"),     
]),



#Rebellion changes end

  # script_get_culture_with_party_faction_for_music
  # Input: arg1 = party_no
  # Output: reg0 = culture
  ("get_culture_with_party_faction_for_music",
    [
      (store_script_param, ":party_no", 1),
      (store_faction_of_party, ":faction_no", ":party_no"),
      (try_begin),
        (this_or_next|eq, ":faction_no", "fac_player_faction"),
        (eq, ":faction_no", "fac_player_supporters_faction"),
        (assign, ":faction_no", "$players_kingdom"),
      (try_end),
      (try_begin),
        (is_between, ":party_no", centers_begin, centers_end),
        (this_or_next|eq, ":faction_no", "fac_player_supporters_faction"),
        (neg|is_between, ":faction_no", kingdoms_begin, kingdoms_end),
        (party_get_slot, ":faction_no", ":party_no", slot_center_original_faction),
      (try_end),
      (call_script, "script_get_culture_with_faction_for_music", ":faction_no"),
     ]),

  # script_get_culture_with_faction_for_music
  # Input: arg1 = party_no
  # Output: reg0 = culture
  ("get_culture_with_faction_for_music",
    [
      (store_script_param, ":faction_no", 1),
      (try_begin),
        (eq, ":faction_no", "fac_kingdom_1"),
        (assign, ":result", mtf_culture_1),
      (else_try),
        (eq, ":faction_no", "fac_kingdom_2"),
        (assign, ":result", mtf_culture_2),
      (else_try),
        (eq, ":faction_no", "fac_kingdom_3"),
        (assign, ":result", mtf_culture_3),
      (else_try),
        (eq, ":faction_no", "fac_kingdom_4"),
        (assign, ":result", mtf_culture_4),
      (else_try),
        (eq, ":faction_no", "fac_kingdom_5"),
        (assign, ":result", mtf_culture_5),
      (else_try),
        (eq, ":faction_no", "fac_kingdom_6"),
        (assign, ":result", mtf_culture_6),
      (else_try),
        (this_or_next|eq, ":faction_no", "fac_outlaws"),
        (this_or_next|eq, ":faction_no", "fac_peasant_rebels"),
        (this_or_next|eq, ":faction_no", "fac_deserters"),
        (this_or_next|eq, ":faction_no", "fac_mountain_bandits"),
        (eq, ":faction_no", "fac_forest_bandits"),
        (assign, ":result", mtf_culture_6),
      (else_try),
        (assign, ":result", 0), #no culture, including player with no bindings to another kingdom
      (try_end),
      (assign, reg0, ":result"),
     ]),

  # script_music_set_situation_with_culture
  # Input: arg1 = music_situation
  # Output: none
  ("music_set_situation_with_culture",
    [
      (store_script_param, ":situation", 1),
      (assign, ":culture", 0), #no culture
      (try_begin),
        (this_or_next|eq, ":situation", mtf_sit_town),
        (this_or_next|eq, ":situation", mtf_sit_day),
        (this_or_next|eq, ":situation", mtf_sit_night),
        (this_or_next|eq, ":situation", mtf_sit_town_infiltrate),
        (eq, ":situation", mtf_sit_encounter_hostile),
        (call_script, "script_get_culture_with_party_faction_for_music", "$g_encountered_party"),
        (val_or, ":culture", reg0),
      (else_try),
        (this_or_next|eq, ":situation", mtf_sit_ambushed),
        (eq, ":situation", mtf_sit_fight),
        (call_script, "script_get_culture_with_party_faction_for_music", "$g_encountered_party"),
        (val_or, ":culture", reg0),
        (call_script, "script_get_culture_with_party_faction_for_music", "p_main_party"),
        (val_or, ":culture", reg0),
        (call_script, "script_get_closest_center", "p_main_party"),
        (call_script, "script_get_culture_with_party_faction_for_music", reg0),
        (val_or, ":culture", reg0),
      (else_try),
        (eq, ":situation", mtf_sit_multiplayer_fight),
        (call_script, "script_get_culture_with_faction_for_music", "$g_multiplayer_team_1_faction"),
        (val_or, ":culture", reg0),
        (call_script, "script_get_culture_with_faction_for_music", "$g_multiplayer_team_2_faction"),
        (val_or, ":culture", reg0),
      (else_try),
        (eq, ":situation", mtf_sit_travel),
        (call_script, "script_get_culture_with_party_faction_for_music", "p_main_party"),
        (val_or, ":culture", reg0),
        (call_script, "script_get_closest_center", "p_main_party"),
        (call_script, "script_get_culture_with_party_faction_for_music", reg0),
        (val_or, ":culture", reg0),
      (else_try),
        (eq, ":situation", mtf_sit_victorious),
        (call_script, "script_get_culture_with_party_faction_for_music", "p_main_party"),
        (val_or, ":culture", reg0),
      (else_try),
        (eq, ":situation", mtf_sit_killed),
        (call_script, "script_get_culture_with_party_faction_for_music", "$g_encountered_party"),
        (val_or, ":culture", reg0),
      (try_end),
      (try_begin),
        (this_or_next|eq, ":situation", mtf_sit_town),
        (eq, ":situation", mtf_sit_day),
        (try_begin),
          (is_currently_night),
          (assign, ":situation", mtf_sit_night),
        (try_end),
      (try_end),
      (music_set_situation, ":situation"),
      (music_set_culture, ":culture"),
     ]),

  
  # script_combat_music_set_situation_with_culture
  # Input: none
  # Output: none
  ("combat_music_set_situation_with_culture",
    [
      (assign, ":situation", mtf_sit_fight),
      (assign, ":num_allies", 0),
      (assign, ":num_enemies", 0),
      (try_for_agents, ":agent_no"),
        (agent_is_alive, ":agent_no"),
        (agent_is_human, ":agent_no"),
        (agent_get_troop_id, ":agent_troop_id", ":agent_no"),
        (store_character_level, ":troop_level", ":agent_troop_id"),
        (val_add,  ":troop_level", 10),
        (val_mul, ":troop_level", ":troop_level"),
        (try_begin),
          (agent_is_ally, ":agent_no"),
          (val_add, ":num_allies", ":troop_level"),
        (else_try),
          (val_add, ":num_enemies", ":troop_level"),
        (try_end),
      (try_end),
      (val_mul, ":num_allies", 4), #play ambushed music if we are 2 times outnumbered.
      (val_div, ":num_allies", 3),
      (try_begin),
        (lt, ":num_allies", ":num_enemies"),
        (assign, ":situation", mtf_sit_ambushed),
      (try_end),
      (call_script, "script_music_set_situation_with_culture", ":situation"),
     ]),

  # script_play_victorious_sound
  # Input: none
  # Output: none
  ("play_victorious_sound",
   [
     (call_script, "script_music_set_situation_with_culture", mtf_sit_victorious),
#      (play_cue_track, "track_victorious_neutral_1"),
#      (play_track, "track_victorious_neutral_1", 1),
     ]),
  
  # script_set_items_for_tournament
  # Input: arg1 = horse_chance, arg2 = lance_chance (with horse only), arg3 = sword_chance, arg4 = axe_chance, arg5 = bow_chance (without horse only), arg6 = javelin_chance (with horse only), arg7 = mounted_bow_chance (with horse only), arg8 = crossbow_sword_chance, arg9 = armor_item_begin, arg10 = helm_item_begin
  # Output: none (sets mt_arena_melee_fight items)
  ("set_items_for_tournament",
    [
      (store_script_param, ":horse_chance", 1),
      (store_script_param, ":lance_chance", 2),
      (store_script_param, ":sword_chance", 3),
      (store_script_param, ":axe_chance", 4),
      (store_script_param, ":bow_chance", 5),
      (store_script_param, ":javelin_chance", 6),
      (store_script_param, ":mounted_bow_chance", 7),
      (store_script_param, ":crossbow_sword_chance", 8),
      (store_script_param, ":armor_item_begin", 9),
      (store_script_param, ":helm_item_begin", 10),
      (store_add, ":total_chance", ":sword_chance", ":axe_chance"),
      (val_add, ":total_chance", ":crossbow_sword_chance"),
      (try_for_range, ":i_ep", 0, 32),
        (mission_tpl_entry_clear_override_items, "mt_arena_melee_fight", ":i_ep"),
        (assign, ":has_horse", 0),
        (store_div, ":cur_team", ":i_ep", 8),
        (try_begin),
          (store_random_in_range, ":random_no", 0, 100),
          (lt, ":random_no", ":horse_chance"),
          (assign, ":has_horse", 1),
          (mission_tpl_entry_add_override_item, "mt_arena_melee_fight", ":i_ep", "itm_practice_horse"),
        (try_end),
        (try_begin),
          (eq, ":has_horse", 1),
          (store_add, ":cur_total_chance", ":total_chance", ":lance_chance"),
          (val_add, ":cur_total_chance", ":javelin_chance"),
          (val_add, ":cur_total_chance", ":mounted_bow_chance"),
        (else_try),
          (store_add, ":cur_total_chance", ":total_chance", ":bow_chance"),
        (try_end),
        (store_random_in_range, ":random_no", 0, ":cur_total_chance"),
        (store_add, ":cur_shield_item", "itm_arena_shield_red", ":cur_team"),
        (try_begin),
          (val_sub, ":random_no", ":sword_chance"),
          (lt, ":random_no", 0),
          (try_begin),
            (store_random_in_range, ":sub_random_no", 0, 100),
            (lt, ":sub_random_no", 50),
            (mission_tpl_entry_add_override_item, "mt_arena_melee_fight", ":i_ep", "itm_practice_sword"),
            (mission_tpl_entry_add_override_item, "mt_arena_melee_fight", ":i_ep", ":cur_shield_item"),
#            (mission_tpl_entry_add_override_item, "mt_arena_melee_fight", ":i_ep", "itm_practice_shield"),
          (else_try),
            (mission_tpl_entry_add_override_item, "mt_arena_melee_fight", ":i_ep", "itm_heavy_practice_sword"),
          (try_end),
        (else_try),
          (val_sub, ":random_no", ":axe_chance"),
          (lt, ":random_no", 0),
          (mission_tpl_entry_add_override_item, "mt_arena_melee_fight", ":i_ep", "itm_practice_axe"),
          (mission_tpl_entry_add_override_item, "mt_arena_melee_fight", ":i_ep", ":cur_shield_item"),
#         (mission_tpl_entry_add_override_item, "mt_arena_melee_fight", ":i_ep", "itm_practice_shield"),
        (else_try),
          (val_sub, ":random_no", ":crossbow_sword_chance"),
          (lt, ":random_no", 0),
          (mission_tpl_entry_add_override_item, "mt_arena_melee_fight", ":i_ep", "itm_practice_sword"),
          (mission_tpl_entry_add_override_item, "mt_arena_melee_fight", ":i_ep", "itm_practice_crossbow"),
          (mission_tpl_entry_add_override_item, "mt_arena_melee_fight", ":i_ep", "itm_practice_bolts"),
        (else_try),
          (eq, ":has_horse", 0),
          (val_sub, ":random_no", ":bow_chance"),
          (lt, ":random_no", 0),
          (mission_tpl_entry_add_override_item, "mt_arena_melee_fight", ":i_ep", "itm_practice_bow"),
          (mission_tpl_entry_add_override_item, "mt_arena_melee_fight", ":i_ep", "itm_practice_arrows"),
          (mission_tpl_entry_add_override_item, "mt_arena_melee_fight", ":i_ep", "itm_practice_dagger"),
        (else_try),
          (eq, ":has_horse", 1),
          (val_sub, ":random_no", ":lance_chance"),
          (lt, ":random_no", 0),
          (mission_tpl_entry_add_override_item, "mt_arena_melee_fight", ":i_ep", "itm_practice_lance"),
          (mission_tpl_entry_add_override_item, "mt_arena_melee_fight", ":i_ep", ":cur_shield_item"),
#          (mission_tpl_entry_add_override_item, "mt_arena_melee_fight", ":i_ep", "itm_practice_shield"),
        (else_try),
          (eq, ":has_horse", 1),
          (val_sub, ":random_no", ":javelin_chance"),
          (lt, ":random_no", 0),
          (mission_tpl_entry_add_override_item, "mt_arena_melee_fight", ":i_ep", "itm_practice_javelin"),
          (mission_tpl_entry_add_override_item, "mt_arena_melee_fight", ":i_ep", ":cur_shield_item"),
#          (mission_tpl_entry_add_override_item, "mt_arena_melee_fight", ":i_ep", "itm_practice_shield"),
        (else_try),
          (eq, ":has_horse", 1),
          (val_sub, ":random_no", ":mounted_bow_chance"),
          (lt, ":random_no", 0),
          (mission_tpl_entry_add_override_item, "mt_arena_melee_fight", ":i_ep", "itm_practice_bow"),
          (mission_tpl_entry_add_override_item, "mt_arena_melee_fight", ":i_ep", "itm_practice_arrows"),
          (mission_tpl_entry_add_override_item, "mt_arena_melee_fight", ":i_ep", "itm_practice_dagger"),
        (try_end),
        (try_begin),
          (ge, ":armor_item_begin", 0),
          (store_add, ":cur_armor_item", ":armor_item_begin", ":cur_team"),
          (mission_tpl_entry_add_override_item, "mt_arena_melee_fight", ":i_ep", ":cur_armor_item"),
        (try_end),
        (try_begin),
          (ge, ":helm_item_begin", 0),
          (store_add, ":cur_helm_item", ":helm_item_begin", ":cur_team"),
          (mission_tpl_entry_add_override_item, "mt_arena_melee_fight", ":i_ep", ":cur_helm_item"),
        (try_end),
      (try_end),
     ]),

# NE settings
	 
  ("cf_formation",
   [(team_get_leader, ":teamleader", reg0),
    (gt,":teamleader",-1),
    (assign,":leader",-1),
    (agent_get_class,":class",":teamleader"),
    (try_begin),
       (eq,":class",reg1),
       (get_player_agent_no,":player"),
       (neq,":teamleader",":player"),
       (assign,":leader",":teamleader"),
    (else_try),
       (call_script,"script_choose_formation_leader"),
       (gt,reg2,-1),
       (assign,":leader",reg2),
    (end_try), 
    (gt,":leader",-1), 
    (agent_get_position,1,":leader"),
    (position_move_x,1,100),
    (assign,":collumn",1),
    (try_for_agents,reg(5)),
       (neq,reg5,":leader"),
       (agent_is_alive,reg(5)),
       (agent_is_human,reg(5)),
       (agent_get_team  ,":team", reg5),
       (eq,":team",reg0),
       (agent_get_class ,":class", reg5),
       (eq,":class",reg1),                                   
       (agent_set_scripted_destination,reg(5),1),
       (position_move_x,1,100),
       (try_begin),
          (eq,":collumn",12),
          (position_move_x,1,-12*100),
          (position_move_y,1,-200),
          (assign,":collumn",1),
       (else_try),
          (val_add,":collumn",1),
       (end_try),
    (end_try)]),

  ("cf_formation_stagger",
   [(team_get_leader, ":teamleader", reg0),
    (gt,":teamleader",-1),
    (assign,":leader",-1),
    (agent_get_class,":class",":teamleader"),
    (try_begin),
       (eq,":class",reg1),
       (get_player_agent_no,":player"),
       (neq,":teamleader",":player"),
       (assign,":leader",":teamleader"),
    (else_try),
       (call_script,"script_choose_formation_leader"),
       (gt,reg2,-1),
       (assign,":leader",reg2),
    (end_try), 
    (gt,":leader",-1),
    (agent_get_position,1,":leader"),
    (position_move_x,1,100),
    (assign,":move_y",-100),
    (try_for_agents,reg(5)),
       (neq,reg5,":leader"),
       (agent_is_alive,reg(5)),
       (agent_is_human,reg(5)),
       (agent_get_team  ,":team", reg5),
       (eq,":team",reg0),
       (agent_get_class ,":class", reg5),
       (eq,":class",reg1),                                   
       (agent_set_scripted_destination,reg(5),1),
       (position_move_x,1,100),
       (position_move_y,1,":move_y"),
       (val_mul,":move_y",-1),
    (end_try)]),

  ("cf_formation_wedge",
   [(team_get_leader, ":teamleader", reg0),
    (gt,":teamleader",-1),
    (assign,":leader",-1),
    (agent_get_class,":class",":teamleader"),
    (try_begin),
       (eq,":class",reg1),
       (get_player_agent_no,":player"),
       (neq,":teamleader",":player"),
          (assign,":fail",0),
          (try_for_range,":ranged_item","itm_jarid","itm_flintlock_pistol"),
             (agent_has_item_equipped,":teamleader",":ranged_item"),
             (assign,":fail",1),
          (end_try),
          (eq,":fail",0),
       (assign,":leader",":teamleader"),
    (else_try),
       (assign,reg2,-1),
       (assign,":max_xp",0),
       (try_for_agents,":agent"),
          (agent_is_alive,":agent"),
          (agent_is_human,":agent"),
          (agent_get_team,":team",":agent"),
          (eq,":team",reg0),
          (agent_get_class,":class",":agent"),
          (eq,":class",reg1),
          (get_player_agent_no,":player"),
          (neq,":player",":agent"),
          (assign,":fail",0),
          (try_for_range,":ranged_item","itm_jarid","itm_flintlock_pistol"),
             (agent_has_item_equipped,":agent",":ranged_item"),
             (assign,":fail",1),
          (end_try),
          (eq,":fail",0),
          (agent_get_troop_id,":troop", ":agent"),
          (troop_get_xp, ":xp", ":troop"),
          (gt,":xp",":max_xp"),
          (assign,":max_xp",":xp"),
          (assign,reg2,":agent"),
       (end_try),
       (gt,reg2,-1),
       (assign,":leader",reg2),
    (end_try), 
    (gt,":leader",-1),
    (agent_get_position,1,":leader"),
    (assign,":collumn",1),
    (assign,":nc",3),
    (position_move_x,1,-150),
    (try_for_agents,reg(5)),
       (neq,reg5,":leader"),
       (agent_is_alive,reg(5)),
       (agent_is_human,reg(5)),
       (agent_get_team  ,":team", reg5),
       (eq,":team",reg0),
       (agent_get_class ,":class", reg5),
       (eq,":class",reg1),
          (assign,":fail",0),
          (try_for_range,":ranged_item","itm_jarid","itm_flintlock_pistol"),
             (agent_has_item_equipped,reg5,":ranged_item"),
             (assign,":fail",1),
          (end_try),
          (eq,":fail",0),
       (agent_set_scripted_destination,reg(5),1),
       (try_begin),
          (eq,":collumn",":nc"),
          (val_mul,":nc",-150),
          (position_move_x,1,":nc"),
          (position_move_y,1,-300),
          (assign,":collumn",1),
          (val_div,":nc",-150),
          (val_add,":nc",2),
       (else_try),
          (position_move_x,1,150),
          (val_add,":collumn",1),
       (end_try),
    (end_try)]),

  ("formation_end",
   [(try_for_agents,reg(5)),
       (agent_is_alive,reg(5)),
       (agent_is_human,reg(5)),
       (agent_get_team  ,":team", reg5),
       (eq,":team",reg0),
       (agent_get_class ,":class", reg5),
       (eq,":class",reg1), 
       (agent_clear_scripted_mode,reg5),
     (try_end),]),

  ("choose_formation_leader",
   [(assign,reg2,-1),
    (assign,":max_xp",0),
    (try_for_agents,":agent"),
        (agent_is_alive,":agent"),
        (agent_is_human,":agent"),
        (agent_get_team,":team",":agent"),
        (eq,":team",reg0),
        (agent_get_class,":class",":agent"),
        (eq,":class",reg1),
        (get_player_agent_no,":player"),
        (neq,":player",":agent"),
        (agent_get_troop_id,":troop", ":agent"),
        (troop_get_xp, ":xp", ":troop"),
        (gt,":xp",":max_xp"),
        (assign,":max_xp",":xp"),
        (assign,reg2,":agent"),
    (end_try),]),
   



  #script_healthbars
    ("healthbars",
    [
(assign,reg1,"$allies_coh_base"),
(assign,reg2,"$enemies_coh"),
(assign,reg3,"$new_kills"),
(display_message,"@Your troops are at {reg1}% cohesion (+{reg3}% bonus), the enemy at {reg2}%!",0x6495ed),
     ]),

  #script_morale_check
    ("morale_check",
    [
            (try_begin),
              (lt,"$allies_coh",80),
              (store_random_in_range,":routed",1,101),
              (assign,":chance_ply",85),
              (val_sub,":chance_ply","$allies_coh"),
                (try_begin),           
                  (le,":routed",":chance_ply"),             
                  (display_message,"@Morale of your troops wavers!",0xff4040),           
                  (call_script, "script_flee_allies"),
                (try_end),
            (try_end),

            (try_begin),
              (lt,"$enemies_coh",80),
              (store_random_in_range,":routed",1,101),
              (assign,":chance_ply",85),
              (val_sub,":chance_ply","$enemies_coh"),
                (try_begin), 
                  (le,":routed",":chance_ply"),             
                  (display_message,"@Morale of your enemies wavers!",0x7ccd7c),           
                  (call_script, "script_flee_enemies"),
                (try_end),           
            (try_end),
     ]),

  #script_battle_cry
    ("battle_cry",
    [

(store_skill_level,":leader","skl_leadership","trp_player"),
(try_for_agents,":agent"),
         (agent_is_alive,":agent"),
         (agent_is_human,":agent"),
         (agent_is_ally,":agent"),
         (store_agent_hit_points,":hitpoints",":agent",0),
(try_begin),
                   (le,":hitpoints",80),
   (val_add,":hitpoints",":leader"),
   (val_add,":hitpoints",10),
                   (agent_set_hit_points,":agent",":hitpoints"),
               (try_end),
(end_try),
(try_for_agents,":agent"),
         (agent_is_alive,":agent"),
         (agent_is_human,":agent"),
         (agent_is_ally,":agent"),
         (store_agent_hit_points,":hitpoints",":agent",0),
         (val_sub,":hitpoints",10),
         (store_random_in_range,":routed",1,101),
              (try_begin),
                   (le,":routed",":hitpoints"),
                         (agent_clear_scripted_mode,":agent"),
               (try_end),
(end_try),
     ]),

    ("rally",
    [
#(display_message,"@Your enemies rally to rejoin the battle!",0xff4040),
(try_for_agents,":agent"),
         (agent_is_alive,":agent"),
         (agent_is_human,":agent"),
         (store_agent_hit_points,":hitpoints",":agent",0),
         #(val_sub,":hitpoints",10),
         (store_random_in_range,":routed",1,101),
              (try_begin),
                   (le,":routed",":hitpoints"),
                         (agent_clear_scripted_mode,":agent"),
               (try_end),
(end_try),
     ]),


  #script_rout_check
    ("rout_check",
    [
(assign,":ally","$allies_coh"),
#(assign,reg2,"$allies_coh"),
#(display_message,"@allies {reg2}% cohesion!"),
(assign,":enemy","$enemies_coh"),
#(assign,reg2,"$enemies_coh"),
#(display_message,"@enemies {reg2}% cohesion!"),
(val_sub,":ally",":enemy"),
#(assign,reg2,":ally"),
#(display_message,"@difference {reg2}."),
(assign,":enemyflee",40),
(party_get_skill_level, ":enemy_party_tactics",  "p_collective_enemy", skl_tactics),
(val_max,":enemy_party_tactics",1),
(assign,":leader",1),
(try_for_agents,":agent"),
(neg|agent_is_ally,":agent"),
(agent_is_human,":agent"),
(store_skill_level,":newleader","skl_leadership",":agent"),
(val_max,":leader",":newleader"),
(try_end),
(val_mul,":leader",":enemy_party_tactics"),
(val_mul,":leader",60),
(val_div,":leader",100),
(val_add,":enemyflee",":leader"),
                (try_begin),
                   (ge,":ally",":enemyflee"),
                  (display_message,"@Your enemies flee in terror!",0x7ccd7c), 
                  (call_script, "script_rout_enemies"),
                  (assign,"$airout",1),
               (try_end),
(assign,":allyflee",-40),
(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"),
(val_max, ":player_party_tactics", 1),
(store_skill_level,":leader","skl_leadership","trp_player"),
(val_max, ":leader", 1),
(val_mul,":leader",":player_party_tactics"),
(val_mul,":leader",60),
(val_div,":leader",100),
(val_sub,":allyflee",":leader"),
                (try_begin),
                   (le,":ally",":allyflee"),
                  (display_message,"@Your troops flee in terror!",0xff4040), 
                  (call_script, "script_rout_allies"),
                  (assign,"$rout",1),
               (try_end),
     ]),



## script_flee
    ("flee_allies",
    [
(get_scene_boundaries, pos3, pos4),

(position_get_x,":xmin",pos3),
(position_get_y,":ymin",pos3),
(position_get_x,":xmax",pos4),
(position_get_y,":ymax",pos4),
   
   (val_div,":xmin",100),
   (val_div,":xmax",100),
   
(store_random_in_range,":xrout_point3",":xmin",":xmax"),
    (val_mul,":xrout_point3",100),
(store_random_in_range,":yrout_point3",":xmin",":xmax"),
(val_mul,":yrout_point3",100),
(store_random_in_range,":xrout_point4",":xmin",":xmax"),
(val_mul,":xrout_point4",100),
(store_random_in_range,":yrout_point4",":xmin",":xmax"),
(val_mul,":yrout_point4",100),

   (val_mul,":xmin",100),
   (val_mul,":xmax",100),

(val_add,":xrout_point3",":xmin"),
(val_add,":xrout_point3",":xmin"),
(val_add,":xrout_point3",":xmin"),
(val_div,":xrout_point3",4),
(position_set_x,pos3,":xrout_point3"),
(val_add,":yrout_point3",":ymin"),
(val_add,":yrout_point3",":ymin"),
(val_add,":yrout_point3",":ymin"),
(val_div,":yrout_point3",4),
(position_set_y,pos3,":yrout_point3"),

(val_add,":xrout_point4",":xmax"),
(val_add,":xrout_point4",":xmax"),
(val_add,":xrout_point4",":xmax"),
(val_div,":xrout_point4",4),
(position_set_x,pos4,":xrout_point4"),
(val_add,":yrout_point4",":ymax"),
(val_add,":yrout_point4",":ymax"),
(val_add,":yrout_point4",":ymax"),
(val_div,":yrout_point4",4),
(position_set_y,pos4,":yrout_point4"),


(store_skill_level,":leader","skl_leadership","trp_player"),
(try_for_agents,":agent"),
         (agent_is_alive,":agent"),
         (agent_is_human,":agent"),
         (agent_is_ally,":agent"),
         (store_agent_hit_points,":hitpoints",":agent",0),
(agent_get_troop_id,":troop_type", ":agent"),
(store_character_level, ":troop_level", ":troop_type"),
(val_div,":troop_level",10),
(val_add,":hitpoints",":troop_level"),
         (assign,":chance_ply",100),
         (val_sub,":chance_ply",":hitpoints"),
         (val_sub,":chance_ply",":leader"),
         (val_div,":chance_ply",2),
         (store_random_in_range,":routed",1,101),
              (try_begin),
                   (le,":routed",":chance_ply"),
#                  (display_message,"@One ally runs!"), 
                (agent_get_position,pos2,":agent"),
(position_move_z,pos2,200,0),
                         (agent_clear_scripted_mode,":agent"),
                         (agent_set_scripted_destination,":agent",pos4,1),
               (try_end),
(end_try),
     ]),

    ("flee_enemies",
    [
(get_scene_boundaries, pos3, pos4),

(position_get_x,":xmin",pos3),
(position_get_y,":ymin",pos3),
(position_get_x,":xmax",pos4),
(position_get_y,":ymax",pos4),
   
   (val_div,":xmin",100),
   (val_div,":xmax",100),
   
(store_random_in_range,":xrout_point3",":xmin",":xmax"),
    (val_mul,":xrout_point3",100),
(store_random_in_range,":yrout_point3",":xmin",":xmax"),
(val_mul,":yrout_point3",100),
(store_random_in_range,":xrout_point4",":xmin",":xmax"),
(val_mul,":xrout_point4",100),
(store_random_in_range,":yrout_point4",":xmin",":xmax"),
(val_mul,":yrout_point4",100),

   (val_mul,":xmin",100),
   (val_mul,":xmax",100),

(val_add,":xrout_point3",":xmin"),
(val_add,":xrout_point3",":xmin"),
(val_add,":xrout_point3",":xmin"),
(val_div,":xrout_point3",4),
(position_set_x,pos3,":xrout_point3"),
(val_add,":yrout_point3",":ymin"),
(val_add,":yrout_point3",":ymin"),
(val_add,":yrout_point3",":ymin"),
(val_div,":yrout_point3",4),
(position_set_y,pos3,":yrout_point3"),

(val_add,":xrout_point4",":xmax"),
(val_add,":xrout_point4",":xmax"),
(val_add,":xrout_point4",":xmax"),
(val_div,":xrout_point4",4),
(position_set_x,pos4,":xrout_point4"),
(val_add,":yrout_point4",":ymax"),
(val_add,":yrout_point4",":ymax"),
(val_add,":yrout_point4",":ymax"),
(val_div,":yrout_point4",4),
(position_set_y,pos4,":yrout_point4"),


(try_for_agents,":agent"),
         (agent_is_alive,":agent"),
         (agent_is_human,":agent"),
         (neg|agent_is_ally,":agent"),
         (store_agent_hit_points,":hitpoints",":agent",0),
(agent_get_troop_id,":troop_type", ":agent"),
(store_character_level, ":troop_level", ":troop_type"),
(val_div,":troop_level",10),
(val_add,":hitpoints",":troop_level"),
         (assign,":chance_ply",100),
         (val_sub,":chance_ply",":hitpoints"),
         (val_sub,":chance_ply",4),
         (val_div,":chance_ply",2),
         (store_random_in_range,":routed",1,101),
(try_begin),
                   (le,":routed",":chance_ply"),
#                  (display_message,"@One enemy runs!"), 
                (agent_get_position,pos2,":agent"),
(position_move_z,pos2,200,0),
                         (agent_clear_scripted_mode,":agent"),
                         (agent_set_scripted_destination,":agent",pos3,1),
               (try_end),
(end_try),
     ]),

## script_rout
    ("rout_allies",
    [
(get_scene_boundaries, pos3, pos4),

(position_get_x,":xmin",pos3),
(position_get_y,":ymin",pos3),
(position_get_x,":xmax",pos4),
(position_get_y,":ymax",pos4),
   
   (val_div,":xmin",100),
   (val_div,":xmax",100),
   
(store_random_in_range,":xrout_point3",":xmin",":xmax"),
    (val_mul,":xrout_point3",100),
(store_random_in_range,":yrout_point3",":xmin",":xmax"),
(val_mul,":yrout_point3",100),
(store_random_in_range,":xrout_point4",":xmin",":xmax"),
(val_mul,":xrout_point4",100),
(store_random_in_range,":yrout_point4",":xmin",":xmax"),
(val_mul,":yrout_point4",100),

   (val_mul,":xmin",100),
   (val_mul,":xmax",100),

(val_add,":xrout_point3",":xmin"),
(val_add,":xrout_point3",":xmin"),
(val_add,":xrout_point3",":xmin"),
(val_div,":xrout_point3",4),
(position_set_x,pos3,":xrout_point3"),
(val_add,":yrout_point3",":ymin"),
(val_add,":yrout_point3",":ymin"),
(val_add,":yrout_point3",":ymin"),
(val_div,":yrout_point3",4),
(position_set_y,pos3,":yrout_point3"),

(val_add,":xrout_point4",":xmax"),
(val_add,":xrout_point4",":xmax"),
(val_add,":xrout_point4",":xmax"),
(val_div,":xrout_point4",4),
(position_set_x,pos4,":xrout_point4"),
(val_add,":yrout_point4",":ymax"),
(val_add,":yrout_point4",":ymax"),
(val_add,":yrout_point4",":ymax"),
(val_div,":yrout_point4",4),
(position_set_y,pos4,":yrout_point4"),



(store_skill_level,":leader","skl_leadership","trp_player"),
(try_for_agents,":agent"),
         (agent_is_alive,":agent"),
         (agent_is_human,":agent"),
         (agent_is_ally,":agent"),
         (store_agent_hit_points,":hitpoints",":agent",0),
(agent_get_troop_id,":troop_type", ":agent"),
(store_character_level, ":troop_level", ":troop_type"),
(val_div,":troop_level",10),
         (val_div,":hitpoints",3),
         (assign,":chance_ply",100),
         (val_sub,":chance_ply",":hitpoints"),
         (val_sub,":chance_ply",":leader"),
         (val_sub,":chance_ply",":troop_level"),
         (store_random_in_range,":routed",1,101),
              (try_begin),
                   (le,":routed",":chance_ply"),
#                  (display_message,"@One ally runs!"), 
                (agent_get_position,pos2,":agent"),
(position_move_z,pos2,200,0),
                         (agent_clear_scripted_mode,":agent"),
                         (agent_set_scripted_destination,":agent",pos4,1),
               (try_end),
(end_try),
     ]),

    ("rout_enemies",
    [
(get_scene_boundaries, pos3, pos4),

(position_get_x,":xmin",pos3),
(position_get_y,":ymin",pos3),
(position_get_x,":xmax",pos4),
(position_get_y,":ymax",pos4),
   
   (val_div,":xmin",100),
   (val_div,":xmax",100),
   
(store_random_in_range,":xrout_point3",":xmin",":xmax"),
    (val_mul,":xrout_point3",100),
(store_random_in_range,":yrout_point3",":xmin",":xmax"),
(val_mul,":yrout_point3",100),
(store_random_in_range,":xrout_point4",":xmin",":xmax"),
(val_mul,":xrout_point4",100),
(store_random_in_range,":yrout_point4",":xmin",":xmax"),
(val_mul,":yrout_point4",100),

   (val_mul,":xmin",100),
   (val_mul,":xmax",100),

(val_add,":xrout_point3",":xmin"),
(val_add,":xrout_point3",":xmin"),
(val_add,":xrout_point3",":xmin"),
(val_div,":xrout_point3",4),
(position_set_x,pos3,":xrout_point3"),
(val_add,":yrout_point3",":ymin"),
(val_add,":yrout_point3",":ymin"),
(val_add,":yrout_point3",":ymin"),
(val_div,":yrout_point3",4),
(position_set_y,pos3,":yrout_point3"),

(val_add,":xrout_point4",":xmax"),
(val_add,":xrout_point4",":xmax"),
(val_add,":xrout_point4",":xmax"),
(val_div,":xrout_point4",4),
(position_set_x,pos4,":xrout_point4"),
(val_add,":yrout_point4",":ymax"),
(val_add,":yrout_point4",":ymax"),
(val_add,":yrout_point4",":ymax"),
(val_div,":yrout_point4",4),
(position_set_y,pos4,":yrout_point4"),


(try_for_agents,":agent"),
         (agent_is_alive,":agent"),
         (agent_is_human,":agent"),
         (neg|agent_is_ally,":agent"),
         (store_agent_hit_points,":hitpoints",":agent",0),
(agent_get_troop_id,":troop_type", ":agent"),
(store_character_level, ":troop_level", ":troop_type"),
(val_div,":troop_level",10),
         (val_div,":hitpoints",3),
         (assign,":chance_ply",100),
         (val_sub,":chance_ply",":hitpoints"),
         (val_sub,":chance_ply",3), ## AI's Leadership bonus
         (val_sub,":chance_ply",":troop_level"),
         (store_random_in_range,":routed",1,101),
(try_begin),
                   (le,":routed",":chance_ply"),
#                  (display_message,"@One enemy runs!"), 
                (agent_get_position,pos2,":agent"),
(position_move_z,pos2,200,0),
                         (agent_clear_scripted_mode,":agent"),
                         (agent_set_scripted_destination,":agent",pos3,1),
               (try_end),
(end_try),
    ]), 

 

  #script_coherence
    ("coherence",
    [
(get_scene_boundaries, pos3, pos4),
(assign,":num_allies",0),
(assign,":coh_allies",0),
(assign,":num_enemies",0),
(assign,":coh_enemies",0),
     (try_for_agents,":agent"),
         (agent_is_ally,":agent"),
         (agent_is_human,":agent"),
(store_agent_hit_points,":hitpoints",":agent",0),
(agent_get_troop_id,":troop_type", ":agent"),
(store_character_level, ":troop_level", ":troop_type"),
# (val_div,":troop_level",10),
(val_mul,":hitpoints",":troop_level"),
(val_add,":num_allies",":troop_level"),
         (val_add,":coh_allies",":hitpoints"),
      (else_try),
         (agent_is_human,":agent"),
(store_agent_hit_points,":hitpoints",":agent",0),
(agent_get_troop_id,":troop_type", ":agent"),
(store_character_level, ":troop_level", ":troop_type"),
# (val_div,":troop_level",10),
(val_mul,":hitpoints",":troop_level"),
(val_add,":num_enemies",":troop_level"),
         (val_add,":coh_enemies",":hitpoints"),
      (end_try),
(val_div,":coh_allies",":num_allies"),
(assign,"$allies_coh_base",":coh_allies"),
(assign,"$allies_coh","$allies_coh_base"),
(val_add,"$allies_coh","$new_kills"),
(val_div,":coh_enemies",":num_enemies"),
(assign,"$enemies_coh",":coh_enemies"),
     ]), 


  #script_hero_exp_penalty
    ("hero_exp_penalty",
    [(store_character_level,":level","trp_player"),
     (val_mul,":level",-20),
     (add_xp_to_troop,":level","trp_player"),
     (assign,reg1,":level"),
       (display_message, "@You lost {reg1} experience points.",0x8fbc8f),     
     ]),

  
# NE end settings	 
  
  # script_custom_battle_end
  # Input: none
  # Output: none
  ("custom_battle_end",
    [
      (assign, "$g_custom_battle_team1_death_count", 0),
      (assign, "$g_custom_battle_team2_death_count", 0),
      (get_player_agent_no, ":player_agent"),
      (agent_get_team, ":player_team", ":player_agent"),
      (try_for_agents, ":cur_agent"),
        (agent_is_human, ":cur_agent"),
        (neg|agent_is_alive, ":cur_agent"),
        (agent_get_team, ":cur_team", ":cur_agent"),
        (try_begin),
          (eq, ":cur_team", ":player_team"),
          (val_add, "$g_custom_battle_team1_death_count", 1),
        (else_try),
          (val_add, "$g_custom_battle_team2_death_count", 1),
        (try_end),
      (try_end),
      ]),  

# NE settings

## Shield bash code start - Modified by Jinnai
 ("cf_agent_shield_bash",
    [(store_script_param, ":agent",1),
     (agent_get_position,pos1,":agent"),
     (agent_set_animation, ":agent", "anim_release_bash"),
     (agent_play_sound,":agent","snd_man_grunt"),
     (agent_get_team,":team1",":agent"),
     (assign,":victim",-1),
     (try_for_agents,":possible_victim"),
        (agent_is_alive,":possible_victim"),
        (agent_is_human,":possible_victim"),
        (neq,":possible_victim",":agent"),
        (agent_get_team,":team2",":possible_victim"),
        (neq,":team1",":team2"),
        (agent_get_class ,":class", ":possible_victim"),
        (neq,":class",grc_cavalry),
        (agent_get_position,pos2,":possible_victim"),
        (get_distance_between_positions,":dist",pos1,pos2),
        (lt,":dist",150),
        (neg|position_is_behind_position,pos2,pos1),
        (assign,":victim",":possible_victim"),
     (end_try),
     (gt,":victim",-1),
     (store_random_in_range,":rand",0,2),
     (store_agent_hit_points,":hp",":victim",1),
     (val_sub,":hp",":rand"),
     (store_random_in_range,":hit_reaction",1,101),
     (store_skill_level,":a_shield",skl_shield,":victim"),
     (store_skill_level,":v_shield",skl_shield,":agent"),   
     (try_begin),
         (gt,":hp",0),
         (agent_set_hit_points,":victim",":hp",1),
         (agent_play_sound,":agent","snd_shield_hit_wood_wood"),
         (agent_play_sound,":victim","snd_blunt_hit"),
         (try_begin),      
           (gt,":a_shield", ":v_shield"),
              (try_begin),      
                (is_between,":hit_reaction",0,10),   
                (agent_set_animation, ":victim", "anim_bash_unsuccessful"),
				# (display_message, "@You attempt a shield bash but miss!"),     
              (else_try),      
                (is_between,":hit_reaction",11,20),   
                (agent_set_animation, ":victim", "anim_bash_crouch"),         
				# (display_message, "@You merely scrape your opponent!"),  
              (else_try),
                (is_between,":hit_reaction",21,30),   
                (agent_set_animation, ":victim", "anim_bash_mini_stun"),
				# (display_message, "@You momentarily stun your opponent!"),  
              (else_try),
                (is_between,":hit_reaction",21,79),   
                (agent_set_animation, ":victim", "anim_bash_stun"),    
                # (display_message, "@You stun your opponent!"),  				
              (else_try),
                (is_between,":hit_reaction",80,100),   
                (agent_set_animation, ":victim", "anim_bash_knocked"),
				# (display_message, "@You knock down your opponent!"),  
              (end_try),            
         (else_try),
           (lt,":a_shield", ":v_shield"),
              (try_begin),      
                (is_between,":hit_reaction",0,20),   
                (agent_set_animation, ":victim", "anim_bash_unsuccessful"),
				#(display_message, "@You attempt a shield bash but miss!"),  
              (else_try),      
                (is_between,":hit_reaction",21,42),   
                (agent_set_animation, ":victim", "anim_bash_crouch"),   
                # (display_message, "@You merely scrape your opponent!"),  				
              (else_try),
                (is_between,":hit_reaction",43,65),   
                (agent_set_animation, ":victim", "anim_bash_mini_stun"),
				# (display_message, "@You momentarily stun your opponent!"),  
              (else_try),
                (is_between,":hit_reaction",66,92),   
                (agent_set_animation, ":victim", "anim_bash_stun"),     
			    # (display_message, "@You stun your opponent!"), 		
              (else_try),
                (is_between,":hit_reaction",93,100),   
                (agent_set_animation, ":victim", "anim_bash_knocked"),
				# (display_message, "@You knock down your opponent!"),  
              (end_try),
         (else_try),
           (eq,":a_shield", ":v_shield"),
              (try_begin),      
                (is_between,":hit_reaction",0,16),   
                (agent_set_animation, ":victim", "anim_bash_unsuccessful"),
				# (display_message, "@You attempt a shield bash but miss!"), 
              (else_try),      
                (is_between,":hit_reaction",17,33),   
                (agent_set_animation, ":victim", "anim_bash_crouch"),    
                # (display_message, "@You merely scrape your opponent!"),  				
              (else_try),
                (is_between,":hit_reaction",34,50),   
                (agent_set_animation, ":victim", "anim_bash_mini_stun"),
				# (display_message, "@You momentarily stun your opponent!"),  
              (else_try),
                (is_between,":hit_reaction",51,89),   
                (agent_set_animation, ":victim", "anim_bash_stun"),    
			    # (display_message, "@You stun your opponent!"), 
              (else_try),
                (is_between,":hit_reaction",90,100),   
                (agent_set_animation, ":victim", "anim_bash_knocked"),
				# (display_message, "@You knock down your opponent!"),  
              (end_try),
         (end_try),      
     (else_try),
         (agent_play_sound,":agent","snd_shield_hit_wood_wood"),
         (agent_play_sound,":victim","snd_blunt_hit"),
         (agent_deliver_damage_to_agent,":agent",":victim"),
     (end_try),
   ]), 
## Shield bash code end

# ne end settings	  
	  
  # script_remove_troop_from_prison
  # Input: troop_no
  # Output: none
  #Other search terms: release, peace
  
  ("remove_troop_from_prison",
    [
      (store_script_param, ":troop_no", 1),
      (troop_set_slot, ":troop_no", slot_troop_prisoner_of_party, -1),
      (try_begin),
        (eq, "$do_not_cancel_quest", 0),      
        (check_quest_active, "qst_rescue_lord_by_replace"),
        (quest_slot_eq, "qst_rescue_lord_by_replace", slot_quest_target_troop, ":troop_no"),        
        (call_script, "script_cancel_quest", "qst_rescue_lord_by_replace"),
      (try_end),
      (try_begin),
        (eq, "$do_not_cancel_quest", 0),      
        (check_quest_active, "qst_rescue_prisoner"),
        (quest_slot_eq, "qst_rescue_prisoner", slot_quest_target_troop, ":troop_no"),        
        (call_script, "script_cancel_quest", "qst_rescue_prisoner"),
      (try_end),
      (try_begin),
        (check_quest_active, "qst_deliver_message_to_prisoner_lord"),
        (quest_slot_eq, "qst_deliver_message_to_prisoner_lord", slot_quest_target_troop, ":troop_no"),
        (call_script, "script_cancel_quest", "qst_deliver_message_to_prisoner_lord"),
      (try_end),
      ]),

  # script_debug_variables
  # Input: two variables which will be examined by coder, this script is only for debugging.
  # Output: none
  ("debug_variables",
    [
      (store_script_param, ":unused", 1),
      (store_script_param, ":unused_2", 2),
    ]),        
        
#lord recruitment scripts begin	  
  ("troop_describes_troop_to_s15",
  [
	(store_script_param, ":troop_1", 1),
	(store_script_param, ":troop_2", 2),

	
	(str_store_troop_name, s15, ":troop_2"),
	
	(try_begin),
		(eq, ":troop_2", "trp_player"),
		(str_store_string, s15, "str_you"),
	(else_try),	
		(eq, ":troop_2", ":troop_1"),
		(str_store_string, s15, "str_myself"),
	(else_try),
		(call_script, "script_troop_get_family_relation_to_troop", ":troop_2", ":troop_1"),
		(gt, reg0, 0),
		(str_store_string, s15, "str_my_s11_s15"),
	(else_try),	
		(call_script, "script_troop_get_relation_with_troop", ":troop_2", ":troop_1"),
		(ge, reg0, 20),
		(str_store_string, s15, "str_my_friend_s15"),
	(try_end),	
	
	]),
	
  ("troop_describes_quarrel_with_troop_to_s14",
  #perhaps replace this with get_relevant_comment at a later date
    [
	(store_script_param, ":troop", 1),
	(store_script_param, ":troop_2", 2),

	(str_store_troop_name, s15, ":troop"),
	(str_store_troop_name, s16, ":troop_2"),

	(str_store_string, s14, "str_stop_gap__s15_is_the_rival_of_s16"),
	
	(try_begin),
		(eq, ":troop", "$g_talk_troop"),
		(call_script, "script_cf_test_lord_incompatibility_to_s17", ":troop", ":troop_2"),
		(str_store_string, s14, s17),
	(else_try),	
		(eq, ":troop_2", "$g_talk_troop"),
		(call_script, "script_cf_test_lord_incompatibility_to_s17", ":troop_2", ":troop"),
		(str_store_string, s14, s17),
	(else_try),
		(str_store_string, s14, "str_general_quarrel"),
	(try_end),
	
]),

  ("cf_test_lord_incompatibility_to_s17", #writes rivalry chance to reg0
    [

	(store_script_param, ":source_lord", 1),
	(store_script_param, ":target_lord", 2),
	
	
	(assign, ":chance_of_rivalry", 0),
	
	(troop_get_slot, ":source_reputation", ":source_lord", slot_lord_reputation_type),
	(troop_get_slot, ":target_reputation", ":target_lord", slot_lord_reputation_type),
	
	(troop_get_type, reg15, ":target_lord"),
	
	(str_store_troop_name, s18, ":target_lord"),
	
	(assign, ":divisor", 1),
	
	(call_script, "script_troop_get_family_relation_to_troop", ":target_lord", ":source_lord"),
	(assign, ":family_relationship", reg0),
	
	(try_begin),
		(gt, ":family_relationship", 0),
		(store_div, ":family_divisor", reg0, 5),
		(val_add, ":divisor", ":family_divisor"),
		(str_store_string, s18, "str_my_s11_s18"),
	(else_try),
		(gt, ":target_reputation", lrep_upstanding),
		(this_or_next|eq, ":source_reputation", lrep_debauched),
			(eq, ":source_reputation", lrep_selfrighteous),
		(str_store_string, s18, "str_the_socalled_s11_s18"),
	(try_end),	

	
	(try_begin), #test if reps are compatible
        (eq, ":source_reputation", lrep_martial),
		(is_between, ":family_relationship", 1, 5), #uncles and cousins
		
		(assign, ":chance_of_rivalry", 100),
        (str_store_string, s17, "str_s18_would_cheat_me_of_my_inheritance_by_heaven_i_know_my_rights_and_im_not_going_to_back_down"), 
	(else_try),
        (eq, ":source_reputation", lrep_martial),
        (eq, ":target_reputation", lrep_quarrelsome),
        (str_store_string, s17, "str_s18_once_questioned_my_honour_and_my_bravery_i_long_for_the_day_when_i_can_meet_him_in_battle_and_make_him_retract_his_statement"),
		(assign, ":chance_of_rivalry", 50),

	(else_try),
        (eq, ":source_reputation", lrep_martial),
        (eq, ":target_reputation", lrep_upstanding),
        (str_store_string, s17, "str_s18_once_questioned_my_judgment_in_battle_by_heaven_would_he_have_us_shirk_our_duty_to_smite_our_sovereigns_foes"),
		(assign, ":chance_of_rivalry", 50),

	(else_try),
        (eq, ":target_reputation", lrep_martial),
		(is_between, ":family_relationship", 1, 5),
		
		(assign, ":chance_of_rivalry", 100),
        (str_store_string, s17, "str_s18_seems_to_think_he_has_the_right_to_some_of_my_property_well_he_does_not"), 
		
	(else_try),
        (eq, ":source_reputation", lrep_quarrelsome),
        (eq, ":target_reputation", lrep_martial),
        (str_store_string, s17, "str_s18_once_took_something_i_said_amiss_stubborn_bastard_wont_give_it_up_and_keeps_trying_to_get_me_to_recant_my_words"), 
		(assign, ":chance_of_rivalry", 50),

	(else_try),
        (eq, ":source_reputation", lrep_quarrelsome),
        (eq, ":target_reputation", lrep_cunning),
        (str_store_string, s17, "str_s18_is_a_crafty_weasel_and_i_dont_trust_him_one_bit"), 
		(assign, ":chance_of_rivalry", 100),

		
    (else_try),
        (eq, ":source_reputation", lrep_debauched),
        (eq, ":target_reputation", lrep_upstanding),
		(str_store_string, s17, "str_s18_i_despite_him_he_puts_on_such_a_nauseating_display_of_virtue_and_thinks_nothing_of_insulting_his_betters"),
		(assign, ":chance_of_rivalry", 100),

        #debauched insults upstanding

    (else_try),
        (eq, ":source_reputation", lrep_debauched),
        (eq, ":target_reputation", lrep_selfrighteous),
		(str_store_string, s17, "str_s18_entered_into_a_little_deal_with_me_and_is_now_trying_to_wriggle_out_of_it"),
		(assign, ":chance_of_rivalry", 100),

        #debauched insults selfrighteous

		
		
    (else_try),
        (eq, ":source_reputation", lrep_selfrighteous),
        (eq, ":target_reputation", lrep_debauched),
		(str_store_string, s17, "str_s18_once_ran_an_errand_for_me_and_now_thinks_i_owe_him_something_i_owe_his_ilk_nothing"),
		(assign, ":chance_of_rivalry", 100),
        #selfrighteous dismisses debauched
		
    (else_try),
        (eq, ":source_reputation", lrep_selfrighteous),
        (eq, ":target_reputation", lrep_goodnatured),
		(str_store_string, s17, "str_s18_is_soft_and_weak_and_not_fit_to_govern_a_fief_and_i_have_always_detested_him"),
		(assign, ":chance_of_rivalry", 100),
             

			 
	(else_try),
        (eq, ":source_reputation", lrep_cunning),
        (eq, ":target_reputation", lrep_quarrelsome),
        (str_store_string, s17, "str_s18_is_a_quarrelsome_oaf_and_a_liability_in_my_opinion_and_ive_let_him_know_as_much"), 
		(assign, ":chance_of_rivalry", 100),
        #cunning insults quarrelsome

	(else_try),
        (eq, ":source_reputation", lrep_cunning),
        (eq, ":target_reputation", lrep_goodnatured),
        (str_store_string, s17, "str_s18_i_am_sorry_to_say_is_far_too_softhearted_a_man_to_be_given_any_kind_of_responsibility_his_chivalry_will_allow_the_enemy_to_flee_to_fight_another_day_and_will_cost_the_lives_of_my_own_faithful_men"), 
		(assign, ":chance_of_rivalry", 100),
		

	(else_try),
        (eq, ":source_reputation", lrep_goodnatured),
        (eq, ":target_reputation", lrep_cunning),
        (str_store_string, s17, "str_s18_seems_to_have_something_against_me_for_some_reason_i_dont_like_to_talk_ill_of_people_but_i_think_hes_can_be_a_bit_of_a_cad_sometimes"), 
		(assign, ":chance_of_rivalry", 100),
		
	(else_try),
        (eq, ":source_reputation", lrep_goodnatured),
        (eq, ":target_reputation", lrep_selfrighteous),
        (str_store_string, s17, "str_s18_has_always_treated_me_contemptuously_although_i_have_done_him_no_wrong"), 
		(assign, ":chance_of_rivalry", 100),
		
		

	(else_try),
        (eq, ":source_reputation", lrep_upstanding),
        (eq, ":target_reputation", lrep_debauched),
        (str_store_string, s17, "str_s18_is_thoroughly_dishonorable_and_a_compulsive_spinner_of_intrigues_which_i_fear_will_drag_us_into_wars_or_incite_rebellions"), 
		(assign, ":chance_of_rivalry", 50),

	(else_try),
        (eq, ":source_reputation", lrep_upstanding),
        (eq, ":target_reputation", lrep_martial),
        (str_store_string, s17, "str_s18_disappoints_me_i_once_scolded_for_his_rashness_in_battle_and_he_took_offense_i_do_not_care_to_apologize_for_my_efforts_to_save_his_life_and_the_lives_of_his_men"), 
		(assign, ":chance_of_rivalry", 50),

	#for commons	
	(else_try),
        (this_or_next|eq, ":source_reputation", lrep_upstanding),
		(this_or_next|eq, ":source_reputation", lrep_martial),
			(eq, ":source_reputation", lrep_selfrighteous),
        (eq, ":target_reputation", lrep_roguish),
        (str_store_string, s17, "str_s18_squanders_money_and_carouses_in_a_way_most_unbefitting_a_noble_by_doing_so_he_disgraces_us_all"), 
		(assign, ":chance_of_rivalry", 100),

		
	(else_try),
        (eq, ":source_reputation", lrep_roguish),
        (this_or_next|eq, ":target_reputation", lrep_upstanding),
		(this_or_next|eq, ":target_reputation", lrep_martial),
			(eq, ":target_reputation", lrep_selfrighteous),
        (str_store_string, s17, "str_s18_has_been_speaking_ill_of_me_behind_my_back_or_so_they_say"), 
		(assign, ":chance_of_rivalry", 100),


	(else_try),
        (this_or_next|eq, ":source_reputation", lrep_quarrelsome),
		(this_or_next|eq, ":source_reputation", lrep_martial),
			(eq, ":source_reputation", lrep_selfrighteous),
        (eq, ":target_reputation", lrep_custodian),
        (str_store_string, s17, "str_s18_is_a_disgrace_reg3shehe_consorts_with_merchants_lends_money_at_interest_uses_coarse_language_and_shows_no_attempt_to_uphold_the_dignity_of_the_honor_bestowed_upon_reg3herhim"), 
		(assign, ":chance_of_rivalry", 100),

	(else_try),
        (eq, ":source_reputation", lrep_custodian),
		(this_or_next|eq, ":target_reputation", lrep_quarrelsome),
		(this_or_next|eq, ":target_reputation", lrep_martial),
			(eq, ":target_reputation", lrep_selfrighteous),
        (str_store_string, s17, "str_s18_has_condemned_me_for_engaging_in_commerce_what_could_possibly_be_wrong_with_that"), 
		(assign, ":chance_of_rivalry", 100),

		
	(else_try),
        (this_or_next|eq, ":source_reputation", lrep_debauched),
		(this_or_next|eq, ":source_reputation", lrep_martial),
			(eq, ":source_reputation", lrep_selfrighteous),
        (eq, ":target_reputation", lrep_benefactor),
        (str_store_string, s17, "str_s18_i_have_heard_has_been_encouraging_seditious_ideas_among_the_peasantry__a_foolish_move_which_endangers_us_all"), 
		(assign, ":chance_of_rivalry", 100),
		
		
	(else_try),
        (eq, ":source_reputation", lrep_benefactor),
		(this_or_next|eq, ":target_reputation", lrep_debauched),
		(this_or_next|eq, ":target_reputation", lrep_martial),
			(eq, ":target_reputation", lrep_selfrighteous),
        (str_store_string, s17, "str_s18_has_called_me_out_for_the_way_i_deal_with_my_tenants_well_so_be_it_if_i_teach_them_that_they_are_the_equal_of_anyone_with_socalled_gentle_blood_what_is_it_to_reg3herhim"), 
		(assign, ":chance_of_rivalry", 100),


	#lady incompatibilities	
	(else_try),	
		(eq, ":source_reputation", lrep_conventional),
		(this_or_next|eq, ":target_reputation", lrep_martial),
			(eq, ":target_reputation", lrep_selfrighteous),
        (str_store_string, s17, "str_a_most_gallant_gentleman_who_knows_how_to_treat_a_lady"), 
		(assign, ":chance_of_rivalry", -50),

	(else_try),	
		(eq, ":source_reputation", lrep_conventional),
		(eq, ":target_reputation", lrep_quarrelsome),
        (str_store_string, s17, "str_a_base_cad"), 
		(assign, ":chance_of_rivalry", 50),
	
		
	(else_try),	
		(eq, ":source_reputation", lrep_adventurous),
		(eq, ":target_reputation", lrep_cunning),
        (str_store_string, s17, "str_a_man_who_treats_me_as_his_equal_which_is_rare"), 
		(assign, ":chance_of_rivalry", -50),

	(else_try),	
		(eq, ":source_reputation", lrep_adventurous),
		(this_or_next|eq, ":target_reputation", lrep_martial),
			(eq, ":target_reputation", lrep_debauched),
		(str_store_string, s17, "str_appears_to_value_me_with_his_estate_and_his_horse_as_prizes_worth_having"), 
		(assign, ":chance_of_rivalry", 50),

	(else_try),	
		(eq, ":source_reputation", lrep_adventurous),
		(neq, ":target_reputation", lrep_goodnatured),
		
        (str_store_string, s17, "str_a_bit_dull_but_what_can_you_expect"), 
		(assign, ":chance_of_rivalry", 10),

	(else_try),	
		(eq, ":source_reputation", lrep_otherworldly),
		(call_script, "script_troop_get_romantic_chemistry_with_troop", ":source_lord", ":target_lord"),
		(ge, reg0, 10),
        (str_store_string, s17, "str_the_man_whom_destiny_intends_for_me"), 
		(assign, ":chance_of_rivalry", -50),

	(else_try),	
		(eq, ":source_reputation", lrep_otherworldly),
		(lt, reg0, 0),
		
        (str_store_string, s17, "str_is_not_right_for_me__i_cannot_say_why_but_he_makes_my_skin_crawl"), 
		(assign, ":chance_of_rivalry", 50),

		
	(else_try),	
		(eq, ":source_reputation", lrep_ambitious),
		(this_or_next|eq, ":target_reputation", lrep_selfrighteous),
			(eq, ":target_reputation", lrep_cunning),
        (str_store_string, s17, "str_is_a_man_who_clearly_intends_to_make_his_mark_in_the_world"), 
		(assign, ":chance_of_rivalry", -20),

	(else_try),	
		(eq, ":source_reputation", lrep_ambitious),
		(eq, ":target_reputation", lrep_goodnatured),
		
        (str_store_string, s17, "str_is_a_layabout_a_naif_prey_for_others_who_are_cleverer_than_he"), 
		(assign, ":chance_of_rivalry", 30),

				
	(else_try),	
		(eq, ":source_reputation", lrep_moralist),
		(eq, ":target_reputation", lrep_upstanding),
		
        (str_store_string, s17, "str_is_a_man_of_stalwart_character"), 
		(assign, ":chance_of_rivalry", -50),

	(else_try),	
		(eq, ":source_reputation", lrep_moralist),
		(this_or_next|eq, ":target_reputation", lrep_debauched),
			(eq, ":target_reputation", lrep_cunning),
			
        (str_store_string, s17, "str_appears_to_be_a_man_of_low_morals"), 
		(assign, ":chance_of_rivalry", 50),

	(else_try),	
		(eq, ":source_reputation", lrep_moralist),
		(eq, ":target_reputation", lrep_quarrelsome),
		
        (str_store_string, s17, "str_appears_to_be_a_man_who_lacks_selfdiscipline"), 
		(assign, ":chance_of_rivalry", 50),
		
	(else_try),

	
    (try_end),

	(val_div, ":chance_of_rivalry", ":divisor"),

	(assign, reg0, ":chance_of_rivalry"),

	(neq, ":chance_of_rivalry", 0),
#	(eq, ":incompatibility_found", 1), #cf can be removed with this
	
	]),

  ("troop_get_romantic_chemistry_with_troop", #source is lady, target is man
    [
      (store_script_param, ":source_lady", 1),
      (store_script_param, ":target_lord", 2),
      
      (store_add, ":chemistry_sum", ":source_lady", ":target_lord"),
      (val_add, ":chemistry_sum", "$romantic_attraction_seed"),      
      
      #This calculates (modula ^ 2) * 3 
      (store_mod, ":chemistry_remainder", ":chemistry_sum", 5),
      (val_mul, ":chemistry_remainder", ":chemistry_remainder"), #0, 1, 4, 9, 16
      (val_mul, ":chemistry_remainder", 3), #0, 3, 12, 27, 48
      
      (store_attribute_level, ":romantic_chemistry", ":target_lord", ca_charisma),
      (val_sub, ":romantic_chemistry", ":chemistry_remainder"),
      
      (val_mul, ":romantic_chemistry", 2),
      (assign, reg0, ":romantic_chemistry"), 
      
      #examples : 
      #For a charisma of 18, yields (18 - 0) * 2 = 36, (18 - 3) * 2 = 30, (18 - 12) * 2 = 12, (18 - 27) * 2 = -18, (18 - 48) * 2 = -60
      #For a charisma of 10, yields (10 - 0) * 2 = 20, (10 - 3) * 2 = 14, (10 - 12) * 2 = -4, (10 - 27) * 2 = -34, (10 - 48) * 2 = -76
      #For a charisma of 7, yields  (7 - 0) * 2 = 14,  (7 - 3) * 2 = 8,   (7 - 12) * 2 = -10, (7 - 27) * 2 = -40,  (7 - 48) * 2 = -82
      
      #15 is high attraction, 0 is moderate attraction, -76 is lowest attraction
	]),
	

  ("cf_troop_get_romantic_attraction_to_troop", #source is lady, target is man
    [	

	(store_script_param, ":source_lady", 1),
	(store_script_param, ":target_lord", 2),

	(assign, ":weighted_romantic_assessment", 0),	

	(troop_get_type, ":source_is_female", ":source_lady"),
	(eq, ":source_is_female", 1),
	(troop_get_type, ":target_is_female", ":target_lord"),
	(eq, ":target_is_female", 0),
	
	(call_script, "script_troop_get_romantic_chemistry_with_troop", ":source_lady", ":target_lord"),
	(assign, ":romantic_chemistry", reg0),

	
	#objective attraction - average renown
	(troop_get_slot, ":modified_renown", ":target_lord", slot_troop_renown),
	(assign, ":lady_status", 60),
	(val_div, ":modified_renown", 5),
	(val_sub, ":modified_renown", ":lady_status"),
	(val_min, ":modified_renown", 60),


	
	#weight values
	(try_begin),
		(assign, ":personality_match", 0),
		(call_script, "script_cf_test_lord_incompatibility_to_s17", ":source_lady", ":target_lord"),
		(store_sub, ":personality_match", 0, reg0),
	(try_end),
	
	(troop_get_slot, ":lady_reputation", ":source_lady", slot_lord_reputation_type),
	(try_begin),
		(eq, ":lady_reputation", lrep_ambitious),
		(val_mul, ":modified_renown", 2),
		(val_div, ":romantic_chemistry", 2),
	(else_try),
		(eq, ":lady_reputation", lrep_otherworldly),
		(val_div, ":modified_renown", 2),
		(val_mul, ":romantic_chemistry", 2),
	(else_try),
		(eq, ":lady_reputation", lrep_adventurous),
		(val_div, ":modified_renown", 2),
	(else_try),
		(eq, ":lady_reputation", lrep_moralist),
		(val_div, ":modified_renown", 2),
		(val_div, ":romantic_chemistry", 2),
	(try_end),

	(val_add, ":weighted_romantic_assessment", ":romantic_chemistry"),
	(val_add, ":weighted_romantic_assessment", ":personality_match"),
	(val_add, ":weighted_romantic_assessment", ":modified_renown"),
	
	(assign, reg0, ":weighted_romantic_assessment"),
	
	]),	
	
	
  ("cf_random_political_event", #right now, just enmities
    [
	
	(store_random_in_range, ":lord_1", active_npcs_begin, active_npcs_end),
	(store_random_in_range, ":lord_2", active_npcs_begin, active_npcs_end),

	(troop_slot_eq, ":lord_1", slot_troop_occupation, slto_kingdom_hero),
	(troop_slot_eq, ":lord_2", slot_troop_occupation, slto_kingdom_hero),

	(neq, ":lord_1", ":lord_2"),
	
	(val_add, "$total_political_events", 1),
					
	(store_troop_faction, ":lord_1_faction", ":lord_1"),
	(store_troop_faction, ":lord_2_faction", ":lord_2"),
	
	(assign, reg8, "$total_political_events"),
	
	
	(faction_get_slot, ":faction_1_leader", ":lord_1_faction", slot_faction_leader),
	(faction_get_slot, ":faction_2_leader", ":lord_2_faction", slot_faction_leader),
	
	(this_or_next|eq, ":lord_1_faction", ":lord_2_faction"),
	(this_or_next|eq, ":lord_1", ":faction_1_leader"),
		(eq, ":lord_2", ":faction_2_leader"),
	
	
	(call_script, "script_troop_get_relation_with_troop", ":lord_1", ":lord_2"),
	(assign, ":relation", reg0),
	

	(store_random_in_range, ":random", 0, 100),
		
	(try_begin),
		#reconciliation
		#The chance of a liege reconciling two quarreling vassals is equal to (relationship with lord 1 x relationship with lord 2) / 4
		
		(eq, ":lord_1_faction", ":lord_2_faction"),
		(neq, ":faction_1_leader", "trp_player"),
		
		(le, ":relation", -10),
		
#		(ge, "$total_political_events", 5000),

		(call_script, "script_troop_get_relation_with_troop", ":lord_1", ":faction_1_leader"),
		(gt, reg0, 0),
		(assign, ":lord_1_leader_rel", reg0),
		
		(call_script, "script_troop_get_relation_with_troop", ":lord_2", ":faction_1_leader"),
		(gt, reg0, 0),
		(store_mul, ":reconciliation_chance", ":lord_1_leader_rel", reg0),		
		(val_div, ":reconciliation_chance", 4),	#was 2 before	
				
		(le, ":random", ":reconciliation_chance"), 
		
		(str_store_troop_name, s4, ":faction_1_leader"),
		(str_store_troop_name, s5, ":lord_1"),
		(str_store_troop_name, s6, ":lord_2"),
		(try_begin),
			(eq, "$cheat_mode", 1),
			(display_message, "str_check_reg8_s4_reconciles_s5_and_s6_"),
		(try_end),
		
		(call_script, "script_troop_change_relation_with_troop", ":lord_1", ":lord_2", 20),
		(val_add, "$total_random_quarrel_changes", 20),
	(else_try),	#lord intervenes in quarrel
		(eq, ":lord_1_faction", ":lord_2_faction"),

		(le, ":relation", -10),
#		(ge, ":random", 50),
		(try_begin),
			(eq, ":faction_1_leader", "trp_player"),
			(try_begin),
				(eq, "$cheat_mode", 1),
				(display_message, "str_diagnostic__player_should_receive_consultation_quest_here_if_not_already_active"),
			(try_end),
			(neg|check_quest_active, "qst_consult_with_minister"),
			(neg|check_quest_active, "qst_resolve_dispute"),
			(eq, "$g_minister_notification_quest", 0),
			(assign, "$g_minister_notification_quest", "qst_resolve_dispute"),
			(quest_set_slot, "qst_resolve_dispute", slot_quest_target_troop, ":lord_1"),
			(quest_set_slot, "qst_resolve_dispute", slot_quest_object_troop, ":lord_2"),
			
			(call_script, "script_add_notification_menu", "mnu_notification_player_should_consult", 0, 0),
			
			
		(else_try),
			(call_script, "script_troop_get_relation_with_troop", ":lord_1", ":faction_1_leader"),
			(assign, ":lord_1_rel_w_leader", reg0),
			
			(call_script, "script_troop_get_relation_with_troop", ":lord_2", ":faction_1_leader"),
			(assign, ":lord_2_rel_w_leader", reg0),
			
			(store_random_in_range, ":another_random", -5, 5),

			(val_add, ":lord_1_rel_w_leader", ":another_random"),
			
			(try_begin),
				(ge, ":lord_1_rel_w_leader", ":lord_2_rel_w_leader"),
				(assign, ":winner_lord", ":lord_1"),
				(assign, ":loser_lord", ":lord_2"),
			(else_try),
				(assign, ":loser_lord", ":lord_1"),
				(assign, ":winner_lord", ":lord_2"),
			(try_end),
			
			(str_store_troop_name, s4, ":faction_1_leader"),
			(str_store_troop_name, s5, ":winner_lord"),
			(str_store_troop_name, s6, ":loser_lord"),

			(try_begin),
				(eq, "$cheat_mode", 1),
				(display_message, "str_check_reg8_s4_rules_in_s5s_favor_in_quarrel_with_s6_"),
			(try_end), 
			 
			(call_script, "script_add_log_entry", logent_ruler_intervenes_in_quarrel, ":faction_1_leader",  ":loser_lord", ":winner_lord", ":lord_1_faction"), #faction leader is actor, loser lord is center object, winner lord is troop_object
			
			(call_script, "script_troop_change_relation_with_troop", ":winner_lord", ":faction_1_leader", 10),
			(call_script, "script_troop_change_relation_with_troop", ":loser_lord", ":faction_1_leader", -20),
			(val_add, "$total_random_quarrel_changes", -10),

		(try_end),

		
	(else_try), #new quarrel - companions
		(is_between, ":lord_1", companions_begin, companions_end),
		(is_between, ":lord_2", companions_begin, companions_end),
		
		(ge, ":relation", -10), 		
		(this_or_next|troop_slot_eq, ":lord_1", slot_troop_personalityclash_object, ":lord_2"),
			(troop_slot_eq, ":lord_1", slot_troop_personalityclash2_object, ":lord_2"),
		
		(str_store_troop_name, s5, ":lord_1"),
		(str_store_troop_name, s6, ":lord_2"),
		
		(try_begin),
			(eq, "$cheat_mode", 1),
			(display_message, "str_check_reg8_new_rivalry_generated_between_s5_and_s6"),
		(try_end),
		
		(call_script, "script_troop_change_relation_with_troop", ":lord_1", ":lord_2", -30),
		(val_add, "$total_random_quarrel_changes", -30),
				
		
	(else_try), #new quarrel - others
		(eq, ":lord_1_faction", ":lord_2_faction"),

		(ge, ":relation", -10), #can have two quarrels

		(call_script, "script_cf_test_lord_incompatibility_to_s17", ":lord_1", ":lord_2"),
		(assign, ":chance_of_enmity", reg0),
		(gt, ":chance_of_enmity", 0),
	
	
		(lt, ":random", ":chance_of_enmity"), #50 or 100 percent, usually
	
	
		(str_store_troop_name, s5, ":lord_1"),
		(str_store_troop_name, s6, ":lord_2"),
		(try_begin),
			(eq, "$cheat_mode", 1),
			(display_message, "str_check_reg8_new_rivalry_generated_between_s5_and_s6"),
		(try_end),
		
		(call_script, "script_troop_change_relation_with_troop", ":lord_1", ":lord_2", -30),
		(val_add, "$total_random_quarrel_changes", -30),

#		(call_script, "script_update_troop_notes", ":lord_1"),
#		(call_script, "script_update_troop_notes", ":lord_2"),
	(else_try), #a lord attempts to suborn a character
		(store_current_hours, ":hours"),
		(ge, ":hours", 24),
	
		(neq, ":lord_1_faction", ":lord_2_faction"),
#		(eq, ":lord_1", ":faction_1_leader"),
		(is_between, ":lord_1_faction", kingdoms_begin, kingdoms_end),
		
		(call_script, "script_cf_troop_can_intrigue", ":lord_2", 0),
		(neq, ":lord_2", ":faction_2_leader"),
		(neq, ":lord_2", ":faction_1_leader"),
		
		(str_store_troop_name, s5, ":faction_1_leader"),
		(str_store_troop_name, s6, ":lord_2"),		

		(try_begin),
			(ge, "$cheat_mode", 1),
			(display_message, "str_check_reg8_s5_attempts_to_win_over_s6"),
		(try_end),
			
		(call_script, "script_calculate_troop_political_factors_for_liege", ":lord_2", ":faction_1_leader"),
		(assign, ":lord_1_score", reg0),

		(call_script, "script_calculate_troop_political_factors_for_liege", ":lord_2", ":faction_2_leader"),
		(assign, ":faction_2_leader_score", reg0),

		(try_begin),
			(gt, ":lord_1_score", ":faction_2_leader_score"),
			
			
			(try_begin),
				(ge, "$cheat_mode", 1),
				(str_store_troop_name, s4, ":lord_2"),
				(display_message, "@{!}DEBUG - {s4} faction changed in subornment"), 
			(try_end),
			
			(call_script, "script_change_troop_faction", ":lord_2", ":lord_1_faction"),		
		(try_end),
	(try_end),
	
	
	
]),


#this calculates the average number of rivalries per lord, giving a rough indication of how easily a faction may be divided
#fairly expensive in terms of CPU
  ("evaluate_realm_stability",
 
    [
	(store_script_param, ":realm", 1),

	(assign, ":total_lords", 0),
	(assign, ":total_restless_lords", 0),
	(assign, ":total_disgruntled_lords", 0),
	
	(faction_get_slot, ":liege", ":realm", slot_faction_leader),
	
	(try_for_range, ":lord", active_npcs_begin, active_npcs_end),
		(troop_slot_eq, ":lord", slot_troop_occupation, slto_kingdom_hero),
		(store_troop_faction, ":lord_faction", ":lord"),
		(eq, ":lord_faction", ":realm"),
		(val_add, ":total_lords", 1),

		(call_script, "script_calculate_troop_political_factors_for_liege", ":lord", ":liege"),
		(try_begin),
			(le, reg3, -10),
			(val_add, ":total_disgruntled_lords", 1),
		(else_try),
			(le, reg3, 10),
			(val_add, ":total_restless_lords", 1),
		(try_end),
	(try_end),
	
	(try_begin),
		(gt, ":total_lords", 0),
		(store_mul, ":instability_quotient", ":total_disgruntled_lords", 100),
		(val_div, ":instability_quotient", ":total_lords"),

		(store_mul, ":restless_quotient", ":total_restless_lords", 100),
		(val_div, ":restless_quotient", ":total_lords"),

		(store_mul, ":combined_quotient", ":instability_quotient", 2),
		(val_add, ":combined_quotient", ":restless_quotient"),
		(faction_set_slot, ":realm", slot_faction_instability, ":combined_quotient"),
	
		(assign, reg0, ":instability_quotient"),
		(assign, reg1, ":restless_quotient"),
		(assign, reg1, ":restless_quotient"),
	(else_try),
		(try_begin),
			(eq, "$cheat_mode", 1),
			(str_store_faction_name, s1, ":realm"),
			(display_message, "str_s1_has_no_lords"),
		(try_end),
		(assign, reg0, 0),
		(assign, reg1, 0),
	(try_end),
	
	]),
	
	
	
#lord recruitment scripts end	  
	  
#called from game_event_simulate_battle
#Includes a number of consequences that follow on battles, mostly affecting relations between different NPCs
#This only fires from complete victories
  ("battle_political_consequences",
    [
	(store_script_param, ":defeated_party", 1),
	(store_script_param, ":winner_party", 2),

	(try_begin),
		(eq, "$cheat_mode", 1),
		(str_store_party_name, s4, ":winner_party"),
		(str_store_party_name, s5, ":defeated_party"),
		(display_message, "str_do_political_consequences_for_s4_victory_over_s5"),
	(try_end),
	
	(store_faction_of_party, ":winner_faction", ":winner_party"),
	(try_begin),
		(eq, ":winner_party", "p_main_party"),
		(assign, ":winner_faction", "$players_kingdom"),
	(try_end),
		
	(party_get_template_id, ":defeated_party_template", ":defeated_party"),
		
	#did the battle involve travellers?	
	(try_begin),
		(this_or_next|eq, ":defeated_party_template", "pt_village_farmers"),
			(eq, ":defeated_party_template", "pt_kingdom_caravan_party"),

			
		(party_get_slot, ":destination", ":defeated_party", slot_party_ai_object),
		(party_get_slot, ":origin", ":defeated_party", slot_party_last_traded_center),
		
        (call_script, "script_add_log_entry", logent_traveller_attacked, ":winner_party",  ":origin", ":destination", ":winner_faction"),
		
		(try_begin),
			(eq, "$cheat_mode", 2),
			(neg|is_between, ":winner_faction", kingdoms_begin, kingdoms_end),
			(str_store_string, s65, "str_bandits_attacked_a_party_on_the_roads_so_a_bounty_is_probably_available"),
			(call_script, "script_add_notification_menu", "mnu_debug_alert_from_s65", 0, 0),

			(str_store_party_name, s15, ":origin"),
			(str_store_party_name, s16, ":destination"),
			(display_message, "str_travellers_attacked_on_road_from_s15_to_s16"),
		(try_end),
		
		
		#by logging the faction and the party, we can verify that the party number is unlikely to have been reassigned - or at any rate, that the factions have not changed 
	(try_end),
	
	#winner consequences:
	#1)   leader improves relations with other leaders
	#2)  Player given credit for victory if the victorious party is following the player's advice
	(try_begin),
		(party_get_template_id, ":winner_party_template", ":winner_party"),
		(eq, ":winner_party_template", "pt_kingdom_hero_party"),
		(neq, ":winner_party", "p_main_party"),
		#Do not do for player party, as is included in post-battle dialogs
		
		(party_stack_get_troop_id, ":winner_leader", ":winner_party", 0),
		(is_between, ":winner_leader", active_npcs_begin, active_npcs_end),
		
		(store_faction_of_party, ":winner_faction", ":winner_party"),

		(party_collect_attachments_to_party, ":winner_party", "p_temp_party_2"),
        (party_get_num_companion_stacks, ":num_stacks", "p_temp_party_2"),
		(try_for_range, ":troop_iterator", 0, ":num_stacks"),
            (party_stack_get_troop_id, ":cur_troop_id", "p_temp_party_2", ":troop_iterator"),
            (is_between, ":cur_troop_id", active_npcs_begin, active_npcs_end),
			
			(try_begin),
				(troop_get_slot, ":winner_lord_party", ":cur_troop_id", slot_troop_leaded_party),
				(party_is_active, ":winner_lord_party"),				
				(call_script, "script_cf_party_under_player_suggestion", ":winner_lord_party"),
				(call_script, "script_add_log_entry", logent_player_suggestion_succeeded, "trp_player", -1, ":cur_troop_id", -1),
			(try_end),

			
			(store_faction_of_troop, ":troop_faction", ":cur_troop_id"),
			(eq, ":troop_faction", ":winner_faction"),
			(neq, ":cur_troop_id", ":winner_leader"),

			(try_begin),
				(eq, "$cheat_mode", 4),
				(str_store_troop_name, s15, ":cur_troop_id"),
				(str_store_troop_name, s16, ":winner_leader"),
				(display_message, "str_s15_shares_joy_of_victory_with_s16"),
			(try_end),
			
			(call_script, "script_troop_change_relation_with_troop", ":cur_troop_id", ":winner_leader", 3),
			(val_add, "$total_battle_ally_changes", 3),

		(try_end),
		(party_clear, "p_temp_party_2"),
	(try_end),
	
	#consequences of defeat,
	#1) -1 relation with lord per lord, plus -15 if there is an incompatible marshal
	#2)  losers under player suggestion blame the player
	#3) Some losers resent the victor lord
	#4) Possible quarrels over defeat
	(try_begin),
		(party_collect_attachments_to_party, ":defeated_party", "p_temp_party_2"),
        (party_get_num_companion_stacks, ":num_stacks", "p_temp_party_2"),

		(try_begin),
			(gt, "$marshall_defeated_in_battle", 0),
			(str_store_troop_name, s15, "$marshall_defeated_in_battle"),
			(store_faction_of_troop, ":defeated_marshall_faction", "$marshall_defeated_in_battle"),
            (try_begin),
                (eq, "$cheat_mode", 1),
			    (display_message, "str_faction_marshall_s15_involved_in_defeat"),
            (try_end),
		(else_try),
			(eq, "$marshall_defeated_in_battle", "trp_player"),
			(eq, ":defeated_party", "p_main_party"),
			(faction_slot_eq, "fac_player_supporters_faction", slot_faction_state, sfs_active),
            (try_begin),
                (eq, "$cheat_mode", 1),
			    (display_message, "str_player_faction_marshall_involved_in_defeat"),
            (try_end),
		(else_try),	
			(assign, "$marshall_defeated_in_battle", -1),
		(try_end),
		
		(try_for_range, ":troop_iterator", 0, ":num_stacks"),
            (party_stack_get_troop_id, ":cur_troop_id", "p_temp_party_2", ":troop_iterator"),
            (troop_slot_eq, ":cur_troop_id", slot_troop_occupation, slto_kingdom_hero),					
		
			(try_begin), #is party under suggestion?
				(troop_get_slot, ":defeated_lord_party", ":cur_troop_id", slot_troop_leaded_party),
				(party_is_active, ":defeated_lord_party"),

				#is party under suggestion?
                                (call_script, "script_cf_party_under_player_suggestion", ":defeated_lord_party"),
				(call_script, "script_add_log_entry", logent_player_suggestion_failed, "trp_player", -1, ":cur_troop_id", -1),		
			(try_end),

			
			(store_faction_of_troop, ":troop_faction", ":cur_troop_id"),
			
			(faction_get_slot, ":faction_leader", ":troop_faction", slot_faction_leader),
			(neq, ":cur_troop_id", ":faction_leader"),
			
			#Lose one point relation with liege
			(try_begin),
				(eq, "$cheat_mode", 1),
				(str_store_troop_name, s14, ":cur_troop_id"),
				(str_store_faction_name, s15, ":troop_faction"),
				
				(display_message, "str_s14_of_s15_defeated_in_battle_loses_one_point_relation_with_liege"),
			(try_end),
			
			(try_begin),
				(this_or_next|neq, ":faction_leader", "trp_player"), #if leader is zero at beginning of game. I'm not entirely sure how this could happen...
					(eq, "$players_kingdom", ":troop_faction"),
				
				(call_script, "script_troop_change_relation_with_troop", ":cur_troop_id", ":faction_leader", -1),
				(val_add, "$total_battle_ally_changes", -1),
			(try_end),
			
	
			(call_script, "script_faction_inflict_war_damage_on_faction", ":winner_faction", ":troop_faction", 10),
		
			
			(try_begin),
				(this_or_next|is_between, ":winner_leader", active_npcs_begin, active_npcs_end),
					(eq, ":winner_leader", "trp_player"),
					
				(this_or_next|neq, ":winner_leader", "trp_player"), #prevents winner leader being zero, for whatever reason
					(eq, ":winner_party", "p_main_party"),
				
				(this_or_next|troop_slot_eq, ":cur_troop_id", slot_lord_reputation_type, lrep_quarrelsome),
				(this_or_next|troop_slot_eq, ":cur_troop_id", slot_lord_reputation_type, lrep_selfrighteous),
					(troop_slot_eq, ":cur_troop_id", slot_lord_reputation_type, lrep_debauched),
			
				(call_script, "script_troop_change_relation_with_troop", ":cur_troop_id", ":winner_leader", -1),
				(val_add, "$total_battle_enemy_changes", -1),
				
				(try_begin),
					(eq, "$cheat_mode", 1),
					(str_store_troop_name, s14, ":cur_troop_id"),
					(str_store_troop_name, s15, ":winner_leader"),
				
					(display_message, "str_s14_defeated_in_battle_by_s15_loses_one_point_relation"),
				(try_end),

				
			(try_end),
			
			(gt, "$marshall_defeated_in_battle", -1),
			(eq, ":troop_faction", ":defeated_marshall_faction"),
			(str_store_troop_name, s14, ":cur_troop_id"),
			
			(call_script, "script_cf_test_lord_incompatibility_to_s17", ":cur_troop_id", "$marshall_defeated_in_battle"),
            (try_begin),
                (eq, "$cheat_mode", 1),
			    (display_message, "str_s14_blames_s15_for_defeat"),
            (try_end),
			
			(call_script, "script_add_log_entry", logent_lord_blames_defeat, ":cur_troop_id", "$marshall_defeated_in_battle", ":faction_leader", ":winner_faction"),

			(call_script, "script_troop_change_relation_with_troop", ":cur_troop_id", ":faction_leader", -15),
			(val_add, "$total_battle_ally_changes", -15),
			
			(neq, "$marshall_defeated_in_battle", ":faction_leader"),
			(call_script, "script_troop_change_relation_with_troop", ":cur_troop_id", "$marshall_defeated_in_battle", -15),
			(val_add, "$total_battle_ally_changes", -15),
			
		(try_end),
		
		(party_clear, "p_temp_party_2"),
	(try_end),
	]),

    ("faction_inflict_war_damage_on_faction",
    [
	(store_script_param, ":actor_faction", 1),
	(store_script_param, ":target_faction", 2),
	(store_script_param, ":amount", 3),
	
	
	(store_add, ":slot_war_damage", ":target_faction", slot_faction_war_damage_inflicted_on_factions_begin),
	(val_sub, ":slot_war_damage", kingdoms_begin),
	(faction_get_slot, ":cur_war_damage", ":actor_faction", ":slot_war_damage"),
	
	(val_add, ":cur_war_damage", ":amount"),
	(faction_set_slot, ":actor_faction", ":slot_war_damage", ":cur_war_damage"),


	(try_begin),
	  (ge, "$cheat_mode", 1),
	  (str_store_faction_name, s4, ":actor_faction"),
	  (str_store_faction_name, s5, ":target_faction"),
	  (assign, reg3, ":cur_war_damage"),
	  (assign, reg4, ":amount"),
	  (display_message, "@{!}{s4} inflicts {reg4} damage on {s5}, raising total inflicted to {reg3}"),
	(try_end),

	
	(faction_get_slot, ":faction_marshal", ":target_faction", slot_faction_marshall),
	(try_begin),
		(ge, ":faction_marshal", 0),
		(gt, ":amount", 0),
		
		(troop_get_slot, ":controversy", ":faction_marshal", slot_troop_controversy),
		(val_add, ":controversy", ":amount"),
		(val_min, ":controversy", 100),
		(troop_set_slot, ":faction_marshal", slot_troop_controversy, ":controversy"),
		
		(try_begin),
			(ge, "$cheat_mode", 1),
			(str_store_troop_name, s4, ":faction_marshal"),
			(assign, reg4, ":amount"),
			(assign, reg5, ":controversy"),
			(display_message, "@{!}War damage raises {s4}'s controversy by {reg4} to {reg5}"),
		(try_end),
	(try_end),

	(faction_get_slot, ":faction_marshal", ":actor_faction", slot_faction_marshall),
	(try_begin),
		(ge, ":faction_marshal", 0),
		(val_div, ":amount", 3),
		(gt, ":amount", 0),
		
		
		(troop_get_slot, ":controversy", ":faction_marshal", slot_troop_controversy),
		(val_sub, ":controversy", ":amount"),
		(val_max, ":controversy", 0),
		(troop_set_slot, ":faction_marshal", slot_troop_controversy, ":controversy"),
		
		(try_begin),
			(ge, "$cheat_mode", 1),
			(str_store_troop_name, s4, ":faction_marshal"),
			(assign, reg4, ":amount"),
			(assign, reg5, ":controversy"),
			(display_message, "@{!}War damage lowers {s4}'s controversy by {reg4} to {reg5}"),
		(try_end),
	(try_end),


	
	]),
	
    ("calculate_troop_political_factors_for_liege",
    [
	(store_script_param, ":troop", 1),
	(store_script_param, ":liege", 2),

	(troop_get_slot, ":lord_reputation", ":troop", slot_lord_reputation_type),
	
	(store_faction_of_troop, ":faction", ":liege"),

	
	(try_begin),
		(eq, ":faction", "fac_player_faction"),
		(assign, ":faction", "fac_player_supporters_faction"),
	(try_end),

	(assign, ":liege_is_undeclared_rebel", 0),
	(try_begin),
		(neg|faction_slot_eq, ":faction", slot_faction_leader, ":liege"),
		#the liege is a rebel
		(assign, ":liege_is_undeclared_rebel", 1),
		(try_begin),
			(eq, "$cheat_mode", 1),
			(str_store_troop_name, s32, ":liege"),
			(display_message, "str_s32_is_undeclared_rebel"),
		(try_end),
	(try_end),	
	
	(assign, ":result_for_material", 0),
	(assign, ":penalty_for_changing_sides", 0),

	

	#FACTOR 1 - MILITARY SECURITY
	(assign, ":result_for_security", 0),

	#find the lord's home
	(assign, ":base_center", -1),
	(try_begin),
		(is_between, ":troop", active_npcs_begin, active_npcs_end),
		(try_for_range, ":center", centers_begin, centers_end),
			(eq, ":base_center", -1),
			(party_slot_eq, ":center", slot_town_lord, ":troop"),
			(assign, ":base_center", ":center"),
		(try_end),
	(try_end),
	
	(assign, ":faction_has_base", 0),
	
	#add up all other centers for the security value
	(try_for_range, ":center", centers_begin, centers_end),
		(neq, ":center", ":base_center"),
		(gt, ":base_center", 0),
	
		(try_begin),
			(is_between, ":center", towns_begin, towns_end),
			(assign, ":weight", 9000),
		(else_try),
			(is_between, ":center", castles_begin, castles_end),
			(assign, ":weight", 6000),
		(else_try),
			(assign, ":weight", 1000),	
		(try_end),

		(store_distance_to_party_from_party, ":distance", ":base_center", ":center"),
		(val_add, ":distance", 10),
		(val_div, ":weight", ":distance"),
		(val_div, ":weight", ":distance"),
		
		(store_faction_of_party, ":center_faction", ":center"),

		(try_begin),
			(eq, ":center_faction", ":faction"),

			(assign, ":faction_has_base", 1),
			(val_add, ":result_for_security", ":weight"),
		(else_try),
			(neq, ":center_faction", ":faction"),
			(store_relation, ":center_relation", ":center_faction", ":faction"),
		
			(try_begin), #potentially hostile center
				(this_or_next|eq, ":liege_is_undeclared_rebel", 1),
					(lt, ":center_relation", 0),
				(val_div, ":weight", 2),
			(else_try), #neutral center
				(val_div, ":weight", 4),
			(try_end),
		
			(val_sub, ":result_for_security", ":weight"),		
		(try_end),
	(try_end),
	
	
	#if a faction controls no other centers, then there is a small bonus
	(try_begin),
		(eq, ":faction_has_base", 0),
		(val_add, ":result_for_security", 20),
		(try_begin),
			(eq, "$cheat_mode", 2),
			(display_message, "str_small_bonus_for_no_base"),
		(try_end),
	(try_end),
	(val_clamp, ":result_for_security", -100, 100),

	
	(assign, ":result_for_security_weighted", ":result_for_security"),
	(try_begin),
		(eq, ":lord_reputation", lrep_cunning),
		(val_mul, ":result_for_security_weighted", 2),
	(else_try),
		(eq, ":lord_reputation", lrep_martial),
		(val_div, ":result_for_security_weighted", 2),
	(try_end),



	#FACTOR 2 - INTERNAL FACTION POLITICS
	#this is a calculation of how much influence the lord believes he will have in each faction
	(assign, ":result_for_political", 0),
	
    (try_for_range, ":loop_var", "trp_kingdom_heroes_including_player_begin", active_npcs_end),
        (assign, ":kingdom_hero", ":loop_var"),

		(this_or_next|troop_slot_eq, ":kingdom_hero", slot_troop_occupation, slto_kingdom_hero),
		(this_or_next|eq, ":kingdom_hero", "trp_kingdom_heroes_including_player_begin"),
			(is_between, ":kingdom_hero", pretenders_begin, pretenders_end),

		(store_faction_of_troop, ":kingdom_hero_faction", ":kingdom_hero"),

        (try_begin),
            (eq, ":loop_var", "trp_kingdom_heroes_including_player_begin"),
            (assign, ":kingdom_hero", "trp_player"),
			(assign, ":kingdom_hero_faction", "$players_kingdom"),
			(try_begin), #do not count player relation if the player is trying to suborn the character. this has the slight potential for a miscalculation, if the script is called from outside dialogs and $g_talk_troop has not been reset
				(eq, "$g_talk_troop", ":troop"),
				(store_faction_of_troop, ":cur_faction", ":troop"),
				(eq, ":cur_faction", ":faction"),
				(assign, ":kingdom_hero_faction", 0),
			(try_end),	
		(try_end),
		
		(eq, ":kingdom_hero_faction", ":faction"),
		(neg|faction_slot_eq, ":kingdom_hero_faction", slot_faction_leader, ":kingdom_hero"),
		(neq, ":liege_is_undeclared_rebel", 1),
		(neg|is_between, ":kingdom_hero", pretenders_begin, pretenders_end),
		
						
		(call_script, "script_troop_get_relation_with_troop", ":troop", ":kingdom_hero"),
		(assign, ":troop_rel_w_hero", reg0),

		(call_script, "script_troop_get_relation_with_troop", ":kingdom_hero", ":liege"),
		(assign, ":hero_rel_w_liege", reg0),

		(store_mul, ":lord_political_weight", ":troop_rel_w_hero", ":hero_rel_w_liege"),
		(val_div, ":lord_political_weight", 100),

		(try_begin),
			(eq, "$cheat_mode", 2), #disabled
			(eq, "$g_talk_troop", ":troop"),
			(str_store_faction_name, s20, ":kingdom_hero_faction"),
			(str_store_troop_name, s15, ":kingdom_hero"),
			(assign, reg15, ":lord_political_weight"),
			(display_message, "str_s15_considered_member_of_faction_s20_weight_of_reg15"),
		(try_end),
		
		(val_add, ":result_for_political", ":lord_political_weight"),
	(try_end),			

	(val_clamp, ":result_for_political", -100, 101), #lords portion represents half
	
	(try_begin),
		(call_script, "script_troop_get_relation_with_troop", ":troop", ":liege"),
		(assign, ":liege_relation", reg0),
		(val_add, ":result_for_political", ":liege_relation"),
	(try_end),	

	(val_div, ":result_for_political", 2),
	
	(val_clamp, ":result_for_political", -100, 101), #liege portion represents half
	
	(assign, ":result_for_political_weighted", ":result_for_political"),
	
	(try_begin),
		(this_or_next|eq, ":lord_reputation", lrep_goodnatured),
			(eq, ":lord_reputation", lrep_quarrelsome),
		(val_mul, ":result_for_political_weighted", 2),
	(try_end),

	#FACTOR 3 - PROMISES AND OTHER ANTICIPATED GAINS
	#lord's calculation of anticipated gains
	(assign, ":result_for_material", 0),
	(assign, ":result_for_material_weighted", ":result_for_material"),

	
	#FACTOR 4 - IDEOLOGY
	#lord's calculation of ideological comfort
	(try_begin),
		#Originally, the argument section was not used for a non-player liege. Actually, it can be used
		(eq, 1, 0),
		(neq, ":liege", "trp_player"),
		(neq, ":liege", "$supported_pretender"), #player is advocate for pretender
		(assign, ":argument_strength", 0),
		(assign, ":argument_appeal", 0),
		(assign, ":result_for_argument", 0),
	(else_try),	#only if the recruitment candidate is either the player, or a supported pretender
		(troop_get_slot, ":recruitment_argument", ":troop", slot_lord_recruitment_argument),

		(call_script, "script_rebellion_arguments", ":troop", ":recruitment_argument", ":liege"),
		(assign, ":argument_appeal", reg0),
		(assign, ":argument_strength", reg1),
		
		(store_add, ":result_for_argument", ":argument_appeal", ":argument_strength"),

		(store_skill_level, ":player_persuasion_skill", "skl_persuasion", "trp_player"),
		(try_begin),
			(gt, ":result_for_argument", 0),
			#make sure player is the one making the overture
			
			#if player has 0 persuasion, ":result_for_argument" will be multiplied by 3/10.
			(store_add, ":player_persuasion_skill_plus_5_mul_066", ":player_persuasion_skill", 5),
			(val_mul, ":player_persuasion_skill_plus_5_mul_066", 2),
			(val_div, ":player_persuasion_skill_plus_5_mul_066", 3),
			
			(val_mul, ":result_for_argument", ":player_persuasion_skill_plus_5_mul_066"),
			(val_div, ":result_for_argument", 10),
		(else_try),
			(lt, ":result_for_argument", 0),
			(store_sub, ":ten_minus_player_persuasion_skill", 10, ":player_persuasion_skill"),
			(val_mul, ":result_for_argument", ":ten_minus_player_persuasion_skill"),
			(val_div, ":result_for_argument", 10),
		(try_end),
		
		(try_begin),
			(neq, ":liege", "trp_player"),
			(neq, ":liege", "$supported_pretender"), #player is advocate for pretender
			(val_div, ":argument_strength", 2),
			(val_div, ":argument_appeal", 2),
			(val_div, ":result_for_argument", 2),		
		(try_end),
		
	(try_end),
	
#	(try_begin),
#		(eq, ":lord_reputation", lrep_cunning),
#		(val_div, ":result_for_ideological_weighted", 2),
#	(else_try),
#		(eq, ":lord_reputation", lrep_upstanding),
#		(val_mul, ":result_for_ideological_weighted", 2),
#	(try_end),


	#FACTOR 5 - PENALTY FOR CHANGING SIDES
	(try_begin), #no penalty for the incumbent
		(store_faction_of_troop, ":cur_faction", ":troop"),
		(eq, ":cur_faction", ":faction"),
		(assign, ":penalty_for_changing_sides", 0),
	(else_try), #penalty for the player
		(eq, ":liege", "trp_player"),
		(store_sub, ":penalty_for_changing_sides", 60, "$player_right_to_rule"),
	(else_try), #same culture, such as a pretender
		(troop_get_slot, ":orig_faction_of_lord", ":troop", slot_troop_original_faction),
		(troop_get_slot, ":orig_faction_of_liege", ":liege", slot_troop_original_faction),
		(eq, ":orig_faction_of_lord", ":orig_faction_of_liege"),
		(assign, ":penalty_for_changing_sides", 10),
	(else_try), #a liege from a different culture
		(assign, ":penalty_for_changing_sides", 50),
	(try_end),
	(val_clamp, ":penalty_for_changing_sides", 0, 101),
	
	(assign, ":penalty_for_changing_sides_weighted", ":penalty_for_changing_sides"),
	(try_begin),
		(eq, ":lord_reputation", lrep_debauched),
		(val_div, ":penalty_for_changing_sides_weighted", 2),
	(else_try),
		(eq, ":lord_reputation", lrep_upstanding),
		(val_mul, ":penalty_for_changing_sides_weighted", 2),
	(try_end),

	
	
	(assign, reg1, ":result_for_security"),
	(assign, reg2, ":result_for_security_weighted"),
	(assign, reg3, ":result_for_political"),
	(assign, reg4, ":result_for_political_weighted"),
	(assign, reg5, ":result_for_material"),
	(assign, reg6, ":result_for_material_weighted"),
	(assign, reg7, ":argument_strength"),
	(assign, reg17, ":argument_appeal"),

	(assign, reg8, ":result_for_argument"),
	(assign, reg9, ":penalty_for_changing_sides"),
	(assign, reg10, ":penalty_for_changing_sides_weighted"),

	
	(try_begin),
		(eq, "$cheat_mode", 1),
		(eq, "$g_talk_troop", ":troop"),
		(str_store_troop_name, s20, ":troop"),
		(str_store_faction_name, s21, ":faction"),
		(str_store_troop_name, s22, ":liege"),
		
		(display_message, "@{!}G_talk_troop {s20} evaluates being vassal to {s22} of {s21}"),

		(display_message, "str_base_result_for_security_reg1"),
		(display_message, "str_result_for_security_weighted_by_personality_reg2"),
		(display_message, "str_base_result_for_political_connections_reg3"),	
		(display_message, "str_result_for_political_connections_weighted_by_personality_reg4"),	
#		(display_message, "@{!}Result for anticipated_gains: {reg5}"),	
#		(display_message, "@{!}Result for anticipated_gains weighted by personality: {reg6}"),	

		(try_begin),
			(this_or_next|eq, ":liege", "trp_player"),
				(eq, ":liege", "$supported_pretender"), #player is advocate for pretender
			(display_message, "str_result_for_argument_strength_reg7"),	
			(display_message, "str_result_for_argument_appeal_reg17"),	
			(display_message, "str_combined_result_for_argument_modified_by_persuasion_reg8"),
		(try_end),			
		(display_message, "str_base_changing_sides_penalty_reg9"),	
		(display_message, "str_changing_sides_penalty_weighted_by_personality_reg10"),	
	(try_end),
		
	(store_add, ":total", ":result_for_security_weighted", ":result_for_political_weighted"),
	(val_add, ":total", ":result_for_material_weighted"),
	(val_add, ":total", ":result_for_argument"),
	(val_sub, ":total", ":penalty_for_changing_sides_weighted"),


	(assign, reg0, ":total"),

	(try_begin),
		(eq, "$cheat_mode", 2),
		(display_message, "@{!}DEBUG -- Analyzing lord allegiances, combined bonuses and penalties = {reg0}"),
		#(display_message, "str_combined_bonuses_and_penalties_=_reg0"),
	(try_end),
	]),
	  


    ("cf_troop_can_intrigue",
	#This script should be called from dialogs, and also prior to any event which might result in a lord changing sides
    [
      (store_script_param, ":troop", 1),
      (store_script_param, ":skip_player_party", 2),
      
      (troop_get_slot, ":led_party_1", ":troop", slot_troop_leaded_party),
      (party_is_active, ":led_party_1"),
      
      (try_begin),
        (eq, "$cheat_mode", 1),
        (eq, ":troop", "$g_talk_troop"),
        (display_message, "str_intrigue_test_troop_party_is_active"),
      (try_end),
      
      (party_get_battle_opponent, ":battle_opponent", ":led_party_1"),
      (le, ":battle_opponent", 0), #battle opponent can be 0 for an attached party?
      
      (try_begin),
        (eq, "$cheat_mode", 1),
        (eq, ":troop", "$g_talk_troop"),
        (display_message, "str_intrigue_test_troop_party_is_not_in_battle"),
      (try_end),
      
      (troop_slot_eq, ":troop", slot_troop_prisoner_of_party, -1),
      
      (try_begin),
        (eq, "$cheat_mode", 1),
        (eq, ":troop", "$g_talk_troop"),
        (display_message, "str_intrigue_test_troop_is_not_prisoner"),
      (try_end),
      
      (party_get_attached_to, ":led_party_1_attached", ":led_party_1"),
      
      (store_faction_of_party, ":led_party_1_faction", ":led_party_1"),
      
      (assign, ":other_lords_nearby", 0),
      (try_for_range, ":troop_2", active_npcs_begin, active_npcs_end),
        (neq, ":troop", ":troop_2"),
        (eq, ":other_lords_nearby", 0),
        
        (troop_slot_eq, ":troop_2", slot_troop_occupation, slto_kingdom_hero),
        
        (troop_get_slot, ":led_party_2", ":troop_2", slot_troop_leaded_party),
        (party_is_active, ":led_party_2"),
        (neq, ":led_party_1", ":led_party_2"),
        
        (store_faction_of_party, ":led_party_2_faction", ":led_party_2"),
        (eq, ":led_party_1_faction", ":led_party_2_faction"),
        
        (try_begin),
          (eq, ":led_party_1_attached", -1),
          (store_distance_to_party_from_party, ":distance", ":led_party_1", ":led_party_2"),
          (lt, ":distance", 3),
          (assign, ":other_lords_nearby", 1),
        (else_try),
          (is_between, ":led_party_1_attached", walled_centers_begin, walled_centers_end),
          (party_get_attached_to, ":led_party_2_attached", ":led_party_2"),
          (eq, ":led_party_1_attached", ":led_party_2_attached"),
          (assign, ":other_lords_nearby", 1),
        (try_end),
      (try_end),
      
      (try_begin),
        (eq, "$cheat_mode", 1),
        (eq, ":troop", "$g_talk_troop"),
        (display_message, "str_intrigue_test_troop_is_nearby"),
      (try_end),
      
      (try_begin),
        (eq, ":skip_player_party", 0),
        #temporary spot
      (try_end),
      
      (eq, ":other_lords_nearby", 0),	
	]),


    ("troop_change_relation_with_troop",
    [
	(store_script_param, ":troop1", 1),
	(store_script_param, ":troop2", 2),
	(store_script_param, ":amount", 3),

	(try_begin),
		(eq, ":troop1", "trp_player"),
		(call_script, "script_change_player_relation_with_troop", ":troop2", ":amount"),
	(else_try),	
		(eq, ":troop2", "trp_player"),
		(call_script, "script_change_player_relation_with_troop", ":troop1", ":amount"),
	(else_try),	
		(eq, ":troop1", ":troop2"),
		
	(else_try),
		(call_script, "script_troop_get_relation_with_troop", ":troop1", ":troop2"),
		(store_add, ":new_relation", reg0, ":amount"),

		(val_clamp, ":new_relation", -100, 101),

		(try_begin),
			(eq, ":new_relation", 0),
			(assign, ":new_relation", 1), #this removes the need for a separate "met" slot - any non-zero relation will be a met
		(try_end),
		
		(store_add, ":troop1_slot_for_troop2", ":troop2", slot_troop_relations_begin),
		(troop_set_slot, ":troop1", ":troop1_slot_for_troop2", ":new_relation"),
	
		(store_add, ":troop2_slot_for_troop1", ":troop1", slot_troop_relations_begin),
		(troop_set_slot, ":troop2", ":troop2_slot_for_troop1", ":new_relation"),
	(try_end),
	
	
	(try_begin), #generate controversy if troops are in the same faciton
		(lt, ":amount", -5),
		(try_begin),
			(eq, ":troop1", "trp_player"),
			(assign, ":faction1", "$players_kingdom"),
		(else_try),	
			(store_faction_of_troop, ":faction1", ":troop1"),
		(try_end),
		(try_begin),
			(eq, ":troop2", "trp_player"),
			(assign, ":faction2", "$players_kingdom"),
		(else_try),	
			(store_faction_of_troop, ":faction2", ":troop2"),
		(try_end),
		(eq, ":faction1", ":faction2"),
		(is_between, ":faction1", kingdoms_begin, kingdoms_end),
		
		(store_mul, ":controversy_generated", ":amount", -1),
	
		(troop_get_slot, ":controversy1", ":troop1", slot_troop_controversy),
		(val_add, ":controversy1", ":controversy_generated"),
		(val_min, ":controversy1", 100),
		(troop_set_slot, ":troop1", slot_troop_controversy, ":controversy1"),

		(troop_get_slot, ":controversy2", ":troop2", slot_troop_controversy),
		(val_add, ":controversy2", ":controversy_generated"),
		(val_min, ":controversy2", 100),
		(troop_set_slot, ":troop2", slot_troop_controversy, ":controversy2"),
		
	(try_end),
	
	(try_begin),
		(is_between, ":troop1", active_npcs_begin, active_npcs_end),
		(is_between, ":troop2", active_npcs_begin, active_npcs_end),
		(neq, ":troop1", ":troop2"),
		
		(try_begin),
			(gt, ":amount", 0),
			(val_add, "$total_relation_adds", ":amount"),
		(else_try),
			(val_sub, "$total_relation_subs", ":amount"),
		(try_end),
	(try_end),
	
	(try_begin),
		(eq, "$cheat_mode", 4), #change back to 4
		
		(is_between, ":troop1", active_npcs_begin, active_npcs_end),
		(is_between, ":troop2", active_npcs_begin, active_npcs_end),
		(neq, ":troop1", ":troop2"),
		
		(str_store_troop_name, s20, ":troop1"),
		(str_store_troop_name, s15, ":troop2"),
		(assign, reg4, ":amount"),
		(assign, reg14, ":new_relation"),
		(display_message, "str_s20_relation_with_s15_changed_by_reg4_to_reg14"),
		
		(assign, reg4, "$total_relation_adds"),
		(display_message, "str_total_additions_reg4"),
		(assign, reg4, "$total_relation_subs"),
		(display_message, "str_total_subtractions_reg4"),
		
		(assign, reg4, "$total_courtship_quarrel_changes"),
		(display_message, "@{!}DEBUG -- Total courtship quarrel changes: {reg4}"),

		(assign, reg4, "$total_random_quarrel_changes"),
		(display_message, "@{!}DEBUG -- Total random quarrel changes: {reg4}"),
		
		(assign, reg4, "$total_battle_ally_changes"),
		(display_message, "@{!}DEBUG -- Total battle changes for allies: {reg4}"),

		(assign, reg4, "$total_battle_enemy_changes"),
		(display_message, "@{!}DEBUG -- Total battle changes for enemies: {reg4}"),

		(assign, reg4, "$total_promotion_changes"),
		(display_message, "@{!}DEBUG -- Total promotion changes: {reg4}"),
		
		(assign, reg4, "$total_feast_changes"),
		(display_message, "@{!}DEBUG -- Total feast changes: {reg4}"),
		
		(assign, reg4, "$total_policy_dispute_changes"),
		(assign, reg5, "$number_of_controversial_policy_decisions"),		
		(display_message, "@{!}DEBUG -- Total policy dispute changes: {reg4} from {reg5} decisions"),

		(assign, reg4, "$total_indictment_changes"),
		(display_message, "@{!}DEBUG -- Total faction switch changes: {reg4}"),

		(assign, reg4, "$total_no_fief_changes"),
		(display_message, "@{!}DEBUG -- Total no fief changes: {reg4}"),

		(assign, reg4, "$total_relation_changes_through_convergence"),
		(display_message, "@{!}DEBUG -- Total changes through convergence: {reg4}"),
		
		(assign, reg4, "$total_vassal_days_responding_to_campaign"),
		(display_message, "@{!}DEBUG -- Total vassal responses to campaign: {reg4}"),
		
		(assign, reg4, "$total_vassal_days_on_campaign"),
		(display_message, "@{!}DEBUG -- Total vassal campaign days: {reg4}"),
		
		(val_max, "$total_vassal_days_on_campaign", 1),
		(store_mul, ":response_rate", "$total_vassal_days_responding_to_campaign", 100),
		(val_div, ":response_rate", "$total_vassal_days_on_campaign"),
		(assign, reg4, ":response_rate"),
		(display_message, "@{!}DEBUG -- Vassal response rate: {reg4}"),
		
		
		
#		(assign, reg4, "$total_joy_battle_changes"),
#		(display_message, "@{!}DEBUG -- Total joy of battle changes"),
		
	(try_end),

	]),


    ("troop_get_relation_with_troop",
    [
	(store_script_param, ":troop1", 1),
	(store_script_param, ":troop2", 2),

	(assign, ":relation", 0),
	(try_begin),
		(this_or_next|eq, ":troop1", -1),
			(eq, ":troop2", -1),

		#Possibly switch to relation with liege	
		(assign, ":relation", 0),
	(else_try),
		(eq, ":troop1", "trp_player"),
		(call_script, "script_troop_get_player_relation", ":troop2"),
		(assign, ":relation", reg0),
	(else_try),
		(eq, ":troop2", "trp_player"),
		(call_script, "script_troop_get_player_relation", ":troop1"),
		(assign, ":relation", reg0),
	(else_try),
		(store_add, ":troop1_slot_for_troop2", ":troop2", slot_troop_relations_begin),
		(troop_get_slot, ":relation", ":troop1", ":troop1_slot_for_troop2"),
	(try_end),
	
	
	(val_clamp, ":relation", -100, 101),
	(assign, reg0, ":relation"),
	
	]),

	
	
	("appoint_faction_marshall",
    [
	(store_script_param, ":faction_no", 1),
	(store_script_param, ":faction_marshall", 2),


    (faction_get_slot, ":faction_leader", ":faction_no", slot_faction_leader),
    (faction_get_slot, ":old_marshall", ":faction_no", slot_faction_marshall),

    (faction_set_slot, ":faction_no", slot_faction_marshall, ":faction_marshall"),

    (try_begin),
		(ge, ":old_marshall", 0),
		(troop_get_slot, ":old_marshall_party", ":old_marshall", slot_troop_leaded_party),
        (party_is_active, ":old_marshall_party"),
        (party_set_marshall, ":old_marshall_party", 0),
        (call_script, "script_set_icon_for_lord_party", ":old_marshall"),
    (try_end),  

    
    (try_begin),
      (ge, ":faction_marshall", 0),
	  (troop_get_slot, ":new_marshall_party", ":faction_marshall", slot_troop_leaded_party),
      (party_is_active, ":new_marshall_party"),
      (party_set_marshall,":new_marshall_party", 1),
      (call_script, "script_set_icon_for_lord_party", ":faction_marshall"),
    (try_end),  
	
	
	(try_begin),
		(neq, ":faction_marshall", ":faction_leader"),
		(neq, ":faction_marshall", ":old_marshall"),
		(this_or_next|eq, ":faction_marshall", "trp_player"),
			(is_between, ":faction_marshall", active_npcs_begin, active_npcs_end),
		
		(this_or_next|neq, ":faction_no", "fac_player_supporters_faction"),
			(neg|check_quest_active, "qst_rebel_against_kingdom"),
		
		(try_begin),
			(eq, "$cheat_mode", 1),
			(str_store_faction_name, s15, ":faction_no"),
			(display_message, "str_checking_lord_reactions_in_s15"),
		(try_end),

		
		(call_script, "script_troop_change_relation_with_troop", ":faction_marshall", ":faction_leader", 5),
		(val_add, "$total_promotion_changes", 5),
		
		(try_for_range, ":lord", active_npcs_begin, active_npcs_end),
			(troop_slot_eq, ":lord", slot_troop_occupation, slto_kingdom_hero),
			(store_faction_of_troop, ":lord_faction", ":lord"),
			(eq, ":lord_faction", ":faction_no"),

			(neq, ":lord", ":faction_marshall"),
			(neq, ":lord", ":faction_leader"),

			(call_script, "script_troop_get_relation_with_troop", ":faction_marshall", ":lord"),
#			(try_begin),
#				(eq, "$cheat_mode", 1),
#				(str_store_troop_name, s14, ":lord"),
#				(str_store_troop_name, s17, ":faction_marshall"),
#				(display_message, "@{!}{s14}'s relation with {s17} is {reg0}"),
#			(try_end),	
			(store_sub, ":adjust_relations", reg0, 10),
			(val_div, ":adjust_relations", 15),
			(neq, ":adjust_relations", 0),

			#Not negatively affected if they favored the lord
			(try_begin),
				(troop_slot_eq, ":lord", slot_troop_stance_on_faction_issue, ":faction_marshall"),
				(val_add, ":adjust_relations", 1),
				(val_max, ":adjust_relations", 0),
			(try_end),

			(call_script, "script_troop_change_relation_with_troop", ":faction_leader", ":lord", ":adjust_relations"),
			(val_add, "$total_promotion_changes", ":adjust_relations"),
			
			(lt, ":adjust_relations", -2),
			(store_random_in_range, ":random", 1, 10),
			
			(val_add, ":adjust_relations", ":random"),
			
			(lt, ":adjust_relations", 0),
			
			(str_store_troop_name, s14, ":lord"),
			(str_store_troop_name, s15, ":faction_marshall"),

			(try_begin),
                (eq, "$cheat_mode", 1),
                (display_message, "str_s14_protests_the_appointment_of_s15_as_marshall"),
            (try_end),

			(call_script, "script_troop_change_relation_with_troop", ":faction_leader", ":lord", -10),
			(call_script, "script_troop_change_relation_with_troop", ":faction_marshall", ":lord", -5),
			(val_add, "$total_promotion_changes", -15),
			
			(call_script, "script_add_log_entry", logent_lord_protests_marshall_appointment, ":lord",  ":faction_marshall", ":faction_leader", "$g_encountered_party_faction"),

		(try_end),
	(try_end),
	
		]),
	
	#it might be easier to monitor whether prices are following an intuitive pattern if we separate production from consumption
	#the current system still works very well, however
	("center_get_item_consumption",
    [
	]),

	("locate_player_minister", #maybe deprecate this
    [
	
	(assign, ":walled_center_found", 0),
	(try_for_range, ":walled_center", walled_centers_begin, walled_centers_end),
		(lt, ":walled_center_found", centers_begin),
		(store_faction_of_party, ":walled_center_faction", ":walled_center"),
		(eq, ":walled_center_faction", "fac_player_supporters_faction"),
		(neg|party_slot_ge, ":walled_center", slot_town_lord, active_npcs_begin), #ie, player or a reserved slot
		(assign, ":walled_center_found", ":walled_center"),
	(try_end),

	(troop_get_slot, ":old_location", "$g_player_minister", slot_troop_cur_center),
	(troop_set_slot, "$g_player_minister", slot_troop_cur_center, ":walled_center_found"),
	
	(try_begin),
		(neq, ":old_location", ":walled_center"),
		(str_store_party_name, s10, ":walled_center"),
		(str_store_troop_name, s11, "$g_player_minister"),
		(display_message, "str_s11_relocates_to_s10"),
	(try_end),
	
	]),

	
	("lord_get_home_center",
	[
      (store_script_param, ":troop_no", 1),
      (assign, ":result", -1),
      
      (try_for_range, ":center_no", walled_centers_begin, walled_centers_end),
        (eq, ":result", -1),
        (party_slot_eq, ":center_no", slot_town_lord, ":troop_no"),
        (assign, ":result", ":center_no"),
      (try_end),
      
      #NOTE : In old code if a lord has no walled center then home city of this lord is assigning to 
      #faction leader's home city. Now I changed this to assign home cities more logical and homogeneous.
      #In new code if a lord has no walled center then his home city becomes his village's border_city.
      #This means his home city becomes owner city of his village. If he has no village then as last change 
      #his home city become faction leader's home city.
      (try_begin),
        (eq, ":result", -1),
        (try_for_range, ":center_no", centers_begin, centers_end),
          (eq, ":result", -1),
          (party_slot_eq, ":center_no", slot_town_lord, ":troop_no"),
          
          (try_begin),
            (neg|is_between, ":center_no", walled_centers_begin, walled_centers_end),
            (party_get_slot, ":bound_center", ":center_no", slot_village_bound_center),            
            (assign, ":result", ":bound_center"),
          (try_end),
        (try_end),      
      (try_end),

      #If lord has no walled center and is player faction, then assign player court
      (try_begin),
        (eq, ":result", -1),
        (store_faction_of_troop, ":faction_no", ":troop_no"),
        (eq, ":faction_no", "fac_player_supporters_faction"),
		(is_between, "$g_player_court", walled_centers_begin, walled_centers_end),
		(store_faction_of_party, ":player_court_faction", "$g_player_court"),
		(eq, ":player_court_faction", "fac_player_supporters_faction"),
		
        (assign, ":result", "$g_player_court"),
      (try_end),
      
      #If lord has no walled center and any not walled village then assign faction capital
      (try_begin),
        (eq, ":result", -1),
        (store_faction_of_troop, ":faction_no", ":troop_no"),
        (faction_get_slot, ":faction_leader", ":faction_no", slot_faction_leader),
        (neq, ":troop_no", ":faction_leader"),
        (call_script, "script_lord_get_home_center", ":faction_leader"),
        (gt, reg0, -1),
        (assign, ":result", reg0),
      (try_end),
      
	  #Any center of the faction
      (try_begin),
        (eq, ":result", -1),
		(store_faction_of_troop, ":faction_no", ":troop_no"),
		
		(try_for_range, ":walled_center", walled_centers_begin, walled_centers_end),
		    (eq, ":result", -1),

			(store_faction_of_party, ":center_faction", ":walled_center"),
			(eq, ":faction_no", ":center_faction"),
			(assign, ":result", ":walled_center"),
		(try_end),
      (try_end),
	  
	  
	  
      (assign, reg0, ":result"),	
	]),
	
	
	
	
	("get_kingdom_lady_social_determinants", #Calradian society is rather patriarchal, at least among the upper classes
    [
	(store_script_param, ":kingdom_lady", 1),
	
	(store_faction_of_troop, ":faction_of_lady", ":kingdom_lady"),
	(assign, ":center", -1),
	(assign, ":closest_male_relative", -1),
	(assign, ":best_center_score", 0),
	
	(try_begin),
		(troop_slot_ge, ":kingdom_lady", slot_troop_spouse, 0),
		(troop_get_slot, ":closest_male_relative", ":kingdom_lady", slot_troop_spouse),
	(else_try),
		(troop_slot_ge, ":kingdom_lady", slot_troop_father, 0),
		(troop_get_slot, ":closest_male_relative", ":kingdom_lady", slot_troop_father),
	(else_try),
		(troop_slot_ge, ":kingdom_lady", slot_troop_guardian, 0),
		(troop_get_slot, ":closest_male_relative", ":kingdom_lady", slot_troop_guardian),
	(try_end),
	
	
	(try_begin), #if ongoing social event (maybe add if not besieged)
		(faction_slot_eq, ":faction_of_lady", slot_faction_ai_state, sfai_feast),
		(faction_get_slot, ":feast_center", ":faction_of_lady", slot_faction_ai_object),

		(gt, ":closest_male_relative", -1),
		(troop_get_slot, ":closest_male_party", ":closest_male_relative", slot_troop_leaded_party),
		(party_is_active, ":closest_male_party"),
		(party_get_attached_to, ":closest_male_cur_location", ":closest_male_party"),
		
		(eq, ":closest_male_cur_location", ":feast_center"),
		(is_between, ":feast_center", walled_centers_begin, walled_centers_end),
		
		(assign, ":center", ":feast_center"),
		
	(else_try),
		(troop_slot_eq, "trp_player", slot_troop_spouse, ":kingdom_lady"),
		(is_between, "$g_player_court", walled_centers_begin, walled_centers_end),
		(assign, ":center", "$g_player_court"),
		
	(else_try),
		(try_for_range, ":walled_center", walled_centers_begin, walled_centers_end),
			(store_faction_of_party, ":walled_center_faction", ":walled_center"),
			(this_or_next|eq, ":faction_of_lady", ":walled_center_faction"),
				(neg|is_between, ":faction_of_lady", kingdoms_begin, kingdoms_end), #lady married to a player without a faction
				
			(party_get_slot, ":castle_lord", ":walled_center", slot_town_lord),
		
			(gt, ":castle_lord", -1),
			
			(call_script, "script_troop_get_family_relation_to_troop", ":kingdom_lady", ":castle_lord"),

			(try_begin),
				(this_or_next|is_between, ":faction_of_lady", kingdoms_begin, kingdoms_end),
					(troop_slot_eq, "trp_player", slot_troop_spouse, ":kingdom_lady"),
					
				(faction_slot_eq, ":faction_of_lady", slot_faction_leader, ":castle_lord"),
				(val_max, reg0, 1),
			(try_end),
			
			(try_begin),
				(eq, "$cheat_mode", 2),
				(str_store_troop_name, s3, ":kingdom_lady"),
				(str_store_troop_name, s4, ":castle_lord"),
				(str_store_party_name, s5, ":walled_center"),
				(display_message, "str_checking_s3_at_s5_with_s11_relationship_with_s4_score_reg0"),
				(str_clear, s11),
			(try_end),

			(gt, reg0, ":best_center_score"),
		
			(assign, ":best_center_score", reg0),
			(assign, ":center", ":walled_center"),
			
			
	    (try_end),
	(try_end),

	(assign, reg0, ":closest_male_relative"),
	(assign, reg1, ":center"),
	
	
	]),

	
	#This is probably unnecessarily complicated, but can support a multi-generational mod
	("age_troop_one_year",
    [
	(store_script_param, ":troop_no", 1),

	(troop_get_type, ":is_female", ":troop_no"),
	
	(troop_get_slot, ":age", ":troop_no", slot_troop_age),
	(troop_get_slot, ":appearance", ":troop_no", slot_troop_age_appearance),
	
	(val_add, ":age", 1),
	(store_random_in_range, ":addition", 1, 5),

	(try_begin),
		(eq, ":is_female", 1),
#		(val_add, ":addition", 2), #the women's age slider seems to produce less change than the male one - commented out: makes women look too old.
	(try_end),
	
	(val_add, ":appearance", ":addition"),
	(try_begin),
		(gt, ":age", 45),
		(store_attribute_level, ":strength", ":troop_no", ca_strength),
		(store_attribute_level, ":agility", ":troop_no", ca_agility),
		(store_random_in_range, ":random", 0, 50), #2% loss brings it down to about 36% by age 90, but of course can be counteracted by new level gain
		(try_begin),
			(lt, ":random", ":strength"),
			(troop_raise_attribute, ":troop_no", ca_strength, -1),
		(try_end),
		(try_begin),
			(lt, ":random", ":agility"),
			(troop_raise_attribute, ":troop_no", ca_agility, -1),
		(try_end),
	(try_end),

	(val_clamp, ":appearance", 1, 100),
	
	(troop_set_slot, ":troop_no", slot_troop_age, ":age"), 
	(troop_set_slot, ":troop_no", slot_troop_age_appearance, ":appearance"), 
	(troop_set_age, ":troop_no", ":appearance"),
	]),
	

	("add_lady_items",
	[
	(store_script_param, ":lady_no", 1),
	(troop_equip_items, ":lady_no"),
	
	(store_faction_of_troop, ":faction_no", ":lady_no"),
	
	(store_random_in_range, ":random", 0, 6),
	
	(try_begin), #assign clothes
		(this_or_next|troop_slot_eq, ":lady_no", slot_lord_reputation_type, lrep_adventurous),
			(troop_slot_eq, ":lady_no", slot_lord_reputation_type, lrep_ambitious),
	
		(this_or_next|troop_slot_eq, ":lady_no", slot_lord_reputation_type, lrep_adventurous),
			(lt, ":random", 2),
			
		(neg|troop_slot_ge, ":lady_no", slot_troop_age, 40),
		(try_begin),
			(eq, ":faction_no", "fac_kingdom_2"),
			(lt, ":random", 4),
			(troop_add_item, ":lady_no", "itm_fur_coat", 0),
		(else_try),
			(eq, ":faction_no", "fac_kingdom_3"),
			(lt, ":random", 3),
			(troop_add_item, ":lady_no", "itm_nomad_robe", 0),
		(else_try),	
			(troop_add_item, ":lady_no", "itm_nomad_vest", 0),
		(try_end),
	(else_try),
		(eq, ":faction_no", "fac_kingdom_1"),
		(try_begin),
			(lt, ":random", 2),
			(troop_add_item, ":lady_no", "itm_lady_dress_ruby", 0),
		(else_try),
			(lt, ":random", 4),
			(troop_add_item, ":lady_no", "itm_lady_dress_green", 0),
		(else_try),
			(troop_add_item, ":lady_no", "itm_lady_dress_blue", 0),
		(try_end),
	(else_try),
		(eq, ":faction_no", "fac_kingdom_2"),
		(try_begin),
			(eq, ":random", 0),
			(troop_add_item, ":lady_no", "itm_blue_dress", 0),
		(else_try),
			(eq, ":random", 1),
			(troop_add_item, ":lady_no", "itm_lady_dress_green", 0),
		(else_try),
			(eq, ":random", 2),
			(troop_add_item, ":lady_no", "itm_lady_dress_blue", 0),
		(else_try),
			(lt, ":random", 5),
			(neg|troop_slot_eq, ":lady_no", slot_lord_reputation_type, lrep_conventional),
			(neg|troop_slot_eq, ":lady_no", slot_lord_reputation_type, lrep_ambitious),
			(troop_add_item, ":lady_no", "itm_peasant_dress", 0),
		(else_try),
			(lt, ":random", 5),
			(troop_add_item, ":lady_no", "itm_lady_dress_ruby", 0),
		(else_try),
			(troop_add_item, ":lady_no", "itm_court_dress", 0),
		(try_end),
	
	(else_try),
		(eq, ":faction_no", "fac_kingdom_3"),
		(troop_add_item, ":lady_no", "itm_khergit_lady_dress", 0),
	
	(else_try),
		(eq, ":faction_no", "fac_kingdom_4"),

	(else_try),
		(eq, ":faction_no", "fac_kingdom_5"),

		
	(try_end),
	(troop_equip_items, ":lady_no"),

	#also available:
	#itm_blue_dress
	#itm_court_dress	
	
	#to add for khergits -- salwar/shalvar?
	#western tang costume (p105, china's golden age)
	#kipchak woman from russia book
	
	(try_begin), #assign headguear matched to item
		(this_or_next|troop_has_item_equipped, ":lady_no", "itm_nomad_vest"),
		(this_or_next|troop_has_item_equipped, ":lady_no", "itm_fur_coat"),
			(troop_has_item_equipped, ":lady_no", "itm_nomad_robe"),
		
		#assign no headgear
	(else_try),
		(this_or_next|troop_slot_eq, ":lady_no", slot_lord_reputation_type, lrep_moralist),
		(this_or_next|troop_slot_eq, ":lady_no", slot_lord_reputation_type, lrep_conventional),
			(lt, ":random", 2),
			
		
		(try_begin),
			(troop_has_item_equipped, ":lady_no", "itm_khergit_lady_dress"),
			(troop_add_item, ":lady_no", "itm_khergit_lady_hat", 0),
		
		(else_try),
			(troop_has_item_equipped, ":lady_no", "itm_lady_dress_ruby"),
			(troop_add_item, ":lady_no", "itm_turret_hat_ruby", 0),

			(str_store_troop_name, s4, ":lady_no"),
#			(display_message, "@Giving ruby turret hat to {s4}"),
		(else_try),
			(troop_has_item_equipped, ":lady_no", "itm_lady_dress_blue"),
			(troop_add_item, ":lady_no", "itm_turret_hat_blue", 0),
		
			(str_store_troop_name, s4, ":lady_no"),
#			(display_message, "@Giving blue turret hat to {s4}"),
		(else_try),
			(troop_has_item_equipped, ":lady_no", "itm_lady_dress_green"),
			(troop_add_item, ":lady_no", "itm_turret_hat_green", 0),
		
			(str_store_troop_name, s4, ":lady_no"),
#			(display_message, "@Giving green turret hat to {s4}"),
		(else_try),	
			(troop_has_item_equipped, ":lady_no", "itm_green_dress"),
			(troop_add_item, ":lady_no", "itm_wimple_with_veil", 0),

			(str_store_troop_name, s4, ":lady_no"),
#			(display_message, "@Giving green-lined wimple to {s4}"),
		(else_try),
			(neq, ":faction_no", "fac_kingdom_3"),
			(neq, ":faction_no", "fac_kingdom_6"),
			(troop_add_item, ":lady_no", "itm_wimple_a", 0),

			(str_store_troop_name, s4, ":lady_no"),
#			(display_message, "@Giving red-lined wimple to {s4}"),
		(else_try),
			(eq, ":faction_no", "fac_kingdom_6"),
			(try_begin),
				(troop_has_item_equipped, ":lady_no", "itm_sarranid_lady_dress"),
				(troop_add_item, ":lady_no", "itm_sarranid_head_cloth", 0),
			(else_try),
				(troop_add_item, ":lady_no", "itm_sarranid_head_cloth_b", 0),
			(try_end),
		(try_end),
	(try_end),
	(troop_equip_items, ":lady_no"),
	
	]
	),
	
	("init_troop_age",
	[
	(store_script_param, ":troop_no", 1),
	(store_script_param, ":age", 2), #minimum 20
	
	(try_begin),
		(gt, ":age", 20),
		(troop_set_slot, ":troop_no", slot_troop_age, 20),
	(else_try),
		(troop_set_slot, ":troop_no", slot_troop_age, ":age"),
	(try_end),
	
	(store_sub, ":years_to_age", ":age", 20),
    (troop_set_age, ":troop_no", 0),
	
	(try_begin),
		(gt, ":years_to_age", 0),
		(try_for_range, ":unused", 0, ":years_to_age"),
			(call_script, "script_age_troop_one_year", ":troop_no"),
		(try_end),
	(try_end),	
		
	]),
	
	
	("assign_troop_love_interests", #Called at the beginning, or whenever a lord is spurned
    [
	(store_script_param, ":cur_troop", 1),

	(store_faction_of_troop, ":troop_faction", ":cur_troop"),
	(try_for_range, ":unused", 0, 50),
		(store_random_in_range, ":cur_lady", kingdom_ladies_begin, kingdom_ladies_end),
		(troop_slot_eq, ":cur_lady", slot_troop_spouse, -1),
		(store_faction_of_troop, ":lady_faction", ":cur_lady"),
		(eq, ":troop_faction", ":lady_faction"),
		(call_script, "script_troop_get_family_relation_to_troop", ":cur_troop", ":cur_lady"),
		(eq, reg0, 0),

		(call_script, "script_troop_get_relation_with_troop", ":cur_troop", ":cur_lady"),
		(eq, reg0, 0), #do not develop love interest if already spurned or courted
		
		(neg|troop_slot_eq, ":cur_troop", slot_troop_love_interest_1, ":cur_lady"),
		(neg|troop_slot_eq, ":cur_troop", slot_troop_love_interest_2, ":cur_lady"),
		(neg|troop_slot_eq, ":cur_troop", slot_troop_love_interest_3, ":cur_lady"),
		(try_begin),
			(troop_slot_eq, ":cur_troop", slot_troop_love_interest_1, 0),
			(troop_set_slot, ":cur_troop", slot_troop_love_interest_1, ":cur_lady"),
		(else_try),
			(troop_slot_eq, ":cur_troop", slot_troop_love_interest_2, 0),
			(troop_set_slot, ":cur_troop", slot_troop_love_interest_2, ":cur_lady"),
		(else_try),
			(troop_slot_eq, ":cur_troop", slot_troop_love_interest_3, 0),
			(troop_set_slot, ":cur_troop", slot_troop_love_interest_3, ":cur_lady"),
		(try_end),
	(try_end),
	
	]),
	
	("faction_conclude_feast", 
	[
	(store_script_param, ":faction_no", 1),
	(store_script_param, ":venue", 2),
	
	(str_store_faction_name, s3, ":faction_no"),
	(str_store_party_name, s4, ":venue"),

    (try_begin),
        (eq, "$cheat_mode", 1),
	    (display_message, "str_s3_feast_concludes_at_s4"),
    (try_end),

	(try_begin),
		(eq, ":faction_no", "fac_player_faction"),
		(assign, ":faction_no", "$players_kingdom"),
	(try_end),
	
	(party_set_slot, ":venue", slot_town_has_tournament, 0),
	
	#markspot
	
	(assign, ":nobility_in_faction", 0),
	(assign, ":nobility_in_attendance", 0),

	(try_for_range, ":troop_no", active_npcs_begin, kingdom_ladies_end),
		(store_faction_of_troop, ":troop_faction", ":troop_no"),
		(eq, ":faction_no", ":troop_faction"),
		
		(val_add, ":nobility_in_faction", 1),

		#CHECK -- is the troop there?
		(troop_slot_eq, ":troop_no", slot_troop_cur_center, ":venue"),
		(val_add, ":nobility_in_attendance", 1),

		#check for marriages
		(troop_slot_eq, ":troop_no", slot_troop_occupation, slto_kingdom_lady),
		(troop_get_slot, ":groom", ":troop_no", slot_troop_betrothed),
		(gt, ":groom", 0),

		(troop_get_slot, ":groom_party", ":groom", slot_troop_leaded_party),
		(party_is_active, ":groom_party"),
		(party_get_attached_to, ":groom_party_attached", ":groom_party"),
		(eq, ":groom_party_attached", ":venue"),
		
		(store_faction_of_troop, ":lady_faction", ":troop_no"),
		(store_faction_of_troop, ":groom_faction", ":groom"),

		(eq, ":groom_faction", ":lady_faction"),
		(eq, ":lady_faction", ":faction_no"),
		(store_current_hours, ":hours_since_betrothal"),
		(troop_get_slot, ":betrothal_time", ":troop_no", slot_troop_betrothal_time),
		(val_sub, ":hours_since_betrothal", ":betrothal_time"),
		(ge, ":hours_since_betrothal", 144), #6 days, should perhaps eventually be 29 days, or 696 yours
				
		(call_script, "script_get_kingdom_lady_social_determinants", ":troop_no"), 
		(assign, ":wedding_venue", reg1),
				
		(eq, ":venue", ":wedding_venue"),
		(neq, ":troop_no", "trp_player"),
		(neq, ":groom", "trp_player"),

		(call_script, "script_courtship_event_bride_marry_groom", ":troop_no", ":groom", 0), #parameters from dialog
	(try_end),


#ssss	(assign, ":placeholder_reminder_to_calculate_effect_for_player_feast", 1),
	
	
	
	(party_get_slot, ":feast_host", ":venue", slot_town_lord),
	(assign, ":quality_of_feast", 0),
	
	(try_begin),
		(check_quest_active, "qst_organize_feast"),
		(quest_slot_eq, "qst_organize_feast", slot_quest_target_center, ":venue"),
		(assign, ":feast_host", "trp_player"),
		
		(assign, ":total_guests", 400),
		
		(call_script, "script_succeed_quest", "qst_organize_feast"),
		(call_script, "script_end_quest", "qst_organize_feast"),
		
		(call_script, "script_internal_politics_rate_feast_to_s9", "trp_household_possessions", ":total_guests", "$players_kingdom", 1),
		(assign, ":quality_of_feast", reg0),
	(else_try),
		(assign, ":quality_of_feast", 60),
	(try_end),
	
	
	(try_begin),
		(ge, "$cheat_mode", 1),
		(str_store_troop_name, s4, ":feast_host"),
		(assign, reg4, ":quality_of_feast"),
		(display_message, "@{!}DEBUG - {s4}'s feast has rating of {reg4}"),
	(try_end),
	
	
	(try_begin),
	  (ge, ":feast_host", 0),
	  (store_div, ":renown_boost", ":quality_of_feast", 3),
	  (call_script, "script_change_troop_renown", ":feast_host", ":renown_boost"),

	  (try_for_range, ":troop_no", active_npcs_begin, active_npcs_end),
		(troop_slot_eq, ":troop_no", slot_troop_occupation, slto_kingdom_hero),
		(troop_get_slot, ":leaded_party", ":troop_no", slot_troop_leaded_party),
		(party_is_active, ":leaded_party"),
		(party_get_attached_to, ":leaded_party_attached", ":leaded_party"),
		(eq, ":leaded_party_attached", ":venue"),
		
		(assign, ":relation_booster", ":quality_of_feast"),
		(val_div, ":relation_booster", 20),
		
		(try_begin),
			(eq, ":feast_host", "trp_player"),
			(val_sub, ":relation_booster", 1),
			(val_max, ":relation_booster", 0),
		(try_end),
		(call_script, "script_troop_change_relation_with_troop", ":feast_host", ":troop_no", ":relation_booster"),
		(val_add, "$total_feast_changes", ":relation_booster"),
	  (try_end),
	(try_end),
	

	(assign, reg3, ":nobility_in_attendance"),
	(assign, reg4, ":nobility_in_faction"),
	
	(try_begin),
		(eq, "$cheat_mode", 1),
		(display_message, "str_attendance_reg3_nobles_out_of_reg4"),
	(try_end),	
	]),

	("lady_evaluate_troop_as_suitor", 
	[
	(store_script_param, ":lady", 1),
	(store_script_param, ":suitor", 2),
	
	(call_script, "script_troop_get_romantic_chemistry_with_troop", ":lady", ":suitor"),
	(assign, ":romantic_chemistry", reg0),
	
	(try_begin),
      (call_script, "script_cf_test_lord_incompatibility_to_s17", ":lady", ":suitor"),		
    (try_end),
	
	(store_sub, ":personality_modifier", 0, reg0),
	(assign, reg2, ":personality_modifier"),
		
	(try_begin),
		(troop_get_slot, ":renown_modifier", ":suitor", slot_troop_renown),
		(val_div, ":renown_modifier", 20),
		(try_begin),
			(this_or_next|troop_slot_eq, ":lady", slot_lord_reputation_type, lrep_conventional),
				(troop_slot_eq, ":lady", slot_lord_reputation_type, lrep_ambitious),
			(val_mul, ":renown_modifier", 2),
			(val_sub, ":renown_modifier", 15),
		(try_end),
	(try_end),
	
	(store_add, ":final_score", ":renown_modifier", ":personality_modifier"),
	(val_add, ":final_score", ":romantic_chemistry"),
	(assign, reg0, ":final_score"),	
	]),
	
	("courtship_event_troop_court_lady", 
	[
	(store_script_param, ":suitor", 1),
	(store_script_param, ":lady", 2),

	
	#(try_begin),
	  #(eq, "$cheat_mode", 1),
	  #(str_store_troop_name, s4, ":suitor"),
	  #(str_store_troop_name, s5, ":lady"),
	  #(troop_get_slot, ":lady_location", ":lady", slot_troop_cur_center),
	  #(str_store_party_name, s7, ":lady_location"),
	  #(display_message, "str_s4_pursues_suit_with_s5_in_s7"),
	#(try_end),
	
	(troop_get_slot, ":previous_suitor", ":lady", slot_lady_last_suitor),
	(troop_set_slot, ":lady", slot_lady_last_suitor, ":suitor"), #can determine quarrels
	
	(try_begin),
		(eq, ":previous_suitor", "trp_player"),
		
		(troop_slot_ge, ":lady", slot_troop_met, 2),
		(call_script, "script_troop_get_relation_with_troop", ":suitor", "trp_player"), #add this to list of quarrels
		(assign, ":suitor_relation_w_player", reg0),
		
		(try_begin),
			(this_or_next|troop_slot_eq, ":suitor", slot_lord_reputation_type, lrep_selfrighteous),
			(this_or_next|troop_slot_eq, ":suitor", slot_lord_reputation_type, lrep_quarrelsome),
				(troop_slot_eq, ":suitor", slot_lord_reputation_type, lrep_debauched),
			(gt, ":suitor_relation_w_player", -20),
			(call_script, "script_add_log_entry", logent_lords_quarrel_over_woman, ":suitor", "trp_player", ":lady", 0),
		(else_try),
			(is_between, ":suitor_relation_w_player", -5, -25),
			(call_script, "script_add_log_entry", logent_lords_quarrel_over_woman, ":suitor", "trp_player", ":lady", 0),
		(try_end),
	(else_try),
		(neq, ":previous_suitor", "trp_player"), #not the player
	
		(neq, ":suitor", ":previous_suitor"),
		(ge, ":previous_suitor", active_npcs_begin),
		
		(call_script, "script_cf_test_lord_incompatibility_to_s17", ":suitor", ":previous_suitor"),
		(call_script, "script_add_log_entry", logent_lords_quarrel_over_woman, ":suitor", ":previous_suitor", ":lady", 0),
		
		(call_script, "script_troop_get_relation_with_troop", ":suitor", ":previous_suitor"), #add this to list of quarrels
		(ge, reg0, 0),
		(call_script, "script_troop_change_relation_with_troop", ":suitor", ":previous_suitor", -20),
		(val_add, "$total_courtship_quarrel_changes", -20),
	(else_try),	 #quarrelsome lords quarrel anyway
		(troop_slot_eq, ":suitor", slot_lord_reputation_type, lrep_quarrelsome),
		(neq, ":suitor", ":previous_suitor"),
		(ge, ":previous_suitor", active_npcs_begin),
		
#		(neq, ":previous_suitor", "trp_player"),
		
		(call_script, "script_troop_get_relation_with_troop", ":suitor", ":previous_suitor"), #add this to list of quarrels
		(lt, reg0, 10),
		(call_script, "script_add_log_entry", logent_lords_quarrel_over_woman, ":suitor", ":previous_suitor", ":lady", 0),
		(ge, reg0, 0),
		(call_script, "script_troop_change_relation_with_troop", ":suitor", ":previous_suitor", -20),
		(val_add, "$total_courtship_quarrel_changes", -20),
		
	(try_end),
	
	
#	(call_script, "script_troop_get_relation_with_troop", ":lady", ":suitor"),
#	(assign, ":orig_relation", reg0),

    (call_script, "script_lady_evaluate_troop_as_suitor", ":lady", ":suitor"),
	
	(store_random_in_range, ":random", 5, 16),
	(store_div, ":relationship_change", reg0, ":random"),
	
	(call_script, "script_troop_get_relation_with_troop", ":lady", ":suitor"),
	(assign, ":orig_relation", reg0),

	(call_script, "script_troop_change_relation_with_troop", ":lady", ":suitor", ":relationship_change"),
	
	(call_script, "script_troop_get_relation_with_troop", ":lady", ":suitor"),
	(assign, ":lady_suitor_relation", reg0),
		
	(try_begin),
		(ge, ":lady_suitor_relation", 10),
		(lt, ":orig_relation", 10),
		(call_script, "script_add_log_entry", logent_lady_favors_suitor, ":lady", 0, ":suitor", 0),
		
		(try_begin),
			(eq, "$cheat_mode", 1),
			(display_message, "str_note__favor_event_logged"),
		(try_end),
		
	(else_try),
		(this_or_next|lt, ":lady_suitor_relation", -20),
			(ge, ":lady_suitor_relation", 20),

		(call_script, "script_get_kingdom_lady_social_determinants", ":lady"),
		(assign, ":guardian", reg0),
		(call_script, "script_troop_get_relation_with_troop", ":suitor", ":guardian"),
		(assign, ":suitor_guardian_relation", reg0),
		#things come to a head, one way or another
		
		(assign, ":highest_competitor_lady_score", -1),
		(assign, ":competitor_preferred_by_lady", -1),
		
		(assign, ":highest_competitor_guardian_score", ":suitor_guardian_relation"),
		(assign, ":competitor_preferred_by_guardian", -1),
		
		#log potential competitors
		(try_for_range, ":possible_competitor", lords_begin, lords_end),
			(neq, ":possible_competitor", ":suitor"),
		
			(this_or_next|troop_slot_eq, ":possible_competitor", slot_troop_love_interest_1, ":lady"),
			(this_or_next|troop_slot_eq, ":possible_competitor", slot_troop_love_interest_2, ":lady"),
				(troop_slot_eq, ":possible_competitor", slot_troop_love_interest_3, ":lady"),
			
			(try_begin),
				(call_script, "script_troop_get_relation_with_troop", ":possible_competitor", ":lady"),
				(gt, reg0, ":highest_competitor_lady_score"),
				(assign, ":competitor_preferred_by_lady", ":possible_competitor"),
				(assign, ":highest_competitor_lady_score", reg0),
			(try_end),	

			(try_begin),
				(call_script, "script_troop_get_relation_with_troop", ":possible_competitor", ":guardian"),
				(gt, reg0, ":highest_competitor_guardian_score"),
				(assign, ":competitor_preferred_by_guardian", ":possible_competitor"),
				(assign, ":highest_competitor_guardian_score", reg0),
			(try_end),	
		(try_end),

		#RESULTS
		#Guardian forces lady to be betrothed to suitor now		
		(try_begin), 
			(lt, ":lady_suitor_relation", -20),
			(this_or_next|troop_slot_eq, ":guardian", slot_lord_reputation_type, lrep_selfrighteous),
			(this_or_next|troop_slot_eq, ":guardian", slot_lord_reputation_type, lrep_debauched),
				(troop_slot_eq, ":guardian", slot_lord_reputation_type, lrep_quarrelsome),
			(eq, ":competitor_preferred_by_guardian", -1),

			(this_or_next|troop_slot_eq, ":suitor", slot_lord_reputation_type, lrep_selfrighteous),
			(this_or_next|troop_slot_eq, ":suitor", slot_lord_reputation_type, lrep_debauched),
				(troop_slot_eq, ":suitor", slot_lord_reputation_type, lrep_quarrelsome),

			(troop_slot_eq, ":suitor", slot_troop_betrothed, -1),
			(troop_slot_eq, ":lady", slot_troop_betrothed, -1),
				
			(call_script, "script_add_log_entry", logent_lady_betrothed_to_suitor_by_family, ":lady", 0, ":suitor", 0),
			(troop_set_slot, ":suitor", slot_troop_betrothed, ":lady"),
			(troop_set_slot, ":lady", slot_troop_betrothed, ":suitor"),
			(store_current_hours, ":hours"),
			(troop_set_slot, ":lady", slot_troop_betrothal_time, ":hours"),
			(troop_set_slot, ":suitor", slot_troop_betrothal_time, ":hours"),
			(try_begin),
				(eq, "$cheat_mode", 1),
				(display_message, "str_result_lady_forced_to_agree_to_engagement"),
			(try_end),

		#Lady rejects the suitor			
		(else_try),
			(lt, ":lady_suitor_relation", -20),
			
			(call_script, "script_add_log_entry", logent_lady_rejects_suitor, ":lady", 0, ":suitor", 0),
			(call_script, "script_courtship_event_lady_break_relation_with_suitor", ":lady", ":suitor"),
			(try_begin),
				(eq, "$cheat_mode", 1),
				(display_message, "str_result_lady_rejects_suitor"),
			(try_end),

		#A happy engagement, with parental blessing
		(else_try),	
			(gt, ":lady_suitor_relation", 20),
			(gt, ":suitor_guardian_relation", 0),
			(eq, ":competitor_preferred_by_lady", -1),

			(troop_slot_eq, ":suitor", slot_troop_betrothed, -1),
			(troop_slot_eq, ":lady", slot_troop_betrothed, -1),
			
			(call_script, "script_add_log_entry", logent_lady_betrothed_to_suitor_by_choice, ":lady", 0, ":suitor", 0),
			(troop_set_slot, ":suitor", slot_troop_betrothed, ":lady"),
			(troop_set_slot, ":lady", slot_troop_betrothed, ":suitor"),
			(store_current_hours, ":hours"),
			(troop_set_slot, ":lady", slot_troop_betrothal_time, ":hours"),
			(troop_set_slot, ":suitor", slot_troop_betrothal_time, ":hours"),
			
			(try_begin),
				(eq, "$cheat_mode", 1),
				(str_store_troop_name, s4, ":lady"),
				(str_store_troop_name, s5, ":suitor"),
				(display_message, "str_result_happy_engagement_between_s4_and_s5"),
			(try_end),
			
		#Lady elopes
		(else_try), 
			(gt, ":lady_suitor_relation", 20),
			
			(eq, ":competitor_preferred_by_lady", -1),
			(this_or_next|troop_slot_eq, ":guardian", slot_lord_reputation_type, lrep_adventurous),
				(troop_slot_eq, ":guardian", slot_lord_reputation_type, lrep_ambitious),
				
			(troop_slot_eq, ":suitor", slot_troop_betrothed, -1),
			(troop_slot_eq, ":lady", slot_troop_betrothed, -1),
				
			#lady elopes
			(call_script, "script_courtship_event_bride_marry_groom", ":lady", ":suitor", 1),
			#add elopements to quarrel descriptions
					
			(try_begin),
				(eq, "$cheat_mode", 1),
				(str_store_troop_name, s4, ":lady"),
				(str_store_troop_name, s5, ":suitor"),
				(display_message, "str_result_s4_elopes_with_s5"),
			(try_end),
			
		#Lady reluctantly agrees to marry under pressure from family			
		(else_try),	
			(troop_slot_eq, ":lady", slot_lord_reputation_type, lrep_conventional),
			(eq, ":competitor_preferred_by_guardian", -1),
			(gt, ":suitor_guardian_relation", 4),
			
			(store_random_in_range, ":random", 0, 5),
			(eq, ":random", 0),
			
			(troop_slot_eq, ":suitor", slot_troop_betrothed, -1),
			(troop_slot_eq, ":lady", slot_troop_betrothed, -1),

			(call_script, "script_add_log_entry", logent_lady_betrothed_to_suitor_by_pressure, ":lady", 0, ":suitor", 0),
			(troop_set_slot, ":suitor", slot_troop_betrothed, ":lady"),
			(troop_set_slot, ":lady", slot_troop_betrothed, ":suitor"),
			(store_current_hours, ":hours"),
			(troop_set_slot, ":lady", slot_troop_betrothal_time, ":hours"),
			(troop_set_slot, ":suitor", slot_troop_betrothal_time, ":hours"),
			(try_begin),
				(eq, "$cheat_mode", 1),
				(str_store_troop_name, s4, ":lady"),
				(str_store_troop_name, s5, ":suitor"),				
				(display_message, "str_result_s4_reluctantly_agrees_to_engagement_with_s5"),
			(try_end),

		#Stalemate -- make patience roll
		(else_try), 
			(gt, ":lady_suitor_relation", 20),

			(store_random_in_range, reg3, 0, 3),
			(try_begin),
				(eq, "$cheat_mode", 1),
				(display_message, "str_result_stalemate_patience_roll_=_reg3"),
			(try_end),

			(eq, reg3, 0),
			(call_script, "script_add_log_entry", logent_lady_rejected_by_suitor, ":lady", 0, ":suitor", 0),
			(call_script, "script_courtship_event_lady_break_relation_with_suitor", ":lady", ":suitor"),
		(try_end),
		
	(try_end),
	
	]),


		
	("courtship_event_lady_break_relation_with_suitor", #parameters from dialog
	[
	(store_script_param, ":lady", 1),
	(store_script_param, ":suitor", 2),
	
	(try_for_range, ":love_interest_slot", slot_troop_love_interest_1, slot_troop_love_interests_end),
		(troop_slot_eq, ":suitor", ":love_interest_slot", ":lady"),
		(troop_set_slot, ":suitor", ":love_interest_slot", 0),
	(try_end),
	(call_script, "script_assign_troop_love_interests", ":suitor"),
	
	(try_begin),
		(troop_slot_eq, ":lady", slot_troop_betrothed, ":suitor"),
				
		
		(troop_set_slot, ":lady", slot_troop_betrothed, -1),
		(troop_set_slot, ":suitor", slot_troop_betrothed, -1),
	(try_end),
	
	
	]),
	

	("courtship_event_bride_marry_groom", #parameters from dialog or scripts
	[
	(store_script_param, ":bride", 1),
	(store_script_param, ":groom", 2),
	(store_script_param, ":elopement", 3),

	(try_begin),
		(eq, ":bride", "trp_player"),
		(assign, ":venue", "$g_encountered_party"),
	(else_try),	
		(troop_get_slot, ":venue", ":bride", slot_troop_cur_center),
	(try_end),
	
	(store_faction_of_troop, ":groom_faction", ":groom"),
	
	
	(try_begin),
		(eq, ":elopement", 0),
		(call_script, "script_add_log_entry", logent_lady_marries_suitor, ":bride", ":venue", ":groom", 0),
	(else_try),
		(call_script, "script_add_log_entry", logent_lady_elopes_with_lord, ":bride", ":venue", ":groom", 0),
	(try_end),
	
	(str_store_troop_name, s3, ":bride"), 
	(str_store_troop_name, s4, ":groom"), 
	(str_store_party_name, s5, ":venue"), 

	(try_begin),
        (eq, "$cheat_mode", 1),
	    (display_message, "str_s3_marries_s4_at_s5"),
    (try_end),
	
	(troop_set_slot, ":bride", slot_troop_spouse, ":groom"),
	(troop_set_slot, ":groom", slot_troop_spouse, ":bride"),
	
	#Break groom's romantic relations
	(try_for_range, ":love_interest_slot", slot_troop_love_interest_1, slot_troop_love_interests_end),
		(troop_set_slot, ":groom", ":love_interest_slot", 0),
	(try_end),

	#Break bride's romantic relations
	(try_for_range, ":active_npc", active_npcs_begin, active_npcs_end),
		(try_for_range, ":love_interest_slot", slot_troop_love_interest_1, slot_troop_love_interests_end),
			(troop_slot_eq, ":active_npc", ":love_interest_slot", ":bride"),
			(call_script, "script_courtship_event_lady_break_relation_with_suitor", ":bride", ":active_npc"),
		(try_end),
	(try_end),
	
	
	
	(troop_set_slot, ":bride", slot_troop_betrothed, -1),
	(troop_set_slot, ":groom", slot_troop_betrothed, -1),
	
	
	
    #change relations with family
	(try_for_range, ":family_member", lords_begin, lords_end),
		(call_script, "script_troop_get_family_relation_to_troop", ":bride", ":family_member"),
		(gt, reg0, 0),
		(store_div, ":family_relation_boost", reg0, 3),
		(try_begin),
			(eq, ":elopement", 1),
			(val_mul, ":family_relation_boost", -2),
		(try_end),
		(call_script, "script_troop_change_relation_with_troop", ":groom", ":bride", ":family_relation_boost"),
		(val_add, "$total_courtship_quarrel_changes", ":family_relation_boost"),
	(try_end),
	
	(try_begin),
		(this_or_next|eq, ":groom", "trp_player"),
			(eq, ":bride", "trp_player"),
		(call_script, "script_change_player_right_to_rule", "trp_player", 15),
	(try_end),
	
	
	(try_begin),
		(eq, ":groom", "trp_player"),
		(check_quest_active, "qst_wed_betrothed"),
		(call_script, "script_succeed_quest", "qst_wed_betrothed"),
		(call_script, "script_end_quest", "qst_wed_betrothed"),
	(try_end),

	
	(try_begin),
		(check_quest_active, "qst_visit_lady"),
		(quest_slot_eq, "qst_visit_lady", slot_quest_giver_troop, ":bride"),
		(call_script, "script_abort_quest", "qst_visit_lady", 0),
	(try_end),

	
	(try_begin),
		(eq, ":groom", "trp_player"),
		(check_quest_active, "qst_visit_lady"),
		(call_script, "script_abort_quest", "qst_visit_lady", 0),
	(try_end),	
	(try_begin),
		(eq, ":groom", "trp_player"),
		(check_quest_active, "qst_duel_courtship_rival"),
		(call_script, "script_abort_quest", "qst_duel_courtship_rival", 0),
	(try_end),	
	
	
	(try_begin),
		(eq, ":bride", "trp_player"),
	    (call_script, "script_player_join_faction", ":groom_faction"),
		(assign, "$player_has_homage", 1),
	(else_try),
		(eq, ":groom", "trp_player"),
		
		(try_begin),
			(ge, "$cheat_mode", 1),
			(str_store_troop_name, s4, ":bride"),
			(display_message, "@{!} DEBUG - {s4} faction change in marriage case 5"),
		(try_end),
		(troop_set_faction, ":bride", "$players_kingdom"),
	(else_try),
	
		(try_begin),
			(ge, "$cheat_mode", 1),
			(str_store_troop_name, s4, ":bride"),
			(display_message, "@{!}DEBUG - {s4} faction changed by marriage, case 6"), 
		(try_end),
	
		(troop_set_faction, ":bride", ":groom_faction"),
	(try_end),

    (try_begin),
        (this_or_next|eq, ":groom", "trp_player"),
           (eq, ":bride", "trp_player"),   
        (unlock_achievement, ACHIEVEMENT_HAPPILY_EVER_AFTER),
		(try_begin),
			(eq, ":elopement", 1),
			(unlock_achievement, ACHIEVEMENT_HEART_BREAKER),
		(try_end),
    (try_end),
	
	
	
    (try_begin),
        (this_or_next|eq, ":groom", "trp_player"),
           (eq, ":bride", "trp_player"),
		#(eq, ":elopement", 0),    
        (call_script, "script_start_wedding_cutscene", ":groom", ":bride"),
    (try_end),
	]),


    #script_npc_decision_checklist_party_ai   
	# DECISION CHECKLISTS (OCT 14)
	# I was thinking of trying to convert as much AI decision-making as possible to the checklist format
	# While outcomes are not as nuanced and varied as a random decision using weighted chances for each outcoms, 
	# the checklist has the advantage of being much more transparent, both to developers and to players
	# The checklist can yield a string (standardized to s14) which explains the rationale for the decision
	# When the script yields a yes/no/maybe result, than that is standardized from -3 to +3
    # INPUT: troop_no
    # OUTPUT: none
	("npc_decision_checklist_party_ai", 
	[
	#this script can replace decide_kingdom_hero_ai and decide_kingdom_hero_ai_follow_or_not
	#However, it does not contain script_party_set_ai_state
	
	(store_script_param, ":troop_no", 1),
	
	(troop_get_slot, ":party_no", ":troop_no", slot_troop_leaded_party),
    #(party_get_slot, ":our_strength", ":party_no", slot_party_cached_strength),
    #(store_div, ":min_strength_behind", ":our_strength", 2),
    #(party_get_slot, ":our_follower_strength", ":party_no", slot_party_follower_strength),

    (try_begin),
      (eq, "$cheat_mode", 1),
      (assign, "$g_talk_troop", ":troop_no"),
    (try_end),

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

	(try_begin),
      (eq, ":troop_no", "$g_talk_troop"),
      (str_store_string, s15, "str__i_must_attend_to_this_matter_before_i_worry_about_the_affairs_of_the_realm"),
	(try_end),
	
    #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),
    (assign, ":besieger_party", -1),
    (try_begin),
      (neg|is_between, ":cur_center_no", centers_begin, centers_end),
      (assign, ":cur_center_no", -1),
    (else_try),
      (party_get_slot, ":besieger_party", ":cur_center_no", slot_center_is_besieged_by),
      (try_begin),
        (neg|party_is_active, ":besieger_party"),
        (assign, ":besieger_party", -1),
      (try_end),
    (try_end),
    
	#party_count
    (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_strength_as_percentage_of_ideal", ":party_fit_for_battle", 100),
    (val_div, ":party_strength_as_percentage_of_ideal", ":ideal_size"),
    (try_begin),
      (faction_slot_eq, ":faction_no", slot_faction_num_towns, 0),
      (faction_slot_eq, ":faction_no", slot_faction_num_castles, 0),
      (assign, ":party_ratio_of_prisoners", 0), #do not let prisoners have an effect on ai calculation
    (else_try),
      (party_get_num_prisoners, ":num_prisoners", ":party_no"),
      (val_max, ":party_fit_for_battle", 1), #avoid division by zero error
      (store_div, ":party_ratio_of_prisoners", ":num_prisoners", ":party_fit_for_battle"),
    (try_end),
				
	(assign, ":faction_is_at_war", 0),
	(try_for_range, ":kingdom", kingdoms_begin, kingdoms_end),
	  (faction_slot_eq, ":kingdom", slot_faction_state, sfs_active),
	  (store_relation, ":relation", ":faction_no", ":kingdom"),
	  (lt, ":relation", 0),
	  (assign, ":faction_is_at_war", 1),
	(try_end),
	
	(assign, ":operation_in_progress", 0),
	(try_begin),
	  (this_or_next|party_slot_eq, ":party_no", slot_party_ai_state, spai_raiding_around_center),
	  (party_slot_eq, ":party_no", slot_party_ai_state, spai_besieging_center),
	  
	  (party_get_slot, ":target_center", ":party_no", slot_party_ai_object),
	  (is_between, ":target_center", centers_begin, centers_end),
	  
	  (store_faction_of_party, ":target_center_faction", ":target_center"),
	  (store_relation, ":relation", ":faction_no", ":target_center_faction"),
	  (lt, ":relation", 0),
	  
	  (store_distance_to_party_from_party, ":distance", ":party_no", ":target_center"),
	  (lt, ":distance", 10),
	  (this_or_next|party_slot_eq, ":target_center", slot_village_state, svs_under_siege),
	  (this_or_next|party_slot_eq, ":target_center", slot_village_state, svs_normal),
	  (party_slot_eq, ":target_center", slot_village_state, svs_being_raided),
	  
	  (assign, ":operation_in_progress", 1),	
	(try_end),
			
	(troop_get_slot, ":troop_reputation", ":troop_no", slot_lord_reputation_type),
			
    (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_slot, ":party_cached_strength", ":party_no", slot_party_cached_strength),
	
	(store_current_hours, ":hours_since_last_rest"),
	(party_get_slot, ":last_rest_time", ":party_no", slot_party_last_in_any_center),
	(val_sub, ":hours_since_last_rest", ":last_rest_time"),

	(store_current_hours, ":hours_since_last_home"),
	(party_get_slot, ":last_home_time", ":party_no", slot_party_last_in_home_center),
	(val_sub, ":hours_since_last_home", ":last_home_time"),
	
	(store_current_hours, ":hours_since_last_combat"),
	(party_get_slot, ":last_combat_time", ":party_no", slot_party_last_in_combat),
	(val_sub, ":hours_since_last_combat", ":last_combat_time"),
	
	(store_current_hours, ":hours_since_last_courtship"),
	(party_get_slot, ":last_courtship_time", ":party_no", slot_party_leader_last_courted),
	(val_sub, ":hours_since_last_courtship", ":last_courtship_time"),
	
    (troop_get_slot, ":temp_ai_seed", ":troop_no", slot_troop_temp_decision_seed),
    (store_mod, ":aggressiveness", ":temp_ai_seed", 73), #To derive the 
    (try_begin),
      (eq, ":troop_reputation", lrep_martial),
      (val_add, ":aggressiveness", 27),
    (else_try),
      (neq, ":troop_reputation", lrep_debauched),
      (neq, ":troop_reputation", lrep_quarrelsome),
      (val_add, ":aggressiveness", 14),
    (try_end),
    (try_begin),
      (eq, ":faction_no", "fac_dark_knights"),
      (val_add, ":aggressiveness", 36),
    (try_end),
    
    (try_begin),
      (gt, ":aggressiveness", ":hours_since_last_combat"),
      (val_add, ":aggressiveness", ":hours_since_last_combat"),
      (val_div, ":aggressiveness", 2),
    (try_end),        
    
    (try_begin),
      (eq, "$cheat_mode", 1), #100
      (eq, ":troop_no", "$g_talk_troop"),
      (str_store_troop_name, s4, ":troop_no"), 
      (assign, reg3, ":hours_since_last_rest"),
      (assign, reg4, ":hours_since_last_courtship"),
      (assign, reg5, ":hours_since_last_combat"),
      (assign, reg6, ":hours_since_last_home"),
      (assign, reg7, ":aggressiveness"),
      #(display_message, "@{!}{s4}: hours since rest {reg3}, courtship {reg4}, combat {reg5}, home {reg6}, aggressiveness {reg7}"),
    (try_end),
		
	##I am inspecting an estate (use slot_center_npc_volunteer_troop_amount)
		
	(str_store_string, s17, "str_the_other_matter_took_precedence"),
	
	(assign, ":do_only_collecting_rents", 0),
	
	#Wait in current city (dangerous to travel with less (<=10) men)
	(try_begin),	
      #NOTE : I added also this condition to very top of list. Because if this condition does not exists in top then a bug happens. 
      #Bug is about alone wounded lords without any troop near him travels between cities, sometimes it want to return his home city 
      #to collect reinforcements, sometimes it want to patrol ext, but his party is so weak even without anyone. So we sometimes see 
      #(0/1) parties in map with only one wounded lord inside. Because after wars completely defeated lords spawn again in a walled center 
      #in 48 hours periods (by codes in module_simple_trigers). He spawns with only wounded himself. Then he should wait in there for 
      #a time to collect new men to his (0/1) party. If a lord is the only one in his party and if he is at any walled center already then he 
      #should stay where he is. He should not travel to anywhere because of any reason. If he is the only one and he is wounded and 
      #he is not in any walled center this means this situation happens because of one another bug, because any lord cannot be out of 
      #walled centers with wounded himself only. So I am adding this condition below. 
      
      #SUMMARY : If lord has not got enought troops (<10 || <10%) with himself and he is currently at a walled center he should not leave 
      #his current center because of any reason.
      
      (ge, ":cur_center_no", 0),

      (this_or_next|le, ":party_fit_for_battle", 10),
      (le, ":party_strength_as_percentage_of_ideal", 30),

      (assign, ":action", spai_holding_center),
      (assign, ":object", ":cur_center_no"),

	  (try_begin),
	    (eq, ":troop_no", "$g_talk_troop"), 
	    (str_store_string, s14, "str_i_need_to_raise_some_men_before_attempting_anything_else"),
	    (str_store_string, s16, "str_i_need_to_raise_some_men_before_attempting_anything_else"),
	  (try_end),
	  
	#Stand in a siege
	(else_try),
	  (gt, ":besieger_party", -1),
	  
	  (assign, ":action", spai_holding_center),
	  (assign, ":object", ":cur_center_no"),
	  
	  (try_begin), 
	    (eq, ":troop_no", "$g_talk_troop"),
	    (str_store_string, s14, "str_i_cannot_leave_this_fortress_now_as_it_is_under_siege"),
	    (str_store_string, s16, "str_after_all_we_are_under_siege"),
	  (try_end),
		
	#Continue retreat to walled center
	(else_try),
	  (eq, ":old_ai_state", spai_retreating_to_center),
	  (neg|party_is_in_any_town, ":party_no"),
	  
	  (ge, ":old_ai_object", 0),
	  (party_is_active, ":old_ai_object"),
	  
	  (store_faction_of_party, ":retreat_center_faction", ":old_ai_object"),
	  (eq, ":faction_no", ":retreat_center_faction"),
	  
	  (assign, ":action", spai_retreating_to_center),
	  (assign, ":object", ":old_ai_object"),
	  	  
	  (try_begin),
	    (eq, ":troop_no", "$g_talk_troop"),
	    (str_store_string, s14, "str_we_are_not_strong_enough_to_face_the_enemy_out_in_the_open"),
	    (str_store_string, s16, "str_i_should_probably_seek_shelter_behind_some_stout_walls"),
	  (try_end),

	#Stand by in current center against enemies		
	(else_try),
	  (is_between, ":cur_center_no", walled_centers_begin, walled_centers_end),
	  
	  (party_get_slot, ":enemy_strength_in_area", ":cur_center_no", slot_center_sortie_enemy_strength),
	  (party_get_slot, ":enemy_strength_in_area", ":cur_center_no", slot_center_sortie_enemy_strength),
	  (ge, ":enemy_strength_in_area", 50),
	  
	  (assign, ":action", spai_holding_center),
	  (assign, ":object", ":cur_center_no"),
	  (try_begin),
	    (eq, ":troop_no", "$g_talk_troop"),
	    (str_store_string, s14, "str_enemies_are_reported_to_be_nearby_and_we_should_stand_ready_to_either_man_the_walls_or_sortie_out_to_do_battle"),
	    (str_store_string, s16, "str_the_enemy_is_nearby"),
	  (try_end),
	  
	#As the marshall, lead faction campaign
	(else_try),
	  (faction_slot_eq, ":faction_no", slot_faction_marshall, ":troop_no"),
	  (str_clear, s15), #Does not say that overrides faction orders
	  (faction_slot_eq, ":faction_no", slot_faction_ai_state, sfai_gathering_army),
	  
	  (party_set_ai_initiative, ":party_no", 10),
	  	  
	  #new ozan added - active gathering
	  #this code will allow marshal to travel around cities while gathering army if currently collected are less than 60%. 
	  #By ratio increases travel distances become less. Travels will be only points around walled centers.
	  (party_get_slot, ":old_ai_object", ":party_no", slot_party_ai_object),
	  (assign, ":travel_target", ":old_ai_object"),
      
      (call_script, "script_find_center_to_defend", ":troop_no"),
	  (assign, ":most_threatened_center", reg0),	  
	  (assign, ":travel_target_new_assigned", 0),
	  
      (try_begin),
        (lt, ":old_ai_object", 0),
        
        (store_random_in_range, ":random_value", 0, 8), #to eanble marshal to wait sometime during active gathering
        (this_or_next|eq, "$g_gathering_new_started", 1),
        (eq, ":random_value", 0),
        
        (assign, ":vassals_already_assembled", 0),
        (assign, ":total_vassals", 0),
        (try_for_range, ":lord", active_npcs_begin, active_npcs_end),
          (store_faction_of_troop, ":lord_faction", ":lord"),
          (eq, ":lord_faction", ":faction_no"),
          (troop_get_slot, ":led_party", ":lord", slot_troop_leaded_party),
          (party_is_active, ":led_party"),
          (val_add, ":total_vassals", 1),
          
          (party_slot_eq, ":led_party", slot_party_ai_state, spai_accompanying_army),
          (party_slot_eq, ":led_party", slot_party_ai_object, ":party_no"),
          
          (party_is_active, ":party_no"),
          (store_distance_to_party_from_party, ":distance_to_marshal", ":led_party", ":party_no"),
          (lt, ":distance_to_marshal", 15),
          (val_add, ":vassals_already_assembled", 1),
        (try_end),
     
        (assign, ":ratio_of_vassals_assembled", -1),
        (try_begin),
          (gt, ":total_vassals", 0),
          (store_mul, ":ratio_of_vassals_assembled", ":vassals_already_assembled", 100),
          (val_div, ":ratio_of_vassals_assembled", ":total_vassals"),
        (try_end),
          
        (try_begin),
          #if more than 35% of vassals already collected do not make any more active gathering, just hold and wait last vassals to participate.
          (le, ":ratio_of_vassals_assembled", 35), 
                      
          (assign, ":best_center_to_travel", ":most_threatened_center"),          

          (try_begin),
            (eq, "$g_gathering_new_started", 1),
            
            (assign, ":minimum_distance", 100000),
            (try_for_range, ":center_no", centers_begin, centers_end),
              (store_faction_of_party, ":center_faction", ":center_no"),
              (eq, ":center_faction", ":faction_no"),
              (try_begin),
                (neq, ":center_no", ":most_threatened_center"), #200
                (store_distance_to_party_from_party, ":dist", ":party_no", ":center_no"),                
                (lt, ":dist", ":minimum_distance"),
                (assign, ":minimum_distance", ":dist"),
                (assign, ":best_center_to_travel", ":center_no"),
              (try_end), 
            (try_end),
          (else_try), 
            #active gathering            
            (assign, ":max_travel_distance", 150),
            (try_begin),
              (ge, ":ratio_of_vassals_assembled",15),
              (store_sub, ":max_travel_distance", 35, ":ratio_of_vassals_assembled"),
              (val_add, ":max_travel_distance", 5), #5..25
              (val_mul, ":max_travel_distance", 6), #30..150
            (try_end),
            
            (try_begin),
              (ge, ":most_threatened_center", 0),
              (store_distance_to_party_from_party, reg12, ":party_no", ":most_threatened_center"),
            (else_try),  
              (assign, reg12, 0),
            (try_end),
              
            (assign, ":num_centers", 0),
            (try_for_range, ":center_no", walled_centers_begin, walled_centers_end),
              (store_faction_of_party, ":center_faction", ":center_no"),
              (eq, ":center_faction", ":faction_no"),
              (try_begin),
                #(ge, ":max_travel_distance", 0),
                (store_distance_to_party_from_party, ":dist", ":party_no", ":center_no"),
                
                (try_begin),
                  (ge, ":most_threatened_center", 0),
                  (store_distance_to_party_from_party, reg13, ":center_no", ":most_threatened_center"),
                (else_try),  
                  (assign, reg13, 0),
                (try_end),

                (store_sub, reg11, reg13, reg12),
                
                (this_or_next|ge, reg11, 40),                
                (this_or_next|ge, ":dist", ":max_travel_distance"),
                (eq, ":center_no", ":most_threatened_center"),
              (else_try),
                #this center is a candidate so increase num_centers by one.
                (val_add, ":num_centers", 1),
              (try_end), 
            (try_end),
            
            (try_begin),
              (ge, ":num_centers", 0),
              (store_random_in_range, ":random_center_no", 0, ":num_centers"),
              (val_add, ":random_center_no", 1),
              (assign, ":num_centers", 0),
              (try_for_range, ":center_no", walled_centers_begin, walled_centers_end),
                (store_faction_of_party, ":center_faction", ":center_no"),
                (eq, ":center_faction", ":faction_no"),
                (try_begin),
                  (neq, ":center_no", ":most_threatened_center"),
                  (store_distance_to_party_from_party, ":dist", ":party_no", ":center_no"),
                  (lt, ":dist", ":max_travel_distance"),
                  
                  (try_begin),
                    (ge, ":most_threatened_center", 0),
                    (store_distance_to_party_from_party, reg13, ":center_no", ":most_threatened_center"),
                  (else_try),  
                    (assign, reg13, 0),
                  (try_end),

                  (store_sub, reg11, reg13, reg12),                
                  (lt, reg11, 40),                
                  
                  (val_sub, ":random_center_no", 1),
                  (eq, ":random_center_no", 0),
                  (assign, ":best_center_to_travel", ":center_no"),
                (try_end),
              (try_end),                            
            (try_end),
          (try_end),  
          
          (assign, ":travel_target", ":best_center_to_travel"),          
          (assign, ":travel_target_new_assigned", 1),
        (try_end),
      (else_try),
        #if party has an ai object and they are close to that object while gathering army, 
        #forget that ai object so they will select a new ai object next.
        (is_between, ":old_ai_object", centers_begin, centers_end),
        (party_get_position, pos1, ":party_no"),
        (party_get_position, pos2, ":old_ai_object"),
        (get_distance_between_positions, ":dist", pos1, pos2),
        (le, ":dist", 3),
        (assign, ":travel_target", -1),
      (try_end),
      #end ozan
     
      (try_begin),
        (eq, ":travel_target", -1),
        (assign, ":action", spai_undefined),
      (else_try),
        (assign, ":action", spai_visiting_village),
      (try_end),
     
      (assign, ":object", ":travel_target"),
     
      (try_begin),
        (eq, ":troop_no", "$g_talk_troop"),
        (try_begin),
          (eq, ":travel_target", -1),
          (str_store_string, s14, "str_as_the_marshall_i_am_assembling_the_army_of_the_realm"),
        (else_try),
          (try_begin),
            (eq, ":faction_no", "$players_kingdom"),
            (eq, ":travel_target_new_assigned", 1),
            (le, "$number_of_report_to_army_quest_notes", 13),
            (check_quest_active, "qst_report_to_army"),            
            (str_store_party_name_link, s10, ":travel_target"),                        
            
            (faction_get_slot, ":faction_marshal", ":faction_no", slot_faction_marshall),
            
            (str_store_troop_name_link, s11, ":faction_marshal"),
            (store_current_hours, ":hours"),
            (call_script, "script_game_get_date_text", 0, ":hours"),

            (str_store_string, s14, "str_as_the_marshall_i_am_assembling_the_army_of_the_realm_and_travel_to_lands_near_s10_to_inform_more_vassals"),
            (str_store_string, s14, "@({s1}) {s11}: {s14}"),         
            (add_quest_note_from_sreg, "qst_report_to_army", "$number_of_report_to_army_quest_notes", s14, 0),
            (val_add, "$number_of_report_to_army_quest_notes", 1),
          (try_end),  

          (assign, reg0, ":travel_target"),
          (str_store_party_name, s10, ":travel_target"),
          (str_store_string, s14, "str_as_the_marshall_i_am_assembling_the_army_of_the_realm_and_travel_to_lands_near_s10_to_inform_more_vassals"),
        (try_end),
        (str_store_string, s16, "str_i_intend_to_assemble_the_army_of_the_realm"),
      (try_end),      		 
	(else_try),
	  (faction_slot_eq, ":faction_no", slot_faction_marshall, ":troop_no"),
	  (faction_slot_eq, ":faction_no", slot_faction_ai_state, sfai_attacking_center),
	  (faction_get_slot, ":faction_object", ":faction_no", slot_faction_ai_object),
	  
	  (assign, ":action", spai_besieging_center),
	  (assign, ":object", ":faction_object"),
	  (try_begin),
	    (eq, ":troop_no", "$g_talk_troop"),
	    (str_store_string, s14, "str_as_the_marshall_i_am_leading_the_siege"),
	    (str_store_string, s16, "str_i_intend_to_begin_the_siege"),
	  (try_end),
	
	(else_try),
	  (faction_slot_eq, ":faction_no", slot_faction_marshall, ":troop_no"),
	  (faction_slot_eq, ":faction_no", slot_faction_ai_state, sfai_raiding_village),
	  (faction_get_slot, ":faction_object", ":faction_no", slot_faction_ai_object),
	    
	  (assign, ":action", spai_raiding_around_center),
	  (assign, ":object", ":faction_object"),
	  (try_begin),
	    (eq, ":troop_no", "$g_talk_troop"),
	    (str_store_string, s14, "str_as_the_marshall_i_am_leading_our_raid"),
	    (str_store_string, s16, "str_i_intend_to_start_our_raid"),
	  (try_end),
	
	(else_try),
	  (faction_slot_eq, ":faction_no", slot_faction_marshall, ":troop_no"),
	  (faction_slot_eq, ":faction_no", slot_faction_ai_state, sfai_attacking_enemies_around_center),
	  (faction_get_slot, ":faction_object", ":faction_no", slot_faction_ai_object),
	  (party_is_active, ":faction_object"),
	  
	  #moved (party_set_ai_initiative, ":party_no", 10), #new to avoid losing time of marshal with attacking unimportant targets while there is a threat in our centers.
	  
	  (party_get_battle_opponent, ":besieger_party", ":faction_object"),
	  
	  (try_begin),
	    (gt, ":besieger_party", 0),
        (party_is_active, ":besieger_party"),
	    
	    (assign, ":action", spai_engaging_army),
	    (assign, ":object", ":besieger_party"),
	    (try_begin),
          (eq, ":troop_no", "$g_talk_troop"),
          (str_store_string, s14, "str_as_the_marshall_i_am_leading_our_forces_to_engage_the_enemy_in_battle"),
          (str_store_string, s16, "str_i_intend_to_lead_our_forces_out_to_engage_the_enemy"),
        (try_end),
      (else_try),      
        (assign, ":action", spai_patrolling_around_center),                
        (assign, ":object", ":faction_object"),
        (try_begin),
          (eq, ":troop_no", "$g_talk_troop"),
          (str_store_string, s14, "str_as_the_marshall_i_am_leading_our_forces_in_search_of_the_enemy"),
          (str_store_string, s16, "str_i_intend_to_lead_our_forces_out_to_find_the_enemy"),
        (try_end),
      (try_end), 
      
    (else_try),
      (faction_slot_eq, ":faction_no", slot_faction_marshall, ":troop_no"),
      (faction_slot_eq, ":faction_no", slot_faction_ai_state, sfai_attacking_enemy_army),
      (faction_get_slot, ":faction_object", ":faction_no", slot_faction_ai_object),
      (party_is_active, ":faction_object"),
      
      (assign, ":action", spai_engaging_army),
      (assign, ":object", ":faction_object"),
      (try_begin),
        (eq, ":troop_no", "$g_talk_troop"),
        (str_store_string, s14, "str_as_the_marshall_i_am_leading_our_forces_to_engage_the_enemy_in_battle"),
        (str_store_string, s16, "str_i_intend_to_lead_our_forces_out_to_engage_the_enemy"),
      (try_end),
		
	#Get reinforcements		
	(else_try),
	  (assign, ":lowest_acceptable_strength_percentage", 30),
	  
	  #if troop has enought gold then increase by 10%
	  #(troop_get_slot, ":cur_wealth", ":troop_no", slot_troop_wealth),            
	  #(try_begin),
	  #  (ge, ":cur_wealth", 2000),
	  #  (assign, ":wealth_addition", 10),
	  #(else_try),  
	  #  (store_div, ":wealth_addition", ":cur_wealth", 200),
	  #(try_end),
	  #(val_add, ":lowest_acceptable_strength_percentage", ":wealth_addition"),
	  
	  (call_script, "script_lord_get_home_center", ":troop_no"),
	  (assign, ":home_center", reg0),
	  (gt, ":home_center", -1),
	  (party_slot_eq, ":home_center", slot_town_lord, ":troop_no"), #newly added
	  
	  #if troop is very close to its home center increase by 20%
	  (assign, ":distance_addition", 0),
	  (party_get_position, pos0, ":home_center"),
	  (party_get_position, pos1, ":party_no"),
	  (get_distance_between_positions, ":dist", pos0, pos1),	  	  
	  	  
	  (try_begin),	  
	    (le, ":dist", 9000),
	    (store_div, ":distance_addition", ":dist", 600),
	    (store_sub, ":distance_addition", 15, ":distance_addition"),
	  (else_try),
	    (assign, ":distance_addition", 0),
	  (try_end),
	  (val_add, ":lowest_acceptable_strength_percentage", ":distance_addition"),
	  
	  #if there is no campaign for faction increase by 35%
	  (assign, ":no_campaign_addition", 35),
	  (try_begin),
	    (this_or_next|faction_slot_eq, ":faction_no", slot_faction_ai_state, sfai_attacking_enemy_army),
	    (this_or_next|faction_slot_eq, ":faction_no", slot_faction_ai_state, sfai_attacking_enemies_around_center),
	    (this_or_next|faction_slot_eq, ":faction_no", slot_faction_ai_state, sfai_raiding_village),
	    (this_or_next|faction_slot_eq, ":faction_no", slot_faction_ai_state, sfai_attacking_center),
	    (faction_slot_eq, ":faction_no", slot_faction_ai_state, sfai_gathering_army),
	    (assign, ":no_campaign_addition", 0),
	    
	    #If marshal is player itself and if there is a campaign then lower lowest_acceptable_strength_percentage by 10 instead of not changing it.
	    #Because players become confused when they see very less participation from AI lords to their campaigns.
	    (try_begin),	    
	      (faction_slot_eq, ":faction_no", slot_faction_marshall, "trp_player"),
	      (game_get_reduce_campaign_ai, ":reduce_campaign_ai"),
	      (try_begin),
	        (eq, ":reduce_campaign_ai", 0), #hard
	        (assign, ":no_campaign_addition", 0),
	      (else_try),  
	        (eq, ":reduce_campaign_ai", 1), #medium
	        (assign, ":no_campaign_addition", -10),
	      (else_try),  
	        (eq, ":reduce_campaign_ai", 2), #easy
	        (assign, ":no_campaign_addition", -15),
	      (try_end),  
	    (try_end),
	  (try_end),
	  (val_add, ":lowest_acceptable_strength_percentage", ":no_campaign_addition"),
	  (val_max, ":lowest_acceptable_strength_percentage", 25),
	
	  #max : 30%+15%+35% = 80% (happens when there is no campaign and player is near to its home center.)
	  (lt, ":party_strength_as_percentage_of_ideal", ":lowest_acceptable_strength_percentage"),
	  
	  (try_begin),
	    (store_div, ":lowest_acceptable_strength_percentage_div_3", ":lowest_acceptable_strength_percentage", 3),
	    (ge, ":party_strength_as_percentage_of_ideal", ":lowest_acceptable_strength_percentage_div_3"),
	    (troop_get_slot, ":troop_wealth", ":troop_no", slot_troop_wealth), 
	    (le, ":troop_wealth", 1800),
	    (assign, ":do_only_collecting_rents", 1),
	  (try_end),
	  	  	  
	  (assign, ":action", spai_holding_center),
	  (assign, ":object", ":home_center"),
	  
	  (try_begin),
	    (eq, ":troop_no", "$g_talk_troop"),
	    (str_store_string, s14, "str_i_dont_have_enough_troops_and_i_need_to_get_some_more"),
	    	    
	    (str_store_string, s16, "str_i_am_running_low_on_troops"),
	  (try_end),
	  
	  (eq, ":do_only_collecting_rents", 0),
		
	#follow player orders
	(else_try),
	  (eq, ":do_only_collecting_rents", 0),
	  (party_slot_ge, ":party_no", slot_party_following_orders_of_troop, "trp_kingdom_heroes_including_player_begin"),
	  
	  (party_get_slot, ":orders_type", ":party_no", slot_party_orders_type),
	  (party_get_slot, ":orders_object", ":party_no", slot_party_orders_object),
	  (party_get_slot, ":orders_time", ":party_no", slot_party_orders_time),
	  
	  (ge, ":orders_object", 0),
	  
	  (store_current_hours, ":hours_since_orders_given"),
	  (val_sub, ":hours_since_orders_given", ":orders_time"),
	  
	  (party_is_active, ":orders_object"),
	  (party_get_slot, ":object_state", ":orders_object", slot_village_state),
	  (store_faction_of_party, ":object_faction", ":orders_object"),	  
	  (store_relation, ":relation_with_object", ":faction_no", ":object_faction"),
	  
	  (assign, ":orders_are_appropriate", 1),
	  (try_begin),
	    (gt, ":hours_since_orders_given", 48),
	    (assign, ":orders_are_appropriate", 0),
	  (else_try),
	    (eq, ":orders_type", spai_raiding_around_center),
	    (this_or_next|ge, ":relation_with_object", 0),
	    (ge, ":object_state", 2),
	    (assign, ":orders_are_appropriate", 0),
	  (else_try),
	    (eq, ":orders_type", spai_besieging_center),
	    (ge, ":relation_with_object", 0),
	    (assign, ":orders_are_appropriate", 0),
	  (else_try),
	    (this_or_next|eq, ":orders_type", spai_holding_center),
	    (this_or_next|eq, ":orders_type", spai_retreating_to_center),
	    (this_or_next|eq, ":orders_type", spai_accompanying_army),
	    (eq, ":orders_type", spai_visiting_village),
	    (le, ":relation_with_object", 0),
	    (assign, ":orders_are_appropriate", 0),
	  (try_end),
	  
	  (eq, ":orders_are_appropriate", 1),
	  
	  (assign, ":action", ":orders_type"),
	  (assign, ":object", ":orders_object"),
	  (try_begin),
	    (eq, ":troop_no", "$g_talk_troop"),
	    (str_store_string, s14, "str_we_are_following_your_direction"),
	  (try_end),
		
	#Host of player wedding
	(else_try),
	  (eq, ":do_only_collecting_rents", 0),
	  (eq, ":operation_in_progress", 0),
	  (check_quest_active, "qst_wed_betrothed"),
	  (quest_slot_eq, "qst_wed_betrothed", slot_quest_giver_troop, ":troop_no"),
	  (quest_get_slot, ":bride", "qst_wed_betrothed", slot_quest_target_troop),
	  (call_script, "script_get_kingdom_lady_social_determinants", ":bride"),
	  (assign, ":wedding_venue", reg1),
	  
	  (assign, ":action", spai_holding_center),
	  (assign, ":object", ":wedding_venue"),
	  
	  (try_begin),
	    (eq, ":troop_no", "$g_talk_troop"),
	    (str_store_string, s14, "str_i_need_to_make_preparations_for_your_wedding"),
	    (str_store_string, s16, "str_after_all_i_need_to_make_preparations_for_your_wedding"),
	  (try_end),
	
	#Bridegroom at player wedding
	(else_try),
	  (eq, ":do_only_collecting_rents", 0),
	  (eq, ":operation_in_progress", 0),
	  (check_quest_active, "qst_wed_betrothed_female"),
	  (quest_slot_eq, "qst_wed_betrothed_female", slot_quest_giver_troop, ":troop_no"),
	  
	  (faction_slot_eq, ":faction_no", slot_faction_ai_state, sfai_feast),
	  (faction_get_slot, ":feast_venue", ":faction_no", slot_faction_ai_object),
	  
	  (assign, ":action", spai_holding_center),
	  (assign, ":object", ":feast_venue"),
	  
	  (try_begin),
	    (eq, ":troop_no", "$g_talk_troop"),
	    (str_store_string, s14, "str_i_am_heading_to_the_site_of_our_wedding"),
	    (str_store_string, s16, "str_after_all_we_are_soon_to_be_wed"),
	  (try_end),
 	
	#Host of other feast
	(else_try),
	  (eq, ":do_only_collecting_rents", 0),
	  (eq, ":operation_in_progress", 0),
	  (faction_slot_eq, ":faction_no", slot_faction_ai_state, sfai_feast),
	  (faction_get_slot, ":feast_venue", ":faction_no", slot_faction_ai_object),
	  (party_slot_eq, ":feast_venue", slot_town_lord, ":troop_no"),
	  
	  (assign, ":action", spai_holding_center),
	  (assign, ":object", ":feast_venue"),
	  
	  (try_begin),
	    (eq, ":troop_no", "$g_talk_troop"),
	    (str_store_string, s14, "str_i_am_hosting_a_feast_there"),
	    (str_store_string, s16, "str_i_have_a_feast_to_host"),
	  (try_end),
		
	#I am the bridegroom at a feast
	(else_try),
	  (eq, ":do_only_collecting_rents", 0),
	  (eq, ":operation_in_progress", 0),
	  (faction_slot_eq, ":faction_no", slot_faction_ai_state, sfai_feast),
	  (troop_get_slot, ":troop_betrothed", ":troop_no", slot_troop_betrothed),
	  (is_between, ":troop_betrothed", kingdom_ladies_begin, kingdom_ladies_end),
	  
	  (faction_get_slot, ":feast_venue", ":faction_no", slot_faction_ai_object),
	  
	  (assign, ":action", spai_holding_center),
	  (assign, ":object", ":feast_venue"),
	  
	  (try_begin),
	    (eq, ":troop_no", "$g_talk_troop"),
	    (str_store_string, s14, "str_i_am_to_be_the_bridegroom_there"),
	    (str_store_string, s16, "str_my_wedding_day_draws_near"),
	  (try_end),
	  
	#Drop off prisoners
	(else_try),
	  (eq, ":do_only_collecting_rents", 0),
	  (gt,  ":party_ratio_of_prisoners", 35),
	  (eq, ":operation_in_progress", 0),
	  
	  (call_script, "script_lord_get_home_center", ":troop_no"),
	  (assign, ":home_center", reg0),
	  
	  (gt, ":home_center", -1),
	  
	  (assign, ":action", spai_holding_center),
	  (assign, ":object", ":home_center"),
	  
	  (try_begin),
	    (eq, ":troop_no", "$g_talk_troop"),
	    (str_store_string, s14, "str_i_have_too_much_loot_and_too_many_prisoners_and_need_to_secure_them"),
	    (str_store_string, s16, "str_i_should_think_of_dropping_off_some_of_my_prisoners"),
	  (try_end),
	
	#Reinforce a weak center		
	(else_try),
	  (eq, ":do_only_collecting_rents", 0),
	  (assign, ":center_to_reinforce", -1),
	  (assign, ":center_reinforce_score", 100),
	  (eq, ":operation_in_progress", 0),
	  
	  (try_for_range, ":walled_center", walled_centers_begin, walled_centers_end),
	    (party_slot_eq, ":walled_center", slot_town_lord, ":troop_no"),
	    (party_get_slot, ":center_strength", ":walled_center", slot_party_cached_strength),
	    (lt, ":center_strength", ":center_reinforce_score"),
	    (assign, ":center_to_reinforce", ":walled_center"),
	    (assign, ":center_reinforce_score", ":center_strength"),
	  (try_end),
	  
	  (gt, ":center_to_reinforce", -1),
	  
	  (assign, ":action", spai_holding_center),
	  (assign, ":object", ":center_to_reinforce"),
	  (try_begin),
	    (eq, ":troop_no", "$g_talk_troop"),
	    (str_store_string, s14, "str_i_need_to_reinforce_it_as_it_is_poorly_garrisoned"),
	    (str_store_string, s16, "str_there_is_a_hole_in_our_defenses"),
	  (try_end),

	#Continue screening, if already doing so
	(else_try),	
	  (eq, ":do_only_collecting_rents", 0),
	  (eq, ":old_ai_state", spai_screening_army),
	  
	  (faction_get_slot, ":faction_marshal", ":faction_no", slot_faction_marshall),
           (ge, ":faction_marshal", 0),
	  (troop_get_slot, ":marshal_party", ":faction_marshal", slot_troop_leaded_party),
	  (party_is_active, ":marshal_party"),
	  
	  (call_script, "script_npc_decision_checklist_troop_follow_or_not", ":troop_no"),
	  (eq, reg0, 1),
	  
	  (assign, ":action", spai_screening_army),
	  (assign, ":object", ":marshal_party"),
	  (try_begin),
	    (eq, "$g_talk_troop", ":troop_no"),
	    (str_store_string, s14, "str_i_am_following_the_marshals_orders"),
	    (str_store_string, s16, "str_the_marshal_has_given_me_this_command"),
	  (try_end),
		
    (else_try), #special case for sfai_attacking_enemies_around_center for village raids
      (faction_slot_eq, ":faction_no", slot_faction_ai_state, sfai_attacking_enemies_around_center),
      (is_between, ":faction_object", villages_begin, villages_end),
      
      (call_script, "script_npc_decision_checklist_troop_follow_or_not", ":troop_no"),
      (eq, reg0, 1),
      
      (faction_get_slot, ":faction_object", ":faction_no", slot_faction_ai_object),
      (party_get_slot, ":raider_party", ":faction_object", slot_village_raided_by),
      (party_is_active, ":raider_party"),
      
      #think about adding one more condition here, what if raider army is so powerfull, again lords will go and engage enemy one by one?
      (party_get_slot, ":enemy_strength_nearby", ":faction_object", slot_center_sortie_enemy_strength),
      (lt, ":enemy_strength_nearby", 4000),
      #end think
      
      (assign, ":action", spai_engaging_army),
      (assign, ":object", ":raider_party"),
      (try_begin),
        (eq, ":troop_no", "$g_talk_troop"),
        (str_store_string, s14, "str_our_realm_needs_my_support_there_is_enemy_raiding_one_of_our_villages_which_is_not_to_far_from_here_i_am_going_there"),
        (str_store_string, s16, "str_the_marshal_has_issued_a_summons"),
      (try_end),
      						
	#Follow the marshall's orders - if on the offensive, and the campaign has not lasted too long. Readiness is currently randomly set
	(else_try),	
	  (eq, ":do_only_collecting_rents", 0),
	  (call_script, "script_npc_decision_checklist_troop_follow_or_not", ":troop_no"),
	  (eq, reg0, 1),
	  
	  (faction_get_slot, ":faction_marshal", ":faction_no", slot_faction_marshall),
           (ge, ":faction_marshal", 0),
	  (troop_get_slot, ":marshal_party", ":faction_marshal", slot_troop_leaded_party),
	  	  
	  (assign, ":action", spai_accompanying_army),
	  (assign, ":object", ":marshal_party"),
	  	  	  
	  (try_begin),
	    (eq, "$g_talk_troop", ":troop_no"),
	    (str_store_string, s14, "str_i_am_answering_the_marshals_summons"),
	    (str_store_string, s16, "str_the_marshal_has_issued_a_summons"),
	  (try_end),
	  
	#Support a nearby ally who is on the offensive		
	(else_try),	
	  (eq, ":do_only_collecting_rents", 0),
	  (eq, ":faction_is_at_war", 1),
	  
	  (assign, ":party_to_support", -1),
	  (try_for_range, ":allied_hero", active_npcs_begin, active_npcs_end),
	    (troop_slot_eq, ":allied_hero", slot_troop_occupation, slto_kingdom_hero),
	    (store_faction_of_troop, ":allied_hero_faction", ":allied_hero"),
	    (eq, ":allied_hero_faction", ":faction_no"),
	  
	    (neq, ":allied_hero", ":troop_no"),
	  
	    (troop_get_slot, ":allied_hero_party", ":allied_hero", slot_troop_leaded_party),
	    (gt, ":allied_hero_party", 1),
	    (party_is_active, ":allied_hero_party"),
		
	  
	    (this_or_next|party_slot_eq, ":allied_hero_party", slot_party_ai_state, spai_raiding_around_center),
			(party_slot_eq, ":allied_hero_party", slot_party_ai_state, spai_besieging_center),
	  
	    (call_script, "script_troop_get_relation_with_troop", ":troop_no", ":allied_hero"),
	    (gt, reg0, 4),
	  
	    (troop_get_slot, ":troop_renown", ":troop_no", slot_troop_renown),		
	    (troop_get_slot, ":ally_renown", ":allied_hero", slot_troop_renown),		
	    (le, ":troop_renown", ":ally_renown"), #Ally to support must have higher renown
	  
	    (store_distance_to_party_from_party, ":distance", ":party_no", ":allied_hero_party"),
	  
	    (lt, ":distance", 5),
	  
 	    (assign, ":party_to_support", ":allied_hero_party"),
	  (try_end),
	  (gt, ":party_to_support", 0),
	  	  
	  (assign, ":action", spai_accompanying_army),
	  (assign, ":object", ":party_to_support"),
	  (try_begin),
		  (eq, ":troop_no", "$g_talk_troop"),
		  (party_stack_get_troop_id, ":leader", ":object", 0),
		  (str_store_troop_name, s10, ":leader"),
		  
		  (call_script, "script_troop_get_family_relation_to_troop", ":leader", "$g_talk_troop"),
		  (try_begin),
		    (eq, reg0, 0),
		    (str_store_string, s11, "str_comradeinarms"),
		  (try_end),
		  (str_store_string, s14, "str_i_am_supporting_my_s11_s10"),
		  (str_store_string, s16, "str_i_believe_that_one_of_my_comrades_is_in_need"),
	  (try_end),
    #I have decided to attack a vulnerable fortress
	(else_try),	
	  (eq, ":do_only_collecting_rents", 0),
	  (eq, ":faction_is_at_war", 1),
	  (eq, ":operation_in_progress", 0),
	  
	  (assign, ":walled_center_to_attack", -1),
	  (assign, ":walled_center_score", 50),
	  
	  (try_for_range, ":walled_center", walled_centers_begin, walled_centers_end),
	    (store_faction_of_party, ":walled_center_faction", ":walled_center"),
	    (store_relation, ":relation", ":faction_no", ":walled_center_faction"),
	    (lt, ":relation", 0),
	    
	    (party_get_slot, ":center_cached_strength", ":walled_center", slot_party_cached_strength),
	    (val_mul, ":center_cached_strength", 3),
	    (val_mul, ":center_cached_strength", 2),
	    
	    (lt, ":center_cached_strength", ":party_cached_strength"), 
	    (lt, ":center_cached_strength", 750),
	    
	    (party_slot_eq, ":walled_center", slot_village_state, svs_normal),
	    (store_distance_to_party_from_party, ":distance", ":walled_center", ":party_no"),
	    (lt, ":distance", ":walled_center_score"),
	    
	    (assign, ":walled_center_to_attack", ":walled_center"),
	    (assign, ":walled_center_score", ":distance"),
	  (try_end),
	  
	  (is_between, ":walled_center_to_attack", centers_begin, centers_end),
	  
	  (assign, ":action", spai_besieging_center),
	  (assign, ":object", ":walled_center_to_attack"),
	  (try_begin),
	    (eq, "$cheat_mode", 1),
	    (str_store_faction_name, s20, ":faction_no"),
	    (str_store_party_name, s21, ":object"),
	    (display_message, "str_s20_decided_to_attack_s21"),
	  (try_end),
	  
	  (try_begin),
	    (eq, ":troop_no", "$g_talk_troop"),
	    (str_store_string, s14, "str_a_fortress_is_vulnerable"),
	    (str_store_string, s16, "str_i_believe_that_the_enemy_may_be_vulnerable"),
	  (try_end),
	  
	#I am visiting an estate
	(else_try),
	  (assign, ":center_to_visit", -1),
	  (assign, ":score_to_beat", 300), #at least 300 gold to pick up
	  (troop_get_slot, ":troop_wealth", ":troop_no", slot_troop_wealth), #average troop wealth is 2000
	  (val_div, ":troop_wealth", 10), #average troop wealth 10% is is 200
	  (val_add, ":score_to_beat", ":troop_wealth"), #average score to beat is 500
	  (eq, ":operation_in_progress", 0),	  	  
	  	  
	  (try_begin),	    
	    (faction_get_slot, ":faction_marshal", ":faction_no", slot_faction_marshall),
	    
	    (assign, reg17, 0),
	    (try_begin),
	      (party_slot_eq, ":party_no", slot_party_ai_state, spai_accompanying_army),
	      (party_slot_eq, ":party_no", slot_party_ai_object, ":faction_marshal"),	    
	      (assign, reg17, 1),
	    (else_try),  	    
	      (party_slot_eq, ":party_no", slot_party_following_player, 1),
	      (assign, reg17, 1),
	    (try_end),  
	    (eq, reg17, 1),
	    
	    (try_begin),
	      (neq, ":faction_marshal", "trp_player"),
	      (neg|party_slot_eq, ":party_no", slot_party_following_player, 1),
	      (val_add, ":score_to_beat", 125),
	    (else_try),
	      (val_add, ":score_to_beat", 250),
	    (try_end),
	  (try_end),  
	  
	  (try_for_range, ":center_no", centers_begin, centers_end),
	    (party_slot_eq, ":center_no", slot_town_lord, ":troop_no"),
	    
	    (assign, reg17, 0),
	    (try_begin),
	      (is_between, ":center_no", villages_begin, villages_end),
	      (party_slot_eq, ":center_no", slot_village_state, svs_normal),
	      (assign, reg17, 1),
	    (else_try),  	    
	      (party_slot_eq, ":center_no", slot_center_is_besieged_by, -1),
	      (assign, reg17, 1),
	    (try_end),	    
	    (eq, reg17, 1),
	    
	    (party_get_slot, ":tariffs_available", ":center_no", slot_center_accumulated_tariffs),
	    (party_get_slot, ":rents_available", ":center_no", slot_center_accumulated_rents),
	    (store_add, ":money_available", ":rents_available", ":tariffs_available"),
	    	    
	    (gt, ":money_available", ":score_to_beat"),
	    (assign, ":center_to_visit", ":center_no"),
	    (assign, ":score_to_beat", ":money_available"),			
	  (try_end),
	  
	  (is_between, ":center_to_visit", centers_begin, centers_end),
	  	  
	  (try_begin),
	    (is_between, ":center_to_visit", walled_centers_begin, walled_centers_end),
	    (assign, ":action", spai_holding_center),
	    (assign, ":object", ":center_to_visit"),
	  (else_try),  
        (assign, ":action", spai_visiting_village),
  	    (assign, ":object", ":center_to_visit"),
	  (try_end),
	  
	  (try_begin),
	    (eq, ":troop_no", "$g_talk_troop"),
	    (str_store_string, s14, "str_i_need_to_inspect_my_properties_and_collect_my_dues"),
	    (str_store_string, s16, "str_it_has_been_too_long_since_i_have_inspected_my_estates"),
	  (try_end),
	  
	#My men are weary, and I wish to return home
	(else_try),
	  (eq, ":do_only_collecting_rents", 0),
	  (this_or_next|gt, ":hours_since_last_rest", 504), #Three weeks
	  (lt, ":aggressiveness", 25),	  
	  (gt, ":hours_since_last_rest", 168), #one week if aggressiveness < 25	
	  (eq, ":operation_in_progress", 0),
	  
	  (call_script, "script_lord_get_home_center", ":troop_no"),
	  (assign, ":home_center", reg0),
	  
	  (gt, ":home_center", -1),
	  (assign, ":action", spai_holding_center),
	  (assign, ":object", ":home_center"),
	  
	  (try_begin),
	    (eq, ":troop_no", "$g_talk_troop"),
	    (str_store_string, s14, "str_my_men_are_weary_so_we_are_returning_home"),
	    (str_store_string, s16, "str_my_men_are_becoming_weary"),
	  (try_end),
	
	#I have a score to settle with the enemy
	(else_try),
	  (eq, ":do_only_collecting_rents", 0),
	  (this_or_next|gt, ":hours_since_last_combat", 12),
	  (lt, ":hours_since_last_rest", 96),
	  (eq, ":operation_in_progress", 0),
	  
	  (eq, ":faction_is_at_war", 1),
	  (this_or_next|eq, ":troop_reputation", lrep_debauched),
	  (eq, ":troop_reputation", lrep_quarrelsome),
	  
	  (assign, ":target_village", -1),
	  (assign, ":score_to_beat", 0), #based on relation
	  
	  (try_for_range, ":possible_target", villages_begin, villages_end),
	    (store_faction_of_party, ":village_faction", ":possible_target"),
	    (store_relation, ":relation", ":village_faction", ":faction_no"),
	    (lt, ":relation", 0),
	    
	    (neg|party_slot_ge, ":possible_target", slot_village_state, svs_looted),
	    (party_get_slot, ":town_lord", ":possible_target", slot_town_lord),
	    (call_script, "script_troop_get_relation_with_troop", ":troop_no", ":town_lord"),
	    (assign, ":village_score", reg0),
	    
	    (lt, ":village_score", ":score_to_beat"),
	    (assign, ":score_to_beat", ":village_score"),
	    (assign, ":target_village", ":possible_target"),
	  (try_end),
	  
	  (is_between, ":target_village", centers_begin, centers_end),
	  (assign, ":action", spai_raiding_around_center),
	  (assign, ":object", ":target_village"),
	  
	  (try_begin),
	    (eq, ":troop_no", "$g_talk_troop"),
	    (str_store_string, s14, "str_i_have_a_score_to_settle_with_the_lord_there"),
	    (str_store_string, s16, "str_i_am_thinking_of_settling_an_old_score"),
	  (try_end),
	
	#I need money, so I am raiding where the money is
	(else_try),
	  (eq, ":do_only_collecting_rents", 0),
	  (eq, ":faction_is_at_war", 1),
	  (eq, ":operation_in_progress", 0),
	  
	  (this_or_next|gt, ":hours_since_last_combat", 12),
	  (lt, ":hours_since_last_rest", 96),
	  (gt, ":aggressiveness", 40),
	  
	  (this_or_next|eq, ":troop_reputation", lrep_debauched),
	  (this_or_next|eq, ":troop_reputation", lrep_selfrighteous),
	  (this_or_next|eq, ":troop_reputation", lrep_cunning),
	  (eq, ":troop_reputation", lrep_quarrelsome),
	  
	  (troop_get_slot, ":wealth", ":troop_no", slot_troop_wealth),	
	  (lt, ":wealth", 500),
	  
	  (assign, ":score_to_beat", 0),
	  (assign, ":target_village", -1),
	  
	  (try_for_range, ":possible_target", villages_begin, villages_end),
	    (store_faction_of_party, ":village_faction", ":possible_target"),
	    (store_relation, ":relation", ":village_faction", ":faction_no"),
	    (lt, ":relation", 0),
	    
	    (this_or_next|party_slot_eq, ":possible_target", slot_village_state, svs_normal),
	    (party_slot_eq, ":possible_target", slot_village_state, svs_being_raided),
	    
	    (party_get_slot, reg17, ":possible_target", slot_town_prosperity),
	    (store_distance_to_party_from_party, ":distance", ":party_no", ":possible_target"),
	    (val_sub, reg17, ":distance"),
	    
	    (gt, reg17, ":score_to_beat"),
	    (assign, ":score_to_beat", reg17),
	    (assign, ":target_village", ":possible_target"),
	  (try_end),
	  
	  (gt, ":target_village", -1),
	  
	  (assign, ":action", spai_raiding_around_center),
	  (assign, ":object", ":target_village"),
	  
	  (try_begin),
	    (eq, ":troop_no", "$g_talk_troop"),
	    (str_store_string, s14, "str_i_am_short_of_money_and_i_hear_that_there_is_much_wealth_there"),
	    (str_store_string, s16, "str_i_need_to_refill_my_purse_preferably_with_the_enemys_money"),
	  (try_end),
	
	#Attacking wealthiest lands
	(else_try),
	  (eq, ":do_only_collecting_rents", 0),
		(eq, ":faction_is_at_war", 1),
		(eq, ":operation_in_progress", 0),
		(gt, ":aggressiveness", 65),
	
		(assign, ":score_to_beat", 0),
		(assign, ":target_village", -1),
		
		(try_for_range, ":possible_target", villages_begin, villages_end),
			(store_faction_of_party, ":village_faction", ":possible_target"),
			(store_relation, ":relation", ":village_faction", ":faction_no"),
			(lt, ":relation", 0),			
			(neg|party_slot_eq, ":possible_target", slot_village_state, svs_looted),			
			(party_get_slot, ":village_prosperity", ":possible_target", slot_town_prosperity),
			(val_mul, ":village_prosperity", 2),

			(store_distance_to_party_from_party, ":distance", ":party_no", ":possible_target"),
			(val_sub, ":village_prosperity", ":distance"),			
			(gt, ":village_prosperity", ":score_to_beat"),
			
			(assign, ":score_to_beat", ":village_prosperity"),
			(assign, ":target_village", ":possible_target"),
		(try_end),

		(gt, ":target_village", -1),

		(assign, ":action", spai_raiding_around_center),
		(assign, ":object", ":target_village"),

		(try_begin),
			(eq, ":troop_no", "$g_talk_troop"),
			(str_store_string, s14, "str_by_striking_at_the_enemys_richest_lands_perhaps_i_can_draw_them_out_to_battle"),
			(str_store_string, s16, "str_i_am_thinking_of_going_on_the_attack"),
		(try_end),

	#End the war
	(else_try),
	  (eq, ":do_only_collecting_rents", 0),
		(eq, ":troop_reputation", lrep_upstanding),
		(eq, ":faction_is_at_war", 1),
		(eq, ":operation_in_progress", 0),
		
		(assign, ":faction_to_attack", -1),
		(try_for_range, ":possible_faction_to_attack", kingdoms_begin, kingdoms_end),
			(store_relation, ":relation", ":faction_no", ":possible_faction_to_attack"),
			(lt, ":relation", 0),
			(faction_slot_eq, ":possible_faction_to_attack", slot_faction_state, sfs_active),
			
			(store_add, ":war_damage_inflicted_slot", ":possible_faction_to_attack", slot_faction_war_damage_inflicted_on_factions_begin),
			(val_sub, ":war_damage_inflicted_slot", kingdoms_begin),
			(faction_get_slot, ":war_damage_inflicted", ":faction_no", ":war_damage_inflicted_slot"),

			(store_add, ":war_damage_suffered_slot", ":faction_no", slot_faction_war_damage_inflicted_on_factions_begin),
			(val_sub, ":war_damage_suffered_slot", kingdoms_begin),
			(faction_get_slot, ":war_damage_suffered", ":possible_faction_to_attack", ":war_damage_suffered_slot"),
			
			(gt, ":war_damage_inflicted", 80),
			(lt, ":war_damage_inflicted", ":war_damage_suffered"),
			(assign, ":faction_to_attack", ":possible_faction_to_attack"),
		(try_end),
		
		(gt, ":faction_to_attack", -1),

		(assign, ":target_village", -1),
		(assign, ":score_to_beat", 50),
		
		(try_for_range, ":possible_target_village", villages_begin, villages_end),
			(store_faction_of_party, ":village_faction", ":possible_target_village"),		
			(eq, ":village_faction", ":faction_to_attack"),			
			(neg|party_slot_eq, ":possible_target_village", slot_village_state, svs_looted),			
			(store_distance_to_party_from_party, ":distance", ":party_no", ":possible_target_village"),			
			(lt, ":distance", ":score_to_beat"),
			
			(assign, ":score_to_beat", ":distance"),
			(assign, ":target_village", ":possible_target_village"),
		(try_end),
		
		(gt, ":target_village", -1),

		(assign, ":action", spai_raiding_around_center),
		(assign, ":object", ":target_village"),

		(try_begin),
			(eq, ":troop_no", "$g_talk_troop"),
			(str_store_string, s14, "str_perhaps_if_i_strike_one_more_blow_we_may_end_this_war_on_our_terms_"),
			(str_store_string, s16, "str_we_may_be_able_to_bring_this_war_to_a_close_with_a_few_more_blows"),
		(try_end),
	
	#I have a feast to attend
	(else_try),
	  (eq, ":do_only_collecting_rents", 0),
		(faction_slot_eq, ":faction_no", slot_faction_ai_state, sfai_feast),
		(faction_get_slot, ":feast_venue", ":faction_no", slot_faction_ai_object),
		(party_get_slot, ":feast_host", ":feast_venue", slot_town_lord), 
		(eq, ":operation_in_progress", 0),
			
		(call_script, "script_troop_get_relation_with_troop", ":troop_no", ":feast_host"),
		(assign, ":relation_with_host", reg0),
			
        (ge, ":relation_with_host", 0),
		
		(assign, ":action", spai_holding_center),
		(assign, ":object", ":feast_venue"),

		(try_begin),
			(eq, ":troop_no", "$g_talk_troop"),
			(str_store_string, s14, "str_i_wish_to_attend_the_feast_there"),
			(str_store_string, s16, "str_there_is_a_feast_which_i_wish_to_attend"),
		(try_end),		
	#A lady to court
	(else_try),
	  (eq, ":do_only_collecting_rents", 0),
		(neg|troop_slot_eq, "trp_player", slot_troop_betrothed, ":troop_no"),
		(troop_slot_eq, ":troop_no", slot_troop_spouse, -1),
		(neg|is_between, ":troop_no", kings_begin, kings_end),
		(neg|is_between, ":troop_no", pretenders_begin, pretenders_end),

		
		(gt, ":hours_since_last_courtship", 72),
		(eq, ":operation_in_progress", 0),
		
		(assign, ":center_to_visit", -1),
		(assign, ":score_to_beat", 150),
		
		(try_for_range, ":love_interest_slot", slot_troop_love_interest_1, slot_troop_love_interests_end),
			(troop_get_slot, ":love_interest", ":troop_no", ":love_interest_slot"),
			(is_between, ":love_interest", kingdom_ladies_begin, kingdom_ladies_end),	
			(troop_get_slot, ":love_interest_center", ":love_interest", slot_troop_cur_center),
			(is_between, ":love_interest_center", centers_begin, centers_end),
			(store_faction_of_party, ":love_interest_faction_no", ":love_interest_center"),
			(eq, ":faction_no", ":love_interest_faction_no"),
            #(store_relation, ":relation", ":faction_no", ":love_interest_faction_no"),
            #(ge, ":relation", 0),
			
			(store_distance_to_party_from_party, ":distance", ":party_no", ":love_interest_center"),
			
			(lt, ":distance", ":score_to_beat"),
			(assign, ":center_to_visit", ":love_interest_center"),
			(assign, ":score_to_beat", ":distance"),			
        (try_end),
 
		(gt, ":center_to_visit", -1),
			
		(assign, ":action", spai_holding_center),
		(assign, ":object", ":center_to_visit"),

		(try_begin),
			(eq, ":troop_no", "$g_talk_troop"),
			(str_store_string, s14, "str_there_is_a_fair_lady_there_whom_i_wish_to_court"),
			(str_store_string, s16, "str_i_have_the_inclination_to_pay_court_to_a_fair_lady"),
		(try_end),
				
	#Patrolling an alarmed center
	(else_try),
	  (eq, ":do_only_collecting_rents", 0),
		(assign, ":target_center", -1),
		(assign, ":score_to_beat", 60),
		(eq, ":operation_in_progress", 0),
		(gt, ":aggressiveness", 40),

		(try_for_range, ":center_to_patrol", centers_begin, centers_end), #find closest center that has spotted enemies.
            (store_faction_of_party, ":center_faction", ":center_to_patrol"),
            (eq, ":center_faction", ":faction_no"),
			(party_slot_ge, ":center_to_patrol", slot_center_last_spotted_enemy, 0),
			
			#new - begin
			(party_get_slot, ":sortie_strength", ":center_to_patrol", slot_center_sortie_strength),
			(party_get_slot, ":enemy_strength", ":center_to_patrol", slot_center_sortie_enemy_strength),
			(store_mul, ":enemy_strength_mul_14_div_10", ":enemy_strength", 14),
			(val_div, ":enemy_strength_mul_14_div_10", 10),
			(party_get_slot, ":party_strength", ":party_no", slot_party_cached_strength),
			
			(this_or_next|neg|party_is_in_town, ":party_no", ":center_to_patrol"),			
			(gt, ":sortie_strength", ":enemy_strength_mul_14_div_10"),
			
			(ge, ":party_strength", 100),
			#new - end
									
			(party_get_slot, reg17, ":center_to_patrol", slot_town_lord),						
			(call_script, "script_troop_get_relation_with_troop", reg17, ":troop_no"),
			
			(this_or_next|eq, ":troop_reputation", lrep_upstanding),
				(gt, reg0, -5),
			
            (store_distance_to_party_from_party, ":distance", ":party_no", ":center_to_patrol"),
			(lt, ":distance", ":score_to_beat"),
			
			(assign, ":target_center", ":center_to_patrol"),
			(assign, ":score_to_beat", ":distance"),
		(try_end),

		(is_between, ":target_center", centers_begin, centers_end),
		
		(assign, ":action", spai_patrolling_around_center),
		(assign, ":object", ":target_center"),
				
		(try_begin),
			(eq, ":troop_no", "$g_talk_troop"),
			(str_store_string, s14, "str_we_have_heard_reports_that_the_enemy_is_in_the_area"),
			(str_store_string, s16, "str_i_have_heard_reports_of_enemy_incursions_into_our_territory"),
		(try_end),
	
	#Time in household
	(else_try),
	  (eq, ":do_only_collecting_rents", 0),
		(gt, ":hours_since_last_home", 168),
		(eq, ":operation_in_progress", 0),

		(call_script, "script_lord_get_home_center", ":troop_no"),
		(assign, ":home_center", reg0),
		(gt, ":home_center", -1),
		
		(assign, ":action", spai_holding_center),
		(assign, ":object", ":home_center"),
		
		(try_begin),
			(eq, ":troop_no", "$g_talk_troop"),
			(str_store_string, s14, "str_i_need_to_spend_some_time_with_my_household"),
			(str_store_string, s16, "str_it_has_been_a_long_time_since_i_have_been_able_to_spend_time_with_my_household"),
		(try_end),

	#Patrolling the borders
	(else_try),
	  (eq, ":do_only_collecting_rents", 0),
		(eq, ":faction_is_at_war", 1),
		(gt, ":aggressiveness", 65),
		(eq, ":operation_in_progress", 0),
		
		(assign, ":center_to_patrol", -1),
		(assign, ":score_to_beat", 75),
		
		(try_for_range, ":village", villages_begin, villages_end),
			(store_faction_of_party, ":village_faction", ":village"),
			(store_relation, ":relation", ":village_faction", ":faction_no"),
			(lt, ":relation", 0),
			
			(store_distance_to_party_from_party, ":distance", ":village", ":party_no"),
			(lt, ":distance", ":score_to_beat"),
			
			(assign, ":score_to_beat", ":distance"),
			(assign, ":center_to_patrol", ":village"),
		(try_end),
		
		(is_between, ":center_to_patrol", villages_begin, villages_end),
				
		(assign, ":action", spai_patrolling_around_center),
		(assign, ":object", ":center_to_patrol"),
		
		(try_begin),
			(eq, ":troop_no", "$g_talk_troop"),
			(str_store_string, s14, "str_i_am_watching_the_borders"),
			(str_store_string, s16, "str_i_may_be_needed_to_watch_the_borders"),
		(try_end),

	#Visiting a friend - temporarily disabled
	(else_try),
		(eq, 1, 0),
		
	#Patrolling home
	(else_try),
	  (eq, ":do_only_collecting_rents", 0),
		(call_script, "script_lord_get_home_center", ":troop_no"),
		(assign, ":home_center", reg0),
		
		(is_between, ":home_center", centers_begin, centers_end),
		(eq, ":operation_in_progress", 0),
		
		(assign, ":action", spai_patrolling_around_center),
		(assign, ":object", ":home_center"),
		
		(try_begin),
			(eq, ":troop_no", "$g_talk_troop"),
			(str_store_string, s14, "str_i_will_guard_the_areas_near_my_home"),
			(str_store_string, s16, "str_i_am_perhaps_needed_most_at_home"),
		(try_end),
	
	#Default end
	(else_try),
	  (eq, ":do_only_collecting_rents", 0),
		(eq, ":operation_in_progress", 0),

		(call_script, "script_lord_get_home_center", ":troop_no"),
		(assign, ":home_center", reg0),
		(is_between, ":home_center", walled_centers_begin, walled_centers_end),
		
		(assign, ":action", spai_holding_center),
		(assign, ":object", ":home_center"),
		
		(try_begin),
			(eq, ":troop_no", "$g_talk_troop"),
			(str_store_string, s14, "str_i_cant_think_of_anything_better_to_do"),
		(try_end),
	(else_try),	
	  (eq, ":do_only_collecting_rents", 0),
		(eq, ":operation_in_progress", 1),

		(party_get_slot, ":action", ":party_no", slot_party_ai_state),
		(party_get_slot, ":object", ":party_no", slot_party_ai_object),
		
		(try_begin),
			(eq, ":troop_no", "$g_talk_troop"),
			(str_store_string, s14, "str_i_am_completing_what_i_have_already_begun"),
		(try_end),
	(else_try),
	  (eq, ":do_only_collecting_rents", 0),
		(assign, ":action", spai_undefined),
		(assign, ":object", -1),
		
		(try_begin),
			(eq, ":troop_no", "$g_talk_troop"),
			(str_store_string, s14, "str_i_dont_even_have_a_home_to_which_to_return"),
		(try_end),
	(try_end),
		
	(try_begin),
		(eq, "$cheat_mode", 2),
		(str_store_troop_name, s10, ":troop_no"),
		(display_message, "str_debug__s10_decides_s14_faction_ai_s15"),
	(try_end),
			
    (assign, reg0, ":action"),
	(assign, reg1, ":object"),  	
	]),
	
	#script_npc_decision_checklist_troop_follow_or_not
    # INPUT: troop_no
    # OUTPUT: reg0
	(
	"npc_decision_checklist_troop_follow_or_not", [

	(store_script_param, ":troop_no", 1),
	(store_faction_of_troop, ":faction_no", ":troop_no"),
	(faction_get_slot, ":faction_ai_state", ":faction_no", slot_faction_ai_state),

	(troop_get_slot, ":troop_reputation", ":troop_no", slot_lord_reputation_type),
	(faction_get_slot, ":faction_marshall", ":faction_no", slot_faction_marshall),
	
	(assign, ":result", 0),
	(try_begin),
		(eq, ":faction_marshall", -1),
		
		(try_begin),
			(eq, ":troop_no", "$g_talk_troop"),
			(str_store_string, s15, "str__i_am_acting_independently_because_no_marshal_is_appointed"),
		(try_end),
	(else_try),			
		(troop_get_slot, ":faction_marshall_party", ":faction_marshall", slot_troop_leaded_party),
		(neg|party_is_active, ":faction_marshall_party"),

		#Not doing an offensive
		(try_begin),
			(eq, ":troop_no", "$g_talk_troop"),
			(str_store_string, s15, "str__i_am_acting_independently_because_our_marshal_is_currently_indisposed"),
		(try_end),
	(else_try),
		(neq, ":faction_ai_state", sfai_attacking_center),
        (neq, ":faction_ai_state", sfai_raiding_village),
        (neq, ":faction_ai_state", sfai_attacking_enemies_around_center),
        (neq, ":faction_ai_state", sfai_attacking_enemy_army),
        (neq, ":faction_ai_state", sfai_gathering_army),
	
		#Not doing an offensive
		(try_begin),
			(eq, ":troop_no", "$g_talk_troop"),
			(str_store_string, s15, "str__i_am_acting_independently_because_our_realm_is_currently_not_on_campaign"),
		(try_end),
	(else_try),
		(call_script, "script_troop_get_relation_with_troop", ":troop_no", ":faction_marshall"),
		(assign, ":relation_with_marshall", reg0),
		
		(try_begin),
		  (le, ":relation_with_marshall", -10),
		  (assign, ":acceptance_level", 10000),
		(else_try),  
		  (store_mul, ":acceptance_level", ":relation_with_marshall", -1000),
		(try_end), 
		
		(val_add, ":acceptance_level", 1500),

        (game_get_reduce_campaign_ai, ":reduce_campaign_ai"),
		(try_begin),
		  (neq, ":faction_no", "$players_kingdom"),          
          (try_begin),
            (eq, ":reduce_campaign_ai", 0), #hard
            (val_add, ":acceptance_level", -1250),
          (else_try),
            (eq, ":reduce_campaign_ai", 1), #moderate
          (else_try),                        
            (eq, ":reduce_campaign_ai", 2), #easy
            (val_add, ":acceptance_level", 1250),
          (try_end),           
        (else_try), 
          (faction_slot_eq, ":faction_no", slot_faction_marshall, "trp_player"),           
          (try_begin),
            (eq, ":reduce_campaign_ai", 0), #hard/player's faction
            (val_add, ":acceptance_level", -1000),
          (else_try),
            (eq, ":reduce_campaign_ai", 1), #moderate/player's faction
            (val_add, ":acceptance_level", -1500),
          (else_try),                        
            (eq, ":reduce_campaign_ai", 2), #easy/player's faction
            (val_add, ":acceptance_level", -2000),
          (try_end),           
		(try_end),
										
		(troop_get_slot, ":temp_ai_seed", ":troop_no", slot_troop_temp_decision_seed),						
		
		(le, ":temp_ai_seed", ":acceptance_level"),				
	
		#Very low opinion of marshall
		(try_begin),
			(eq, ":troop_no", "$g_talk_troop"),
			(str_store_string, s15, "str__i_am_not_accompanying_the_marshal_because_i_fear_that_he_may_lead_us_into_disaster"),
		(try_end),
		#Make nuanced, depending on personality type
	(else_try),	
		(troop_get_slot, ":marshal_controversy", ":faction_marshall", slot_faction_marshall),
	
		(lt, ":relation_with_marshall", 0),
		(ge, ":marshal_controversy", 50),
		
		(try_begin),
			(eq, ":troop_no", "$g_talk_troop"),
			(str_store_string, s15, "str_i_am_not_accompanying_the_marshal_because_i_question_his_judgment"),
		(try_end),
	(else_try),	
		(troop_get_slot, ":marshal_controversy", ":faction_marshall", slot_faction_marshall),
		(neg|faction_slot_eq, ":faction_no", slot_faction_leader, ":faction_marshall"),
		
		(lt, ":relation_with_marshall", 5),
		(ge, ":marshal_controversy", 80),
		
		(try_begin),
			(eq, ":troop_no", "$g_talk_troop"),
			(str_store_string, s15, "str_i_am_not_accompanying_the_marshal_because_will_be_reappointment"),
		(try_end),
	(else_try),
		#(lt, ":relation_with_marshall", 45),	
		#(eq, ":faction_marshall", "trp_player"), #moved below as only effector. Search "think about this".
		
		(store_sub, ":relation_with_marshal_difference", 50, ":relation_with_marshall"),
		
		#for 50 relation with marshal ":acceptance_level" will be 0
		#for 20 relation with marshal ":acceptance_level" will be 2100
		#for 10 relation with marshal ":acceptance_level" will be 2800
		#for 0 relation with marshal ":acceptance_level" will be 3500
		#for -10 relation with marshal ":acceptance_level" will be 4200
		#average is about 2500
		(store_mul, ":acceptance_level", ":relation_with_marshal_difference", 70), 
		
        (game_get_reduce_campaign_ai, ":reduce_campaign_ai"),		
		(try_begin),
		  (neq, ":faction_no", "$players_kingdom"),
          
          (try_begin),
            (eq, ":reduce_campaign_ai", 0), #hard
            (val_add, ":acceptance_level", -1200),
          (else_try),
            (eq, ":reduce_campaign_ai", 1), #moderate
          (else_try),                        
            (eq, ":reduce_campaign_ai", 2), #easy
            (val_add, ":acceptance_level", 1200),
          (try_end),           
		(else_try),        
          (eq, ":faction_marshall", "trp_player"), 
          
          (try_begin),
            (eq, ":reduce_campaign_ai", 0), #hard
            (val_add, ":acceptance_level", -1000),
          (else_try),
            (eq, ":reduce_campaign_ai", 1), #moderate
            (val_add, ":acceptance_level", -1500),
          (else_try),                        
            (eq, ":reduce_campaign_ai", 2), #easy
            (val_add, ":acceptance_level", -2000),
          (try_end),           		  
		(try_end),
		
		(try_begin),
		  (eq, ":troop_reputation", lrep_selfrighteous),
		  (val_add, ":acceptance_level", 1500),
		(else_try),  
		  (this_or_next|eq, ":troop_reputation", lrep_martial),		
		  (this_or_next|eq, ":troop_reputation", lrep_roguish),		
		  (eq, ":troop_reputation", lrep_quarrelsome),
		  (val_add, ":acceptance_level", 1000),
		(else_try),  
		  (eq, ":troop_reputation", lrep_cunning), 
		  (val_add, ":acceptance_level", 500),
		(else_try),  
		  (eq, ":troop_reputation", lrep_upstanding), #neutral
		(else_try),  
		  (this_or_next|eq, ":troop_reputation", lrep_benefactor), #helper	
		  (eq, ":troop_reputation", lrep_goodnatured),		
		  (val_add, ":acceptance_level", -500),
		(else_try),  
		  (eq, ":troop_reputation", lrep_custodian), #very helper
		  (val_add, ":acceptance_level", -1000),
		(try_end),  
		
		(try_begin),
		  (troop_slot_eq, ":faction_marshall", slot_lord_reputation_type, lrep_quarrelsome),
		  (val_add, ":acceptance_level", -750),
		(else_try),  
		  (this_or_next|troop_slot_eq, ":faction_marshall", slot_lord_reputation_type, lrep_martial),
		  (troop_slot_eq, ":faction_marshall", slot_lord_reputation_type, lrep_upstanding),
		  (val_add, ":acceptance_level", -250),
		(try_end),  
				
		(val_add, ":acceptance_level", 2000),
		#average become 2500 + 2000 = 4500, (45% of lords will not join campaign because of this reason. (33% for hard, 57% for easy, 30% for marshal player))
										
		(troop_get_slot, ":temp_ai_seed", ":troop_no", slot_troop_temp_decision_seed),						
				
		(le, ":temp_ai_seed", ":acceptance_level"),		
		
		(try_begin),		  
		  (eq, ":troop_no", "$g_talk_troop"),		  		  		  
		  (str_store_string, s15, "str_i_am_not_accompanying_the_marshal_because_i_can_do_greater_deeds"),
		(try_end),	
		
		#(try_begin),
		#  (ge, "$cheat_mode", 1),
		#  (assign, reg7, ":acceptance_level"),
		#  (assign, reg8, ":relation_with_marshall"),
		#  (display_message, "@{!}DEBUGS : acceptance level : {reg7}, relation with marshal : {reg8}"),
		#(try_end),
	(else_try),
		(store_current_hours, ":hours_since_last_faction_rest"),
		(faction_get_slot, ":last_rest_time", ":faction_no", slot_faction_ai_last_rest_time),
		(val_sub, ":hours_since_last_faction_rest", ":last_rest_time"),				
		
		#nine days on average, marshal will usually end after 10 days
		#ozan changed, 360 hours (15 days) in average, marshal cannot end it during a siege attack/defence anymore.
		(assign, ":troop_campaign_limit", 360), 
		(store_mul, ":marshal_relation_modifier", ":relation_with_marshall", 6), #ozan changed 4 to 6.
		(val_add, ":troop_campaign_limit", ":marshal_relation_modifier"),
		
		(try_begin),
			(eq, ":troop_reputation", lrep_upstanding),
			(val_mul, ":troop_campaign_limit", 4),
			(val_div, ":troop_campaign_limit", 3),
		(try_end),
		
		(str_store_troop_name, s16, ":faction_marshall"),
	
		(gt, ":hours_since_last_faction_rest", ":troop_campaign_limit"),
		
		#Too long a campaign
		(try_begin),
			(eq, ":troop_no", "$g_talk_troop"),
			(str_store_string, s15, "str__s16_has_kept_us_on_campaign_on_far_too_long_and_there_are_other_pressing_matters_to_which_i_must_attend"),
		(try_end),
		#Also make nuanced, depending on personality type
	(else_try),	
		(troop_get_slot, ":party_no", ":troop_no", slot_troop_leaded_party),
		(neg|party_is_active, ":party_no"),
		#This string should not occur, as it will only happen if a lord is contemplating following the player		
	(else_try),	
		(troop_get_slot, ":marshal_party", ":faction_marshall", slot_troop_leaded_party),
		
		(assign, ":information_radius", 40), 
		(try_begin),
		  (faction_slot_eq, ":faction_no", slot_faction_ai_state, sfai_gathering_army),
		  (assign, ":information_radius", 50), 
		(try_end),
		
        (game_get_reduce_campaign_ai, ":reduce_campaign_ai"),
		(try_begin),
		  (neq, ":faction_no", "fac_player_supporters_faction"),
		  (neq, ":faction_no", "$players_kingdom"),		  
		  (try_begin),
		    (eq, ":reduce_campaign_ai", 2), #easy
		    (try_begin),
		      (faction_slot_eq, ":faction_no", slot_faction_ai_state, sfai_gathering_army),
		      (val_add, ":information_radius", -10),
		    (else_try),  
		      (val_add, ":information_radius", -8),
		    (try_end),
		  (else_try),
		    (eq, ":reduce_campaign_ai", 1), #moderate
		    (try_begin),
		      (faction_slot_eq, ":faction_no", slot_faction_ai_state, sfai_gathering_army),
		      (val_add, ":information_radius", -5),
		    (else_try),  
		      (val_add, ":information_radius", -4),
		    (try_end),
		  (try_end),
		(else_try),  
		  (try_begin),
		    (eq, ":reduce_campaign_ai", 2), #easy
		    (try_begin),
		      (faction_slot_eq, ":faction_no", slot_faction_ai_state, sfai_gathering_army),
		      (val_add, ":information_radius", 25),
		    (else_try),  
		      (val_add, ":information_radius", 20),
		    (try_end),
		  (else_try),
		    (eq, ":reduce_campaign_ai", 1), #moderate
		    (try_begin),
		      (faction_slot_eq, ":faction_no", slot_faction_ai_state, sfai_gathering_army),
		      (val_add, ":information_radius", 15),
		    (else_try),  
		      (val_add, ":information_radius", 12),
		    (try_end),
		  (else_try),
		    (eq, ":reduce_campaign_ai", 0), #hard
		    (try_begin),
		      (faction_slot_eq, ":faction_no", slot_faction_ai_state, sfai_gathering_army),
		      (val_add, ":information_radius", 5),
		    (else_try),  
		      (val_add, ":information_radius", 4),
		    (try_end),
		  (try_end),		
		(try_end),  
		
		(faction_get_slot, ":faction_object", ":faction_no", slot_faction_ai_object),		  
		(assign, reg17, 0),
		(try_begin),		  		  
		  (try_begin),
		    (neg|is_between, ":faction_object", villages_begin, villages_end),
		    (assign, reg17, 1),
		  (try_end),
		  (try_begin),
		    (neg|faction_slot_eq, ":faction_no", slot_faction_ai_state, sfai_attacking_enemies_around_center),
		    (assign, reg17, 1),
		  (try_end),		  
		  (eq, reg17, 1),
		  
		  (store_distance_to_party_from_party, ":distance", ":marshal_party", ":party_no"),

		  (gt, ":distance", ":information_radius"),
		
          (try_begin),
            (eq, ":troop_no", "$g_talk_troop"),
            (str_store_string, s15, "str__i_am_not_participating_in_the_marshals_campaign_because_i_do_not_know_where_to_find_our_main_army"),
  		  (try_end),  		  
		(else_try),	
		  (eq, reg17, 0),	
		  
          (assign, reg17, 1),
          (try_begin),
            #if we are already accompanying marshal forget below.
            (party_slot_eq, ":party_no", slot_party_ai_state, spai_accompanying_army),
            (party_slot_eq, ":party_no", slot_party_ai_object, ":marshal_party"),
            (assign, reg17, 0),
          (try_end),                                
          (eq, reg17, 1),
                              
		  #if faction ai is "attacking enemies around a center" is then do not find and compare distance to marshal, find and compare distance to "attacked village"
		  (party_get_slot, ":enemy_strength_nearby", ":faction_object", slot_center_sortie_enemy_strength),
		  
		  (try_begin), #changes between 70..x (as ":enemy_strength_nearby" increases, ":information_radius" increases too.),
		    (ge, ":enemy_strength_nearby", 4000),
		    (val_sub, ":enemy_strength_nearby", 4000),
		    (store_div, ":information_radius", ":enemy_strength_nearby", 200),
		    (val_add, ":information_radius", 70),
		  (else_try), #changes between 30..70
		    (store_div, ":information_radius", ":enemy_strength_nearby", 100),
		    (val_add, ":information_radius", 30),
		  (try_end),
		  
		  (store_distance_to_party_from_party, ":distance", ":faction_object", ":party_no"),

		  (gt, ":distance", ":information_radius"),
		
          (try_begin),
            (eq, ":troop_no", "$g_talk_troop"),
            (str_store_string, s15, "str__i_am_acting_independently_although_some_enemies_have_been_spotted_within_our_borders_they_havent_come_in_force_and_the_local_troops_should_be_able_to_dispatch_them"),
  		  (try_end),  		  
		(try_end),
		
		(gt, ":distance", ":information_radius"),
	(else_try),
		(try_begin),
		  (eq, ":troop_no", "$g_talk_troop"),
		  (str_store_string, s15, "str__the_needs_of_the_realm_must_come_first"),
		(try_end),
		(assign, ":result", 1),
	(try_end),
			
	(assign, reg0, ":result"),	
	]),
	
	#script_find_total_prosperity_score
    # INPUT: center_no
    # OUTPUT: reg0 = total_prosperity_score
	(
	"find_total_prosperity_score",
	[
	  (store_script_param, ":center_no", 1),
	  
      (try_begin), #":total_prosperity_score" changes between 10..100
        (is_between, ":center_no", walled_centers_begin, walled_centers_end),
            
        (party_get_slot, ":center_prosperity", ":center_no", slot_town_prosperity),
        (store_add, ":center_prosperity_add_200_div_10", ":center_prosperity", 200),
        (val_div, ":center_prosperity_add_200_div_10", 10),
        (try_begin),
          (is_between, ":center_no", towns_begin, towns_end),            
          (store_mul, ":this_center_score", ":center_prosperity_add_200_div_10", 15),
        (else_try),
          (store_mul, ":this_center_score", ":center_prosperity_add_200_div_10", 5),
        (try_end),
        (assign, ":total_prosperity_score", ":this_center_score"), 
                        
        (try_for_range_backwards, ":village_no", villages_begin, villages_end),
          (party_slot_eq, ":village_no", slot_village_bound_center, ":center_no"),

          (party_get_slot, ":village_prosperity", ":village_no", slot_town_prosperity),
          (store_add, ":village_prosperity_add_200_div_10", ":village_prosperity", 200),
          (val_div, ":village_prosperity_add_200_div_10", 10),
          (store_mul, ":this_village_score", ":village_prosperity_add_200_div_10", 5),
                    
          (val_add, ":total_prosperity_score", ":this_village_score"), 
        (try_end),
      (else_try),
        (party_get_slot, ":center_prosperity", ":center_no", slot_town_prosperity),
        (store_add, ":center_prosperity_add_200_div_10", ":center_prosperity", 200),
        (val_div, ":center_prosperity_add_200_div_10", 10),
        (store_mul, ":this_center_score", ":center_prosperity_add_200_div_10", 5),
        (assign, ":total_prosperity_score", ":this_center_score"), 
      (try_end),
      (val_div, ":total_prosperity_score", 10),
      
      (assign, reg0, ":total_prosperity_score"),
	]),
		
    #script_calculate_center_assailability_score
    # INPUT: faction_no
    # param1: faction_no 
    # param2: all_vassals_included, (becomes 1 if we want to find attackable center if we collected 20% of vassals during gathering army phase)
    # OUTPUT: 
    # reg0 = center_to_attack (-1 if none is logical)
    # reg1 = maximum_attack_score
    (
    "calculate_center_assailability_score", 
    [		
      (store_script_param, ":troop_no", 1),
      (store_script_param, ":potential_target", 2),
      (store_script_param, ":all_vassals_included", 3),
      
      (assign, ":target_score", -1),
      
      (store_faction_of_troop, ":faction_no", ":troop_no"),
  
      (store_current_hours, ":hours_since_last_offensive"),
      (faction_get_slot, ":last_offensive_time", ":faction_no", slot_faction_last_offensive_concluded),
      (val_sub, ":hours_since_last_offensive", ":last_offensive_time"),
      
      (store_div, ":last_offensive_time_score", ":hours_since_last_offensive", 12), #30..50
      (val_add, ":last_offensive_time_score", 30),
      (val_min, ":last_offensive_time_score", 100),

      (faction_get_slot, ":faction_marshal", ":faction_no", slot_faction_marshall),
    
      (assign, ":marshal_party", -1),
      (assign, ":marshal_strength", 0),
      #(assign, ":strength_of_nearby_friend", 0),
      
      (try_begin),
        (gt, ":faction_marshal", 0),
        (troop_get_slot, ":marshal_party", ":faction_marshal", slot_troop_leaded_party),
        (party_is_active, ":marshal_party"),
        (party_get_slot, ":marshal_strength", ":marshal_party", slot_party_cached_strength),
        #(eq, ":all_vassals_included", 0),
        (party_get_slot, ":strength_of_current_followers", ":marshal_party", slot_party_follower_strength),
        #(party_get_slot, ":strength_of_nearby_friend", ":marshal_party", slot_party_nearby_friend_strength),
      (try_end),
  
      #(try_begin),
      #  (eq, ":all_vassals_included", 0),
      #    
      #  (try_begin),
      #    (gt, ":faction_marshal", 0),
      #    (troop_get_slot, ":marshal_party", ":faction_marshal", slot_troop_leaded_party),
      #    (party_is_active, ":marshal_party"),
      #    (party_get_slot, ":strength_of_potential_followers", ":marshal_party", slot_party_follower_strength),
      #  (try_end),                
      #(else_try),
      #  (eq, ":all_vassals_included", 1),
      #      
      #  (assign, ":strength_of_potential_followers", 0),
      #          
      #  (try_for_parties, ":party_no"),
      #    (store_faction_of_party, ":party_faction", ":party_no"),
      #    (eq, ":party_faction", ":faction_no"),
      #    (neq, ":party_no", ":marshal_party"),          
      #    (party_slot_eq, ":party_no", slot_party_type, spt_kingdom_hero_party),
      #    (call_script, "script_party_calculate_strength", ":party_no", 0),
      #    (val_add, ":strength_of_potential_followers", reg0),
      #  (try_end),    
      #  
      #  (val_div, ":strength_of_potential_followers", 2), #Ozan - Think about this, will you divide strength_of_potential_followers to 3 or 2.5 or 2
      #(else_try),
      #  (assign, ":strength_of_potential_followers", 0),      
      #(try_end),
      
      (faction_get_slot, ":last_attacked_center", ":faction_no", slot_faction_last_attacked_center),
      (faction_get_slot, ":last_attacked_hours", ":faction_no", slot_faction_last_attacked_hours),
            
      (try_begin),
        (store_current_hours, ":hours"),
        (store_add, ":last_attacked_hours_plus_24", ":last_attacked_hours", 24),
        (gt, ":hours", ":last_attacked_hours_plus_24"),
        (faction_set_slot, ":faction_no", slot_faction_last_attacked_center, 0),
        (assign, ":last_attacked_center", 0),
      (try_end),
                
      (try_begin),        
        (this_or_next|eq, ":last_attacked_center", 0),
        (this_or_next|eq, ":last_attacked_center", ":potential_target"),
        (this_or_next|eq, "$g_do_not_skip_other_than_current_ai_object", 1),
        (neg|faction_slot_eq, ":faction_no", slot_faction_marshall, ":troop_no"),
        
        (party_is_active, ":potential_target"),
        (store_faction_of_party, ":potential_target_faction", ":potential_target"),
          
        (store_relation, ":relation", ":potential_target_faction", ":faction_no"),	      
        (lt, ":relation", 0),
        
        #attack if and only if we are already besieging that center or anybody do not making besiege.
        (assign, ":faction_of_besieger_party", -1),
        (try_begin),        
          (is_between, ":potential_target", walled_centers_begin, walled_centers_end),      
          (neg|party_slot_eq, ":potential_target", slot_center_is_besieged_by, -1), 
          (party_get_slot, ":besieger_party", ":potential_target", slot_center_is_besieged_by),
          (party_is_active, ":besieger_party"),
          (store_faction_of_party, ":faction_of_besieger_party", ":besieger_party"),
        (try_end),	
        			     
        (this_or_next|eq, ":faction_of_besieger_party", -1), 
        (eq, ":faction_of_besieger_party", ":faction_no"),
        
        #attack if and only if this center is not a village or if it is village it should not be raided or looted
        (assign, ":village_is_looted_or_raided_already", 0),
        (try_begin),
          (is_between, ":potential_target", villages_begin, villages_end),
          (try_begin),
            (party_slot_eq, ":potential_target", slot_village_state, svs_being_raided),
            (party_get_slot, ":raider_party", ":potential_target", slot_village_raided_by),
			(party_is_active, ":raider_party"),
			
            (store_faction_of_party, ":raider_faction", ":raider_party"),
            (neq, ":raider_faction", ":faction_no"),
            (assign, ":raiding_by_one_other_faction", 1),
          (else_try),
            (assign, ":raiding_by_one_other_faction", 0),
          (try_end),  
          (this_or_next|party_slot_eq, ":potential_target", slot_village_state, svs_looted),
          (eq, ":raiding_by_one_other_faction", 1),
          (assign, ":village_is_looted_or_raided_already", 1),
        (try_end),        
        (eq, ":village_is_looted_or_raided_already", 0),

        #if ":potential_target" is faction object of some other faction which is enemy to owner of 
        #":potential_target" then this target cannot be new target we are looking for.
        (assign, ":this_potantial_target_is_target_of_some_other_faction", 0),
        (try_for_range, ":cur_faction", kingdoms_begin, kingdoms_end),
          (is_between, ":cur_faction", "fac_kingdom_1", kingdoms_end), #Excluding player kingdom
          (neq, ":cur_faction", ":faction_no"),
          (faction_get_slot, ":faction_object", ":cur_faction", slot_faction_ai_object),
          (eq, ":faction_object", ":potential_target"),
          (store_relation, ":rel", ":potential_target_faction", ":cur_faction"),
          (lt, ":rel", 0),
          (assign, ":this_potantial_target_is_target_of_some_other_faction", 1),          
        (try_end),      
        (eq, ":this_potantial_target_is_target_of_some_other_faction", 0),                                            
    		  				
        (try_begin),
          (is_between, ":potential_target", walled_centers_begin, walled_centers_end),      
          (party_get_slot, ":potential_target_inside_strength", ":potential_target", slot_party_cached_strength),
          (party_get_slot, ":potential_target_nearby_enemy_strength", ":potential_target", slot_party_nearby_friend_strength),    
          (val_div, ":potential_target_nearby_enemy_strength", 2),        
          (store_add, ":potential_target_strength", ":potential_target_inside_strength", ":potential_target_nearby_enemy_strength"),

          #(try_begin),
            #(eq, ":faction_no", "fac_kingdom_4"),
            #(assign, reg0, ":potential_target_inside_strength"),
            #(assign, reg1, ":potential_target_nearby_enemy_strength"),
            #(assign, reg2, ":marshal_strength"),
            #(assign, reg3, ":strength_of_potential_followers"),
            #(assign, reg4, ":strength_of_nearby_friend"),
            #(assign, reg6, ":marshal_party"),
            #(str_store_party_name, s8, ":potential_target"),
            #(eq, ":all_vassals_included", 0),
            #(display_message, "@DEBUG : {s8}:{reg0}, neare {reg1}, our {reg2}, follow {reg3}, nearf {reg4}"),
          #(try_end),
                    
          (val_mul, ":potential_target_strength", 4), #in walled centers defenders have advantage.
          (val_div, ":potential_target_strength", 3),
                              
          #(store_add, ":army_strength", ":marshal_strength", ":strength_of_potential_followers"),
          (assign, ":army_strength", ":marshal_strength"),
          (val_add, ":army_strength", ":strength_of_current_followers"),
          (store_mul, ":power_ratio", ":army_strength", 100),
          
          #this ratio ":power_ratio" shows (our total army power) / (their total army power)
          (try_begin),
            (gt, ":potential_target_strength", 0),
            (val_div, ":power_ratio", ":potential_target_strength"),
          (else_try),
            (assign, ":power_ratio", 1000),
          (try_end),  
        (else_try),        
          (party_get_slot, ":potential_target_nearby_enemy_strength", ":potential_target", slot_party_nearby_friend_strength),                      
          (assign, ":potential_target_strength", 1000),
                    
          #(store_add, ":army_strength", ":marshal_strength", ":strength_of_potential_followers"),
          (assign, ":army_strength", ":marshal_strength"),
          (val_add, ":army_strength", ":strength_of_current_followers"),
          (store_mul, ":power_ratio", ":army_strength", 100),
                                                            
          (try_begin),
            (gt, ":potential_target_strength", 0),
            (val_div, ":power_ratio", ":potential_target_strength"),
          (else_try),
            (assign, ":power_ratio", 1000),
          (try_end),            
        (try_end),
                            
        (ge, ":power_ratio", 120), #attack if and only if our army is at least 1.2 times powerfull				
        (store_sub, ":power_ratio_sub_120", ":power_ratio", 120),
        
        (try_begin),
          (lt, ":power_ratio_sub_120", 100), #changes between 20..120
          (store_add, ":power_ratio_score", ":power_ratio_sub_120", 20),
        (else_try),
          (lt, ":power_ratio_sub_120", 200), #changes between 120..170
          (store_sub, ":power_ratio_score", ":power_ratio_sub_120", 100),
          (val_div, ":power_ratio_score", 2),
          (val_add, ":power_ratio_score", 120),
        (else_try),
          (lt, ":power_ratio_sub_120", 400), #changes between 170..210
          (store_sub, ":power_ratio_score", ":power_ratio_sub_120", 200),
          (val_div, ":power_ratio_score", 5),
          (val_add, ":power_ratio_score", 170),
        (else_try),
          (lt, ":power_ratio_sub_120", 800), #changes between 210..250
          (store_sub, ":power_ratio_score", ":power_ratio_sub_120", 400),
          (val_div, ":power_ratio_score", 10),
          (val_add, ":power_ratio_score", 210),
        (else_try),
          (assign, ":power_ratio_score", 250),
        (try_end),
          
        (assign, ":number_of_walled_centers", 0),
        (assign, ":total_distance", 0),
        (try_for_range, ":walled_center", walled_centers_begin, walled_centers_end),
          (store_faction_of_party, ":walled_center_faction", ":walled_center"),
          (eq, ":walled_center_faction", ":faction_no"),
                
          (store_distance_to_party_from_party, ":dist", ":walled_center", ":potential_target"),            
          (val_add, ":total_distance", ":dist"),
                
          (val_add, ":number_of_walled_centers", 1),
        (try_end),
                
        (try_begin),
          (gt, ":number_of_walled_centers", 0),
          (store_div, ":average_distance", ":total_distance", ":number_of_walled_centers"),
          #(assign, reg0, ":average_distance"),                    
          #(str_store_faction_name, s7, ":faction_no"),
          #(str_store_party_name, s8, ":potential_target"),
          #(display_message, "@average distance for {s7} for {s8} is {reg0}"),
          
          (try_begin),
            (ge, ":marshal_party", 0),
            (party_is_active, ":marshal_party"),
            (store_distance_to_party_from_party, ":marshal_dist_to_potential_target", ":marshal_party", ":potential_target"),
          (else_try),
            (assign, ":marshal_dist_to_potential_target", 100),
          (try_end),
                      
          (try_begin),  
            #if currently our target is attacking to an enemy center and that center is besieged/raided by one of our parties then 
            #divide marshal_distance for other center's to "2" instead of "3" and add some small more distance to avoid easily 
            #changing mind during siege because of small score differences.
              
            (faction_get_slot, ":current_ai_state", ":faction_no", slot_faction_ai_state),
            (eq, ":current_ai_state", sfai_attacking_center),
            (faction_get_slot, ":current_ai_object", ":faction_no", slot_faction_ai_object),
            
            (ge, ":current_ai_object", 0),
            (neq, ":current_ai_object", ":potential_target"),
              
            (try_begin),
              (ge, ":power_ratio_score", 300), #200 max
              (assign, ":power_ratio_score", 200),
            (else_try),
              (ge, ":power_ratio_score", 100), #100..200
              (val_sub, ":power_ratio_score", 100),
              (val_div, ":power_ratio_score", 2),
              (val_add, ":power_ratio_score", 100),
            (try_end),  
            
            (try_begin),
              (faction_slot_eq, ":faction_no", slot_faction_marshall, ":troop_no"),
              (eq, "$g_do_not_skip_other_than_current_ai_object", 0),
              (assign, ":power_ratio_score", 0), #lets completely forget all other choices if we are already besieging one center.
            (try_end),  
            
            (faction_set_slot, ":faction_no", slot_faction_last_attacked_center, ":current_ai_object"),
            (store_current_hours, ":hours"),
            (faction_set_slot, ":faction_no", slot_faction_last_attacked_hours, ":hours"),

            (eq, ":all_vassals_included", 0),

            (store_div, ":marshal_dist_to_potential_target_div_x", ":marshal_dist_to_potential_target", 2),
            (assign, ":marshal_dist_to_potential_target_div_x", ":marshal_dist_to_potential_target"),
          (else_try),
            (store_div, ":marshal_dist_to_potential_target_div_x", ":marshal_dist_to_potential_target", 3),
          (try_end),
            
          (store_add, ":total_distance", ":average_distance", ":marshal_dist_to_potential_target_div_x"), #in average ":total_distance" is about 150, min : 0, max : 1000
        (else_try),
          (assign, ":total_distance", 100),
        (try_end),                

        (try_begin),
          #according to cautious troop distance is more important

	      (this_or_next|troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_upstanding),
	      (this_or_next|troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_debauched),
	      (this_or_next|troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_goodnatured),
	      (troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_cunning),	      	      

          (try_begin),
            (lt, ":total_distance", 30), #very close (100p)
            (assign, ":distance_score", 100),
          (else_try),
            (lt, ":total_distance", 80), #close (50p-100p)
            (store_sub, ":distance_score", ":total_distance", 30),
            (val_div, ":distance_score", 1),
            (store_sub, ":distance_score", 100, ":distance_score"),
          (else_try),  
            (lt, ":total_distance", 160), #far (10p-50p)
            (store_sub, ":distance_score", ":total_distance", 80),
            (val_div, ":distance_score", 2),
            (store_sub, ":distance_score", 50, ":distance_score"),
          (else_try),
            (assign, ":distance_score", 10), #very far
          (try_end),
        (else_try),  
          #according to agressive troop distance is less important
          
          (try_begin),
            (lt, ":total_distance", 40), #very close (100p)
            (assign, ":distance_score", 100),
          (else_try),
            (lt, ":total_distance", 140), #close (50p-100p)
            (store_sub, ":distance_score", ":total_distance", 40),
            (val_div, ":distance_score", 2),
            (store_sub, ":distance_score", 100, ":distance_score"),
          (else_try),  
            (lt, ":total_distance", 300), #far (10p-50p)
            (store_sub, ":distance_score", ":total_distance", 140),
            (val_div, ":distance_score", 4),
            (store_sub, ":distance_score", 50, ":distance_score"),
          (else_try),
            (assign, ":distance_score", 10), #very far
          (try_end),
        (try_end),
                                                                                           
        (store_mul, ":target_score", ":distance_score", ":power_ratio_score"),
        (val_mul, ":target_score", ":last_offensive_time_score"),
        (val_div, ":target_score", 100), #target score is between 0..10000 generally here

        (call_script, "script_find_total_prosperity_score", ":potential_target"),                
        (assign, ":total_prosperity_score", reg0),
            
        #(try_begin), #new for increase attackability of villages by ai
          #(is_between, ":potential_target", villages_begin, villages_end), 
          (val_mul, ":total_prosperity_score", 3),
          (val_div, ":total_prosperity_score", 2),
        #(try_end),

        (val_mul, ":target_score", ":total_prosperity_score"),
          
        (try_begin), #if both that center was our (original center) and (ex center) than bonus is 1.2x
          (party_slot_eq, ":potential_target", slot_center_ex_faction, ":faction_no"),
          (party_slot_eq, ":potential_target", slot_center_original_faction, ":faction_no"),
          (val_mul, ":target_score", 12),
          (val_div, ":target_score", 10),
        (else_try), #if either that center was our (original center) or (ex center) than bonus is 1.1x
          (this_or_next|party_slot_eq, ":potential_target", slot_center_ex_faction, ":faction_no"),
          (party_slot_eq, ":potential_target", slot_center_original_faction, ":faction_no"),
          (val_mul, ":target_score", 11),
          (val_div, ":target_score", 10),
        (try_end),
            
        (val_div, ":target_score", 1000), #target score is between 0..1000 generally here
        
        (try_begin),
          (eq, ":potential_target_faction", "fac_player_supporters_faction"),
          (game_get_reduce_campaign_ai, ":reduce_campaign_ai"),
          
          (assign, ":number_of_walled_centers_player_have", 0),
          (try_for_range, ":center_no", walled_centers_begin, walled_centers_end),
            (store_faction_of_party, ":center_faction", ":center_no"),
            (eq, ":center_faction", "fac_player_supporters_faction"),
            (val_add, ":number_of_walled_centers_player_have", 1),
          (try_end),
          
          (try_begin),
            (eq, ":reduce_campaign_ai", 2), #easy
            
            (try_begin),
              (le, ":number_of_walled_centers_player_have", 2),
              (assign, ":hardness_score", 0),              
            (else_try),
              (eq, ":number_of_walled_centers_player_have", 3),
              (assign, ":hardness_score", 20),
            (else_try),
              (eq, ":number_of_walled_centers_player_have", 4),
              (assign, ":hardness_score", 40),
            (else_try),
              (eq, ":number_of_walled_centers_player_have", 5),
              (eq, ":number_of_walled_centers_player_have", 6),
              (assign, ":hardness_score", 55),
            (else_try),
              (eq, ":number_of_walled_centers_player_have", 7),
              (eq, ":number_of_walled_centers_player_have", 8),
              (eq, ":number_of_walled_centers_player_have", 9),
              (assign, ":hardness_score", 70),
            (else_try),
              (assign, ":hardness_score", 85),
            (try_end),
          (else_try),  
            (eq, ":reduce_campaign_ai", 1), #medium

            (try_begin),
              (le, ":number_of_walled_centers_player_have", 1),
              (assign, ":hardness_score", 25),
            (else_try),
              (eq, ":number_of_walled_centers_player_have", 2),
              (assign, ":hardness_score", 45),
            (else_try),
              (eq, ":number_of_walled_centers_player_have", 3),
              (assign, ":hardness_score", 60),
            (else_try),
              (eq, ":number_of_walled_centers_player_have", 4),
              (eq, ":number_of_walled_centers_player_have", 5),
              (assign, ":hardness_score", 75),
            (else_try),
              (eq, ":number_of_walled_centers_player_have", 6),
              (eq, ":number_of_walled_centers_player_have", 7),
              (eq, ":number_of_walled_centers_player_have", 8),
              (assign, ":hardness_score", 85),
            (else_try),
              (assign, ":hardness_score", 92),
            (try_end),
          (else_try), #hard
            (assign, ":hardness_score", 100), 
          (try_end),
          
          (val_mul, ":target_score", ":hardness_score"),
          (val_div, ":target_score", 100),
        (try_end),

        (try_begin),
          (ge, "$cheat_mode", 1),
          (eq, ":faction_no", "fac_kingdom_4"),
          (ge, ":target_score", -1),
          (assign, reg0, ":target_score"),
          (assign, reg7, ":total_prosperity_score"),
          (assign, reg8, ":power_ratio_score"),
          (assign, reg9, ":distance_score"),
          (assign, reg10, ":last_offensive_time_score"),
          (str_store_party_name, s8, ":potential_target"),
          #(eq, ":all_vassals_included", 0),
          (assign, reg11, ":all_vassals_included"),          
          #(display_message, "@DEBUG : attack of {s8} is {reg0}({reg11}), prs:{reg7}, pow:{reg8}, dis:{reg9}, lst:{reg10}"),
        (try_end),  
      (try_end),
                                                     
      (assign, reg0, ":target_score"),
      (assign, reg1, ":power_ratio"),
      (assign, reg2, ":distance_score"),
      (assign, reg3, ":total_prosperity_score"),
    ]),
		
    #script_find_center_to_defend
    # INPUT: 
    # param1: faction_no 
    # OUTPUT: 
    # reg0 = center_to_defend (-1 if none is logical)
    # reg1 = maximum_defend_score
    # reg3 = enemy_strength_near_most_threatened_center
    (
    "find_center_to_defend",
    [
      (store_script_param, ":troop_no", 1),
	  
	  (store_faction_of_troop, ":faction_no", ":troop_no"),
	  
      (faction_get_slot, ":faction_marshal", ":faction_no", slot_faction_marshall),
      (faction_get_slot, ":current_ai_state", ":faction_no", slot_faction_ai_state),
      (assign, ":marshal_party", -1),  
      (try_begin),
        (gt, ":faction_marshal", 0),
        (troop_get_slot, ":marshal_party", ":faction_marshal", slot_troop_leaded_party),
      (try_end),

      (assign, ":most_threatened_center", -1),
      (assign, ":maximum_threat_score", 0),	
      (try_for_range, ":cur_center", centers_begin, centers_end),
        (store_faction_of_party, ":center_faction", ":cur_center"),
        (eq, ":center_faction", ":faction_no"),
	 	    
        (party_get_slot, ":exact_enemy_strength", ":cur_center", slot_center_sortie_enemy_strength),
		#Distort this to account for questionable intelligence
		#(call_script, "script_reduce_exact_number_to_estimate", ":exact_enemy_strength"),
		#(assign, ":enemy_strength_nearby", reg0),
		(assign, ":enemy_strength_nearby", ":exact_enemy_strength"),		
		
        (assign, ":threat_importance", 0),
        (try_begin),          
          (is_between, ":cur_center", walled_centers_begin, walled_centers_end),
          (party_slot_ge, ":cur_center", slot_center_is_besieged_by, 0),
          
          (call_script, "script_find_total_prosperity_score", ":cur_center"),
          (assign, ":total_prosperity_score", reg0),          
                              
          (party_get_slot, ":cur_center_strength", ":cur_center", slot_party_cached_strength),
          (val_mul, ":cur_center_strength", 4),
          (val_div, ":cur_center_strength", 3), #give 33% bonus to insiders because they are inside a castle
          
          #I removed below line and assigned ":cur_center_nearby_strength" to 0, because if not when defender army comes to help
          #threat become less because of high defence power but not yet enemy cleared.
          #(party_get_slot, ":cur_center_nearby_strength", ":cur_center", slot_party_nearby_friend_strength),
          (assign, ":cur_center_nearby_strength", 0),
          
          (val_add, ":cur_center_strength", ":cur_center_nearby_strength"), #add nearby friends and find ":cur_center_strength"
          
          (store_mul, ":power_ratio", ":enemy_strength_nearby", 100),
          (val_add, ":cur_center_strength", 1),
		  (val_max, ":cur_center_strength", 1),
          (val_div, ":power_ratio", ":cur_center_strength"),
         
          (assign, ":player_is_attacking", 0),
          (party_get_slot, ":besieger_party", ":cur_center", slot_center_is_besieged_by),
          (try_begin),
            (party_is_active, ":besieger_party"),
            (try_begin),
              (eq, ":besieger_party", "p_main_party"),
              (assign, ":player_is_attacking", 1),
              #(display_message, "@{!}DEBUG : player is attacking a center (1)"),
            (else_try),
              (store_faction_of_party, ":besieger_faction", ":besieger_party"),
              (eq, ":besieger_faction", "fac_player_faction"),
              (assign, ":player_is_attacking", 1),
              #(display_message, "@{!}DEBUG : player is attacking a center (2)"),
            (else_try), 
              (party_get_attached_to, ":player_is_attached_to", "p_main_party"),
              (ge, ":player_is_attached_to", 0),
              (eq, ":player_is_attached_to", ":besieger_party"),
              (assign, ":player_is_attacking", 1),
              #(display_message, "@{!}DEBUG : player is attacking a center (3)"),
            (try_end),
          (try_end),
          
          (try_begin),
            (eq, ":player_is_attacking", 0),                       
            
            (try_begin),
              (lt, ":power_ratio", 40), #changes between 1..1
              (assign, ":threat_importance", 1),
            (else_try),  
              (lt, ":power_ratio", 80), #changes between 1..7
              (store_sub, ":threat_importance", ":power_ratio", 40),
              (val_div, ":threat_importance", 5),
              (val_add, ":threat_importance", 1), #1
            (else_try),  
              (lt, ":power_ratio", 120), #changes between 7..17
              (store_sub, ":threat_importance", ":power_ratio", 80),
              (val_div, ":threat_importance", 4),
              (val_add, ":threat_importance", 7), #1 + 6
            (else_try),  
              (lt, ":power_ratio", 200),
              (store_sub, ":threat_importance", ":power_ratio", 120),
              (val_div, ":threat_importance", 10),
              (val_add, ":threat_importance", 17), #1 + 6 + 10
            (else_try),  
              (assign, ":threat_importance", 25),
            (try_end),  
          (else_try),
            (try_begin),
              (lt, ":power_ratio", 200), #changes between 5..25
              (store_div, ":threat_importance", ":power_ratio", 10),    #MOTO correction (thanks MOTO:) (mexxico))
              (val_add, ":threat_importance", 6 ),
            (else_try),  
              (assign, ":threat_importance", 26),
            (try_end),             
          (try_end),          
        (else_try),        
          (is_between, ":cur_center", villages_begin, villages_end),
          (party_slot_eq, ":cur_center", slot_village_state, svs_being_raided),
          
          (gt, ":enemy_strength_nearby", 0),
          
          (call_script, "script_find_total_prosperity_score", ":cur_center"),
          (assign, ":power_ratio", 100), #useless
          (assign, ":total_prosperity_score", reg0),
          (assign, ":threat_importance", 10), #if faction village is looted they lose money for shorter time period. So importance is something low (6-8).
        (try_end),
        
        (gt, ":threat_importance", 0),
        
        (try_begin),
          (is_between, ":cur_center", walled_centers_begin, walled_centers_end),
          (assign, ":enemy_strength_nearby_score", 120), 
          
          (try_begin),          
            (ge, ":marshal_party", 0),
            (party_is_active, ":marshal_party"),
            (store_distance_to_party_from_party, ":marshal_dist_to_cur_center", ":marshal_party", ":cur_center"),
          (else_try),
            (assign, ":marshal_dist_to_cur_center", 100),
          (try_end),
                              
          (try_begin),  
            #if currently our target is ride to break a siege then
            #divide marshal_distance for other center's to "2" instead of "4" and add some small more distance to avoid easily 
            #changing mind during siege because of small score differences.
            
	        #(faction_get_slot, ":current_ai_state", ":faction_no", slot_faction_ai_state),
            (eq, ":current_ai_state", sfai_attacking_enemies_around_center),                                   
            (faction_get_slot, ":current_ai_object", ":faction_no", slot_faction_ai_object),            
            (is_between, ":current_ai_object", walled_centers_begin, walled_centers_end),            
            (neq, ":current_ai_object", ":cur_center"),
            (val_mul, ":marshal_dist_to_cur_center", 2),
            (val_add, ":marshal_dist_to_cur_center", 20),
          (try_end),
          
          (val_mul, ":marshal_dist_to_cur_center", 2), #standard multipication (1.5x) to adjust distance scoring same with formula at find_center_to_attack
          #(val_div, ":marshal_dist_to_cur_center", 2),
                    
          (try_begin),
            (lt, ":marshal_dist_to_cur_center", 10), #very close (100p)
            (assign, ":distance_score", 100),
          (else_try),
            (lt, ":marshal_dist_to_cur_center", 160), #close (50p-100p)
            (store_sub, ":distance_score", ":marshal_dist_to_cur_center", 10),
            (val_div, ":distance_score", 3),
            (store_sub, ":distance_score", 100, ":distance_score"),
          (else_try),  
            (lt, ":marshal_dist_to_cur_center", 360), #far (10p-50p)
            (store_sub, ":distance_score", ":marshal_dist_to_cur_center", 250),
            (val_div, ":distance_score", 5),
            (store_sub, ":distance_score", 50, ":distance_score"),
          (else_try),
            (assign, ":distance_score", 10), #very far
          (try_end),
        (else_try),
          (store_add, ":enemy_strength_nearby_score", ":enemy_strength_nearby", 20000), 
          (val_div, ":enemy_strength_nearby_score", 200),
          (assign, ":distance_score", 70), #not related to marshal's position, because everybody is going same place (no gathering in most village raids)
        (try_end),          
        
        (store_mul, ":threat_score", ":enemy_strength_nearby_score", ":total_prosperity_score"), 
        (val_mul, ":threat_score", ":threat_importance"), 
        (val_mul, ":threat_score", ":distance_score"),
        (val_div, ":threat_score", 10000),
        
        (try_begin),
		  (ge, "$cheat_mode", 1),
          (gt, ":threat_score", 0),
          (eq, ":faction_no", "fac_kingdom_6"),
          (assign, reg0, ":threat_score"),
          (str_store_party_name, s32, ":cur_center"),
          (assign, reg1,  ":total_prosperity_score"),
          (assign, reg2, ":enemy_strength_nearby_score"),
          (assign, reg3, ":threat_importance"),
          (assign, reg4, ":distance_score"),
          #(display_message, "@{!}DEBUG : defend of {s32} is {reg0}, prosperity:{reg1}, enemy nearby:{reg2}, threat importance:{reg3}, distance: {reg4}"),
        (try_end),

        (gt, ":threat_score", ":maximum_threat_score"),
        		
        (assign, ":most_threatened_center", ":cur_center"),
        (assign, ":maximum_threat_score", ":threat_score"),
        (assign, ":enemy_strength_near_most_threatened_center", ":enemy_strength_nearby"),
      (try_end),
      
      (val_mul, ":maximum_threat_score", 3),
      (val_div, ":maximum_threat_score", 2),

      (assign, reg0, ":most_threatened_center"),
      (assign, reg1, ":maximum_threat_score"),
      (assign, reg2, ":enemy_strength_near_most_threatened_center"),
    ]),
    	
				
	#script_npc_decision_checklist_peace_or_war
	(
	"npc_decision_checklist_peace_or_war", 
	#this script is used to add a bit more color to diplomacy, particularly with regards to the player
	
	[
	(store_script_param, ":actor_faction", 1),
	(store_script_param, ":target_faction", 2),
	(store_script_param, ":envoy", 3),

	(assign, ":actor_strength", 0),
	(assign, ":target_strength", 0),
	(assign, ":actor_centers_held_by_target", 0),

#	(assign, ":two_factions_share_border", 0),
	(assign, ":third_party_war", 0), 
	(assign, ":num_third_party_wars", 0),

	(assign, ":active_mutual_enemy", 0), #an active enemy with which the target is at war
	(assign, "$g_concession_demanded", 0),
	
	(store_relation, ":current_faction_relation", ":actor_faction", ":target_faction"),
	
	(try_begin),
		(eq, ":target_faction", "fac_player_supporters_faction"),
		(assign, ":modified_honor_and_relation", "$player_honor"), #this can be affected by the emissary's skill
		
		(val_add, ":target_strength", 2), #for player party
	(else_try),
		(assign, ":modified_honor_and_relation", 0), #this can be affected by the emissary's skill
	(try_end),
	
	(faction_get_slot, ":actor_leader", ":actor_faction", slot_faction_leader),
	(faction_get_slot, ":target_leader", ":target_faction", slot_faction_leader),

	(call_script, "script_troop_get_relation_with_troop", ":actor_leader", ":target_leader"),

	(assign, ":relation_bonus", reg0),
	(val_min, ":relation_bonus", 10),
	(val_add, ":modified_honor_and_relation", ":relation_bonus"),

	(str_store_troop_name, s15, ":actor_leader"),
	(str_store_troop_name, s16, ":target_leader"),
	

	(assign, ":war_damage_suffered", 0),
	(assign, ":war_damage_inflicted", 0),

	(call_script, "script_diplomacy_faction_get_diplomatic_status_with_faction", ":actor_faction", ":target_faction"),
	(assign, ":war_peace_truce_status", reg0),
	(str_clear, s12),
	(try_begin),
		(eq, ":war_peace_truce_status", -2),
		(str_store_string, s12, "str_s15_is_at_war_with_s16_"),
		
		(store_add, ":war_damage_inflicted_slot", ":target_faction", slot_faction_war_damage_inflicted_on_factions_begin),
		(val_sub, ":war_damage_inflicted_slot", kingdoms_begin),
		(faction_get_slot, ":war_damage_inflicted", ":actor_faction", ":war_damage_inflicted_slot"),

		(store_add, ":war_damage_suffered_slot", ":actor_faction", slot_faction_war_damage_inflicted_on_factions_begin),
		(val_sub, ":war_damage_suffered_slot", kingdoms_begin),
		(faction_get_slot, ":war_damage_suffered", ":target_faction", ":war_damage_suffered_slot"),

		
	(else_try),
		#truce in effect
		(eq, ":war_peace_truce_status", 1),
		(str_store_string, s12, "str_in_the_short_term_s15_has_a_truce_with_s16_as_a_matter_of_general_policy_"),
	(else_try),
		#provocation noted
		(eq, ":war_peace_truce_status", -1),
		(str_store_string, s12, "str_in_the_short_term_s15_was_recently_provoked_by_s16_and_is_under_pressure_to_declare_war_as_a_matter_of_general_policy_"),
	(try_end),

	#clear for dialog with lords
	(try_begin),
		(is_between, "$g_talk_troop", active_npcs_begin, active_npcs_end),
		(str_clear, s12),
	(try_end),
	
	(try_begin),
		(gt, ":envoy", -1),
		(store_skill_level, ":persuasion_x_2", "skl_persuasion", ":envoy"),
		(val_mul, ":persuasion_x_2", 2),
		(val_add, ":modified_honor_and_relation", ":persuasion_x_2"),
		
		(try_begin),
			(eq, "$cheat_mode", 1),
			(assign, reg4, ":modified_honor_and_relation"),
			(display_message, "str_envoymodified_diplomacy_score_honor_plus_relation_plus_envoy_persuasion_=_reg4"),
		(try_end),

	(try_end),
		
	
	(try_for_range, ":kingdom_to_reset", kingdoms_begin, kingdoms_end),
		(faction_set_slot, ":kingdom_to_reset", slot_faction_temp_slot, 0),
	(try_end),
	
	(try_for_parties, ":party_no"),
		(assign, ":party_value", 0),
		(try_begin),
			(is_between, ":party_no", towns_begin, towns_end),
			(assign, ":party_value", 3),
		(else_try),	
			(is_between, ":party_no", castles_begin, castles_end),
			(assign, ":party_value", 2),
		(else_try),
			(is_between, ":party_no", villages_begin, villages_end),
			(assign, ":party_value", 1),
		(else_try),	
			(party_get_template_id, ":template", ":party_no"),
			(eq, ":template", "pt_kingdom_hero_party"),
			(assign, ":party_value", 2),
		(try_end),
		

		(store_faction_of_party, ":party_current_faction", ":party_no"),
		(party_get_slot, ":party_original_faction", ":party_no", slot_center_original_faction),
		(party_get_slot, ":party_ex_faction", ":party_no", slot_center_ex_faction),
		
		
		#total strengths
		(try_begin),
			(is_between, ":party_current_faction", kingdoms_begin, kingdoms_end),
			(faction_get_slot, ":faction_strength", ":party_current_faction", slot_faction_temp_slot),
			(val_add, ":faction_strength", ":party_value"),
			(faction_set_slot, ":party_current_faction", slot_faction_temp_slot, ":faction_strength"),
		(try_end),
		
		
		(try_begin),
			(eq, ":party_current_faction", ":target_faction"),
			(val_add, ":target_strength", ":party_value"),

			(try_begin),
				(this_or_next|eq, ":party_original_faction", ":actor_faction"),
					(eq, ":party_ex_faction", ":actor_faction"),
				(val_add, ":actor_centers_held_by_target", 1),
				(try_begin),
					(is_between, ":party_no", walled_centers_begin, walled_centers_end),
					(assign, "$g_concession_demanded", ":party_no"),
					(str_store_party_name, s18, "$g_concession_demanded"),
				(try_end),
			(try_end),

# Could include two factions share border, but war is unlikely to break out in the first place unless there is a common border
			
#			(try_begin),
#				(is_between, ":party_no", walled_centers_begin, walled_centers_end),
#				(try_for_range, ":other_center", walled_centers_begin, walled_centers_end),
#					(assign, ":two_factions_share_border", 0),
#					(store_faction_of_party, ":other_faction", ":other_center"),
#					(eq, ":other_faction", ":actor_faction"),
#					(store_distance_to_party_from_party, ":distance", ":party_no", ":other_center"),
#					(le, ":distance", 15),
#					(assign, ":two_factions_share_border", 1),
#				(try_end),
#			(try_end),
		(else_try),
			(eq, ":party_current_faction", ":actor_faction"),
			(val_add, ":actor_strength", ":party_value"),
		(try_end),
	(try_end),

	#Total Calradia strength = 110 x 1 (villages,), 48? x 2 castles, 22 x 3 towns, 88 x 2 lord parties = 272 + 176 = 448
	(assign, ":strongest_kingdom", -1),
	(assign, ":score_to_beat", 60), #Maybe raise once it works
	(try_for_range, ":strongest_kingdom_candidate", kingdoms_begin, kingdoms_end),
		(faction_get_slot, ":candidate_strength", ":strongest_kingdom_candidate", slot_faction_temp_slot),
		(gt, ":candidate_strength", ":score_to_beat"),
		(assign, ":strongest_kingdom", ":strongest_kingdom_candidate"),
		(assign, ":score_to_beat", ":candidate_strength"),
	(try_end),
	
	
	(try_begin),
		(eq, "$cheat_mode", 2),
		(gt, ":strongest_kingdom", 1),
		(str_store_faction_name, s4, ":strongest_kingdom"),
		(assign, reg3, ":score_to_beat"),
		(display_message, "@{!}DEBUG - {s4} strongest kingdom with {reg3} strength"),
	(try_end),
	
	
	(assign, ":strength_ratio", 1),
	(try_begin),
		(gt, ":actor_strength", 0),
		(store_mul, ":strength_ratio", ":target_strength", 100),
		(val_div, ":strength_ratio", ":actor_strength"),
	(try_end),
	
	(try_for_range, ":possible_mutual_enemy", kingdoms_begin, kingdoms_end),
		(neq, ":possible_mutual_enemy", ":target_faction"),
		(neq, ":possible_mutual_enemy", ":actor_faction"),
		(faction_slot_eq, ":possible_mutual_enemy", slot_faction_state, sfs_active),
		
		(store_relation, ":relation", ":possible_mutual_enemy", ":actor_faction"),
		(lt, ":relation", 0),
		(assign, ":third_party_war", ":possible_mutual_enemy"),
		(val_add, ":num_third_party_wars", 1),
		
		(store_relation, ":relation", ":possible_mutual_enemy", ":target_faction"),
		(lt, ":relation", 0),
		(assign, ":active_mutual_enemy", ":possible_mutual_enemy"),
	(try_end),
	
	(store_current_hours, ":cur_hours"),
    (faction_get_slot, ":faction_ai_last_decisive_event", ":actor_faction", slot_faction_ai_last_decisive_event),
    (store_sub, ":hours_since_last_decisive_event", ":cur_hours", ":faction_ai_last_decisive_event"),	
	
	(try_begin),
		(gt, "$supported_pretender", 0),
		(this_or_next|eq, "$supported_pretender", ":actor_leader"),
			(eq, "$supported_pretender", ":target_leader"),
		(this_or_next|eq, ":actor_faction", "$supported_pretender_old_faction"),
            (eq, ":target_faction", "$supported_pretender_old_faction"),

		(assign, ":result", -3),		
		(troop_get_type, reg4, ":actor_leader"),	
		(assign, ":explainer_string", "str_s12s15_cannot_negotiate_with_s16_as_to_do_so_would_undermine_reg4herhis_own_claim_to_the_throne_this_civil_war_must_almost_certainly_end_with_the_defeat_of_one_side_or_another"),
	(else_try),
		(lt, ":modified_honor_and_relation", -20),
		(lt, ":strength_ratio", 125),
		(lt, ":war_damage_suffered", 400),
		(this_or_next|neq, ":war_peace_truce_status", -2),
			(lt, ":hours_since_last_decisive_event", 720),
		
		(eq, ":num_third_party_wars", 0),

		(assign, ":result", -3),		
		(troop_get_type, reg4, ":actor_leader"),	
		(assign, ":explainer_string", "str_s12s15_considers_s16_to_be_dangerous_and_untrustworthy_and_shehe_wants_to_bring_s16_down"),
	(else_try),	
		(gt, ":actor_centers_held_by_target", 0),
		(try_begin),
		  (eq, "$cheat_mode", 1),
		  (display_message, "@{!}Actor centers held by target noted"),
		(try_end),
	
		(lt, ":war_damage_suffered", 200),
		(try_begin),
		  (eq, "$cheat_mode", 1),
          (display_message, "@{!}War damage under minimum"),
		(try_end),
		
		(lt, ":strength_ratio", 125),
		(try_begin),
		  (eq, "$cheat_mode", 1),
          (display_message, "@{!}Strength ratio correct"),
		(try_end),
			
		(eq, ":num_third_party_wars", 0),
		(try_begin),
		  (eq, "$cheat_mode", 1),
          (display_message, "@{!}Third party wars"),
		(try_end),
		
		(assign, ":result", -2),
		(assign, ":explainer_string", "str_s12s15_is_anxious_to_reclaim_old_lands_such_as_s18_now_held_by_s16"),
	(else_try),
		(eq, ":war_peace_truce_status", -2),
		(lt, ":strength_ratio", 125),
		(le, ":num_third_party_wars", 1),
		(ge, ":war_damage_inflicted", 5),
		(this_or_next|neq, ":war_peace_truce_status", -2),
			(lt, ":hours_since_last_decisive_event", 720),
		
		(store_mul, ":war_damage_suffered_x_2", ":war_damage_suffered", 2),
		(gt, ":war_damage_inflicted", ":war_damage_suffered_x_2"),

		(assign, ":result", -2),
		(troop_get_type, reg4, ":actor_leader"),
		(assign, ":explainer_string", "str_s12s15_feels_that_reg4shehe_is_winning_the_war_against_s16_and_sees_no_reason_not_to_continue"),
	(else_try),
		(le, ":war_peace_truce_status", -1),
		
		(this_or_next|eq, ":war_peace_truce_status", -1), #either a war is just beginning, or there is a provocation 
			(le, ":war_damage_inflicted", 1),
			
		(lt, ":strength_ratio", 150),
		(eq, ":num_third_party_wars", 0),
		
		(faction_slot_ge, ":actor_faction", slot_faction_instability, 60),

		(assign, ":result", -1),
		(assign, ":explainer_string", "str_s12s15_faces_too_much_internal_discontent_to_feel_comfortable_ignoring_recent_provocations_by_s16s_subjects"),
	(else_try),	
		(eq, ":war_peace_truce_status", -2),
		(lt, ":war_damage_inflicted", 100),
		(eq, ":num_third_party_wars", 1),

		(assign, ":result", -1),
		(troop_get_type, reg4, ":actor_leader"),		
		(assign, ":explainer_string", "str_s12even_though_reg4shehe_is_fighting_on_two_fronts_s15_is_inclined_to_continue_the_war_against_s16_for_a_little_while_longer_for_the_sake_of_honor"),

	(else_try),	
		(eq, ":war_peace_truce_status", -2),
		(lt, ":war_damage_inflicted", 100),
		(eq, ":num_third_party_wars", 0),

		(assign, ":result", -1),
		(troop_get_type, reg4, ":actor_leader"),		
		(assign, ":explainer_string", "str_s12s15_feels_that_reg4shehe_must_pursue_the_war_against_s16_for_a_little_while_longer_for_the_sake_of_honor"),
	(else_try),
		(this_or_next|faction_slot_eq, ":actor_faction", slot_faction_ai_state, sfai_attacking_center),
		(this_or_next|faction_slot_eq, ":actor_faction", slot_faction_ai_state, sfai_raiding_village),
			(faction_slot_eq, ":actor_faction", slot_faction_ai_state, sfai_attacking_enemy_army),
		(faction_get_slot, ":offensive_object", ":actor_faction", slot_faction_ai_object),
		(party_is_active, ":offensive_object"),
		(store_faction_of_party, ":offensive_object_faction", ":offensive_object"),
		(eq, ":offensive_object_faction", ":target_faction"),
		(str_store_party_name, s17, ":offensive_object"),
		
		(assign, ":result", -1),
		(assign, ":explainer_string", "str_s12s15_is_currently_on_the_offensive_against_s17_now_held_by_s16_and_reluctant_to_negotiate"),

		
	(else_try),
		#Attack strongest kingdom, if it is also at war
		(eq, ":strongest_kingdom", ":target_faction"),
		(eq, ":num_third_party_wars", 0),
		
		#Either not at war, or at war for two months
		(this_or_next|ge, ":war_peace_truce_status", -1),
			(lt, ":hours_since_last_decisive_event", 1440),
		
#		(eq, ":two_factions_share_border", 0),

		(assign, ":at_least_one_other_faction_at_war_with_strongest", 0),
		(try_for_range, ":kingdom_to_check", kingdoms_begin, kingdoms_end),
			(neq, ":kingdom_to_check", ":actor_faction"),
			(neq, ":kingdom_to_check", ":target_faction"),
			(faction_slot_eq, ":kingdom_to_check", slot_faction_state, sfs_active),
			(store_relation, ":relation_of_factions", ":kingdom_to_check", ":target_faction"),
			(lt, ":relation_of_factions", 0),
			(assign, ":at_least_one_other_faction_at_war_with_strongest", 1),
		(try_end),
		(eq, ":at_least_one_other_faction_at_war_with_strongest", 1),
		
		
		(assign, ":result", -1),
		(assign, ":explainer_string", "str_s12s15_is_alarmed_by_the_growing_power_of_s16"),
		
	#bid to conquer all Calradia
	(else_try),
		(eq, ":num_third_party_wars", 0),
		(try_begin),
			(ge, "$cheat_mode", 1),
			(display_message, "@{!}DEBUG -- No third party wars for {s15}"),
		(try_end),
		(eq, ":actor_faction", ":strongest_kingdom"),
		#peace with no truce or provocation

		(try_begin),
			(ge, "$cheat_mode", 1),
			(display_message, "@{!}DEBUG -- {s15} is strongest kingdom"),
		(try_end),

		
		(faction_get_slot, ":actor_strength", ":actor_faction", slot_faction_temp_slot),
		(faction_get_slot, ":target_strength", ":target_faction", slot_faction_temp_slot),
		(store_sub, ":strength_difference", ":actor_strength", ":target_strength"),
		(ge, ":strength_difference", 30),

		(try_begin),
			(ge, "$cheat_mode", 1),
			(display_message, "@{!}DEBUG -- {s15} has 30 point advantage over {s16}"),
		(try_end),

		
		(assign, ":nearby_center_found", 0),
		(try_for_range, ":actor_faction_walled_center", walled_centers_begin, walled_centers_end),
			(store_faction_of_party, ":walled_center_faction_1", ":actor_faction_walled_center"),
			(eq, ":walled_center_faction_1", ":actor_faction"), 
			(try_for_range, ":target_faction_walled_center", walled_centers_begin, walled_centers_end),
				(store_faction_of_party, ":walled_center_faction_2", ":target_faction_walled_center"),
				(eq, ":walled_center_faction_2", ":target_faction"),
				(store_distance_to_party_from_party, ":distance", ":target_faction_walled_center", ":actor_faction_walled_center"),
				(lt, ":distance", 25),
				(assign, ":nearby_center_found", 1),
			(try_end),
		(try_end),
		(eq, ":nearby_center_found", 1),
		
		
		(try_begin),
			(ge, "$cheat_mode", 1),
			(display_message, "@{!}DEBUG -- {s15} has proximity to {s16}"),
		(try_end),
		
		(assign, ":result", -1),
		(assign, ":explainer_string", "str_s12s15_declared_war_to_control_calradia"),
		
	(else_try),	
		(lt, ":modified_honor_and_relation", -20),
		
		(assign, ":result", 0),
		(assign, ":explainer_string", "str_s12s15_distrusts_s16_and_fears_that_any_deals_struck_between_the_two_realms_will_not_be_kept"),
		

	#wishes to deal
	(else_try),
		(lt, ":current_faction_relation", 0),
		(ge, ":num_third_party_wars", 2),
		(assign, ":result", 3),
		
		(assign, ":explainer_string", "str_s12s15_is_at_war_on_too_many_fronts_and_eager_to_make_peace_with_s16"),
	(else_try),
		(gt, ":active_mutual_enemy", 0),
		(eq, ":actor_centers_held_by_target", 0),
		(this_or_next|ge, ":current_faction_relation", 0),
#			(eq, ":two_factions_share_border", 0),
			(eq, 1, 1),
			
		(assign, ":result", 3),
		(str_store_faction_name, s17, ":active_mutual_enemy"),
		(troop_get_type, reg4, ":actor_leader"),
		(assign, ":explainer_string", "str_s12s15_seems_to_think_that_s16_and_reg4shehe_have_a_common_enemy_in_the_s17"),
		
	(else_try),
		(eq, ":war_peace_truce_status", -2),
		(ge, ":hours_since_last_decisive_event", 720),
	
		(troop_get_type, reg4, ":actor_leader"),
		
		(assign, ":result", 2),
		(assign, ":explainer_string", "str_s12s15_feels_frustrated_by_reg4herhis_inability_to_strike_a_decisive_blow_against_s16"),
	
		
	(else_try),
		(lt, ":current_faction_relation", 0),
		(gt, ":war_damage_suffered", 100),
		
		(val_mul, ":war_damage_suffered_x_2", 2),
		(lt, ":war_damage_inflicted", ":war_damage_suffered_x_2"),

		(assign, ":result", 2),
		(assign, ":explainer_string", "str_s12s15_has_suffered_enough_in_the_war_with_s16_for_too_little_gain_and_is_ready_to_pursue_a_peace"),
		
	(else_try),	
		(gt, ":third_party_war", 0),
		(ge, ":modified_honor_and_relation", 0),
		(lt, ":current_faction_relation", 0),

		(assign, ":result", 1),
		(str_store_faction_name, s17, ":third_party_war"),
		(assign, ":explainer_string", "str_s12s15_would_like_to_firm_up_a_truce_with_s16_to_respond_to_the_threat_from_the_s17"),
	(else_try),
		(gt, ":third_party_war", 0),
		(ge, ":modified_honor_and_relation", 0),

		(assign, ":result", 1),
		(str_store_faction_name, s17, ":third_party_war"),
		(assign, ":explainer_string", "str_s12s15_wishes_to_be_at_peace_with_s16_so_as_to_pursue_the_war_against_the_s17"),
	(else_try),
		(gt, ":strength_ratio", 175),
#		(eq, ":two_factions_share_border", 1),
		
		(assign, ":result", 1),
		(assign, ":explainer_string", "str_s12s15_seems_to_be_intimidated_by_s16_and_would_like_to_avoid_hostilities"),
	(else_try),
		(lt, ":current_faction_relation", 0),
		
		(assign, ":result", 1),
		(assign, ":explainer_string", "str_s12s15_has_no_particular_reason_to_continue_the_war_with_s16_and_would_probably_make_peace_if_given_the_opportunity"),
	(else_try),
		(assign, ":result", 1),
		(assign, ":explainer_string", "str_s12s15_seems_to_be_willing_to_improve_relations_with_s16"),
	(try_end),

	(str_store_string, s14, ":explainer_string"),
	(assign, reg0, ":result"),
	(assign, reg1, ":explainer_string"),
	
	]),
	
	("npc_decision_checklist_male_guardian_assess_suitor", #parameters from dialog
	[
	(store_script_param, ":lord", 1),
	(store_script_param, ":suitor", 2),
	
	(troop_get_slot, ":lord_reputation", ":lord", slot_lord_reputation_type),
	(store_faction_of_troop, ":lord_faction", ":lord"),
	
	(try_begin),
		(eq, ":suitor", "trp_player"),
		(assign, ":suitor_faction", "$players_kingdom"),
	(else_try),
		(store_faction_of_troop, ":suitor_faction", ":suitor"),
	(try_end),
	(store_relation, ":faction_relation_with_suitor", ":lord_faction", ":suitor_faction"),
	
	(call_script, "script_troop_get_relation_with_troop", ":lord", ":suitor"),
	(assign, ":lord_suitor_relation", reg0),
	


	(troop_get_slot, ":suitor_renown", ":suitor", slot_troop_renown),


	(assign, ":competitor_found", -1),
	
	(try_begin),
		(eq, ":suitor", "trp_player"),	
		(gt, "$marriage_candidate", 0),		
			
		(try_for_range, ":competitor", lords_begin, lords_end),
			(store_faction_of_troop, ":competitor_faction", ":competitor"),
			(eq, ":competitor_faction", ":lord_faction"),
			(this_or_next|troop_slot_eq, ":competitor", slot_troop_love_interest_1, "$marriage_candidate"),
			(this_or_next|troop_slot_eq, ":competitor", slot_troop_love_interest_2, "$marriage_candidate"),
				(troop_slot_eq, ":competitor", slot_troop_love_interest_3, "$marriage_candidate"),
			
			(call_script, "script_troop_get_relation_with_troop", ":competitor", ":lord"),
			(gt, reg0, 5),

			(troop_slot_ge, ":competitor", slot_troop_renown, ":suitor_renown"),  #higher renown than player
			
			(assign, ":competitor_found", ":competitor"),
			(str_store_troop_name, s14, ":competitor"),
			(str_store_troop_name, s16, "$marriage_candidate"),
		(try_end),
	(try_end),
	
	#renown	
	(try_begin),
		(lt, ":suitor_renown", 50),
		(this_or_next|troop_slot_eq, ":lord", slot_lord_reputation_type, lrep_quarrelsome),
		(this_or_next|troop_slot_eq, ":lord", slot_lord_reputation_type, lrep_debauched),
			(troop_slot_eq, ":lord", slot_lord_reputation_type, lrep_selfrighteous),
		(assign, ":explainer_string", "str_excuse_me_how_can_you_possibly_imagine_yourself_worthy_to_marry_into_our_family"),
		(assign, ":result", -3),
	(else_try),	
		(lt, ":suitor_renown", 50),
		(troop_slot_eq, ":lord", slot_lord_reputation_type, lrep_goodnatured),
		
		(assign, ":explainer_string", "str_em_with_regard_to_her_ladyship_we_were_looking_specifically_for_a_groom_of_some_distinction_fight_hard_count_your_dinars_and_perhaps_some_day_in_the_future_we_may_speak_of_such_things_my_good_man"),
		(assign, ":result", -1),
	(else_try),
		(lt, ":suitor_renown", 50),
	
		(assign, ":explainer_string", "str_em_with_regard_to_her_ladyship_we_were_looking_specifically_for_a_groom_of_some_distinction"),
		(assign, ":result", -2),
		
	(else_try),
		(lt, ":suitor_renown", 200),
		(neg|troop_slot_eq, ":lord", slot_lord_reputation_type, lrep_goodnatured),
		(assign, ":explainer_string", "str_it_is_too_early_for_you_to_be_speaking_of_such_things_you_are_still_making_your_mark_in_the_world"),

		(assign, ":result", -1),
		
	(else_try), #wrong faction
		(eq, ":suitor", "trp_player"),
		(neq, ":suitor_faction", "$players_kingdom"),
		(str_store_faction_name, s4, ":lord_faction"),
		(this_or_next|eq, ":lord_reputation", lrep_quarrelsome),
			(eq, ":lord_reputation", lrep_debauched),
		(assign, ":explainer_string", "str_you_dont_serve_the_s4_so_id_say_no_one_day_we_may_be_at_war_and_i_prefer_not_to_have_to_kill_my_inlaws_if_at_all_possible"),

		(assign, ":result", -1),
		
	(else_try),	
		(eq, ":suitor", "trp_player"),
		(neq, ":suitor_faction", "$players_kingdom"),
		(neq, ":lord_reputation", lrep_goodnatured),
		(neq, ":lord_reputation", lrep_cunning),
	
		(assign, ":explainer_string", "str_as_you_are_not_a_vassal_of_the_s4_i_must_decline_your_request_the_twists_of_fate_may_mean_that_we_will_one_day_cross_swords_and_i_would_hope_not_to_make_a_widow_of_a_lady_whom_i_am_obligated_to_protect"),
		
		(assign, ":result", -1),
	(else_try),	
		(eq, ":suitor", "trp_player"),
		(lt, ":faction_relation_with_suitor", 0),

		(assign, ":explainer_string", "str_as_you_are_not_a_vassal_of_the_s4_i_must_decline_your_request_the_twists_of_fate_may_mean_that_we_will_one_day_cross_swords_and_i_would_hope_not_to_make_a_widow_of_a_lady_whom_i_am_obligated_to_protect"),
		
		(assign, ":result", -1),
		
	(else_try),	
		(eq, ":suitor", "trp_player"),
		(neq, "$player_has_homage", 1),
		(neg|faction_slot_eq, "fac_player_supporters_faction", slot_faction_state, sfs_active),
		
		(assign, ":explainer_string", "str_as_you_are_not_a_pledged_vassal_of_our_liege_with_the_right_to_hold_land_i_must_refuse_your_request_to_marry_into_our_family"),
		
		(assign, ":result", -1),
	(else_try),	
		(gt, ":competitor_found", -1),

		(this_or_next|eq, ":lord_reputation", lrep_selfrighteous),
		(this_or_next|eq, ":lord_reputation", lrep_debauched),
		(this_or_next|eq, ":lord_reputation", lrep_martial),
			(eq, ":lord_reputation", lrep_quarrelsome),
		
		(assign, ":explainer_string",	"str_look_here_lad__the_young_s14_has_been_paying_court_to_s16_and_youll_have_to_admit__hes_a_finer_catch_for_her_than_you_so_lets_have_no_more_of_this_talk_shall_we"),
		(assign, ":result", -1),
		
	(else_try),
		(lt, ":lord_suitor_relation", -4),
		

		
		(assign, ":explainer_string", "str_i_do_not_care_for_you_sir_and_i_consider_it_my_duty_to_protect_the_ladies_of_my_household_from_undesirable_suitors"),
		(assign, ":result", -3),
	(else_try),	
		(lt, ":lord_suitor_relation", 5),

		(assign, ":explainer_string",	"str_hmm_young_girls_may_easily_be_led_astray_so_out_of_a_sense_of_duty_to_the_ladies_of_my_household_i_think_i_would_like_to_get_to_know_you_a_bit_better_we_may_speak_of_this_at_a_later_date"),
		(assign, ":result", -1),
	(else_try),	

		(assign, ":explainer_string",	"str_you_may_indeed_make_a_fine_match_for_the_young_mistress"),
		(assign, ":result", 1),
	(try_end),
	
	(assign, reg0, ":result"),
	(assign, reg1, ":explainer_string"),
	
	]),	
	
	("npc_decision_checklist_marry_female_pc", #
	[
	(store_script_param, ":npc", 1),


	(troop_get_slot, ":npc_reputation_type", ":npc", slot_lord_reputation_type),
	
	(call_script, "script_troop_get_romantic_chemistry_with_troop", ":npc", "trp_player"),
	(assign, ":romantic_chemistry", reg0),
	
	(call_script, "script_troop_get_relation_with_troop", ":npc", "trp_player"),
	(assign, ":relation_with_player", reg0),
	
	(assign, ":competitor", -1),
	(try_for_range, ":competitor_candidate", kingdom_ladies_begin, kingdom_ladies_end),
		(this_or_next|troop_slot_eq, ":npc", slot_troop_love_interest_1, ":competitor_candidate"),
		(this_or_next|troop_slot_eq, ":npc", slot_troop_love_interest_2, ":competitor_candidate"),
			(troop_slot_eq, ":npc", slot_troop_love_interest_3, ":competitor_candidate"),
		(call_script, "script_troop_get_relation_with_troop", ":npc", ":competitor"),	
		(assign, ":competitor_relation", reg0),
		
		(gt, ":competitor_relation", ":relation_with_player"),
		(assign, ":competitor", ":competitor_candidate"),
	(try_end),

	(assign, ":player_possessions", 0),
	(try_for_range, ":center", centers_begin, centers_end),
		(troop_slot_eq, ":center", slot_town_lord, "trp_player"),
		(val_add, ":player_possessions", 1),
	(try_end),
	
	(assign, ":lord_agrees", 0),
	#reasons for refusal	
	(try_begin), 
		(troop_slot_ge, "trp_player", slot_troop_betrothed, active_npcs_begin),
		(neg|troop_slot_eq, "trp_player", slot_troop_betrothed, ":npc"),
		
		(str_store_string, s14, "str_my_lady_engaged_to_another"),		
	(else_try),
		#bad relationship - minor
		(lt, ":relation_with_player", -3),
		(this_or_next|eq, ":npc_reputation_type", lrep_upstanding),
		(this_or_next|eq, ":npc_reputation_type", lrep_cunning),
			(eq, ":npc_reputation_type", lrep_goodnatured),
		
		(str_store_string, s14, "str_madame__given_our_relations_in_the_past_this_proposal_is_most_surprising_i_do_not_think_that_you_are_the_kind_of_woman_who_can_be_bent_to_a_hushands_will_and_i_would_prefer_not_to_have_our_married_life_be_a_source_of_constant_acrimony"),
	
	(else_try), #really bad relationship
		(lt, ":relation_with_player", -10),
	
		(this_or_next|eq, ":npc_reputation_type", lrep_quarrelsome),
		(this_or_next|eq, ":npc_reputation_type", lrep_debauched),
			(eq, ":npc_reputation_type", lrep_selfrighteous),

		(str_store_string, s14, "str_i_would_prefer_to_marry_a_proper_maiden_who_will_obey_her_husband_and_is_not_likely_to_split_his_head_with_a_sword"),
	(else_try),
		(lt, ":romantic_chemistry", 5),

		(str_store_string, s14, "str_my_lady_not_sufficient_chemistry"),
		
	(else_try), #would prefer someone more ladylike
		(this_or_next|eq, ":npc_reputation_type", lrep_upstanding),
			(eq, ":npc_reputation_type", lrep_martial),
		
		(str_store_string, s14, "str_my_lady_while_i_admire_your_valor_you_will_forgive_me_if_i_tell_you_that_a_woman_like_you_does_not_uphold_to_my_ideal_of_the_feminine_of_the_delicate_and_of_the_pure"),
	(else_try),
		(eq, ":npc_reputation_type", lrep_quarrelsome),
		(lt, ":romantic_chemistry", 15),		
		
		(str_store_string, s14, "str_nah_i_want_a_woman_wholl_keep_quiet_and_do_what_shes_told_i_dont_think_thats_you"),
	(else_try), #no properties
		(this_or_next|eq, ":npc_reputation_type", lrep_selfrighteous),
			(eq, ":npc_reputation_type", lrep_debauched),
	
		(ge, ":romantic_chemistry", 10),		
		(eq, ":player_possessions", 0),
		
		(str_store_string, s14, "str_my_lady_you_are_possessed_of_great_charms_but_no_properties_until_you_obtain_some_to_marry_you_would_be_an_act_of_ingratitude_towards_my_ancestors_and_my_lineage"),
		
	(else_try), #you're a nobody - I can do better
		(this_or_next|eq, ":npc_reputation_type", lrep_selfrighteous),
			(eq, ":npc_reputation_type", lrep_debauched),
	
		(eq, ":player_possessions", 0),
		
		(str_store_string, s14, "str_my_lady_you_are_a_woman_of_no_known_family_of_no_possessions__in_short_a_nobody_do_you_think_that_you_are_fit_to_marry_into_may_family"),
	(else_try), #just not that into you
		(lt, ":romantic_chemistry", 5),
		(lt, ":relation_with_player", 20),
		
		(neq, ":npc_reputation_type", lrep_debauched),
		(neq, ":npc_reputation_type", lrep_selfrighteous),
		
		(str_store_string, s14, "str_my_lady__forgive_me__the_quality_of_our_bond_is_not_of_the_sort_which_the_poets_tell_us_is_necessary_to_sustain_a_happy_marriage"),
		
	(else_try), #you're a liability, given your relation with the liege
		(eq, ":npc_reputation_type", lrep_cunning),
		(faction_get_slot, ":leader", slot_faction_leader, "$g_talk_troop_faction"),
		(str_store_troop_name, s4, ":leader"),
		(call_script, "script_troop_get_relation_with_troop", ":leader", "trp_player"),
		(lt, reg0, -10),
		
		(str_store_string, s14, "str_um_i_think_that_if_i_want_to_stay_on_s4s_good_side_id_best_not_marry_you"),
	(else_try),	#part of another faction
		(gt, "$players_kingdom", 0),
		(neq, "$players_kingdom", "$g_talk_troop_faction"),
		(faction_get_slot, ":leader", slot_faction_leader, "$g_talk_troop_faction"),
		(troop_get_type, reg4, ":leader"),
		
		(str_store_string, s14, "str_you_serve_another_realm_i_dont_see_s4_granting_reg4herhis_blessing_to_our_union"),
	(else_try), #there's a competitor
		(gt, ":competitor", -1),
		(str_store_troop_name, s4, ":competitor"),
		
		(str_store_string, s14, "str_madame_my_heart_currently_belongs_to_s4"),

	(else_try),
		(lt, ":relation_with_player", 10),
		(assign, ":lord_agrees", 2),
	
		(str_store_string, s14, "str_my_lady_you_are_a_woman_of_great_spirit_and_bravery_possessed_of_beauty_grace_and_wit_i_shall_give_your_proposal_consideration"),
	(else_try),
		(assign, ":lord_agrees", 1),
	
		(str_store_string, s14, "str_my_lady_you_are_a_woman_of_great_spirit_and_bravery_possessed_of_beauty_grace_and_wit_i_would_be_most_honored_were_you_to_become_my_wife"),		
	(try_end),

	
	(assign, reg0, ":lord_agrees"),
	
	]
	),

	
#	(
#	"npc_decision_checklist_king_chooses_lord_for_center", 
#	[
#	(store_script_param, ":center", 1),
	
#	(store_faction_of_party, ":faction", ":center"),
#	(faction_get_slot, ":king", ":faction", slot_faction_leader),
	
#	(assign, ":total_renown_in_faction"),
#	(try_for_range, ":lord_iterator", active_npcs_including_player_begin, active_npcs_end), 
#		(assign, ":lord", ":lord_iterator"),
#		(store_faction_of_troop, ":lord_faction", ":lord"),
#		(try_begin),	
#			(eq, ":lord_iterator", "trp_kingdom_heroes_including_player_begin"),
#			(assign, ":lord", "trp_player"),
#			(assign, ":lord_faction", "$players_kingdom"),
#		(try_end),
#		(troop_get_slot, ":renown", ":lord", slot_troop_renown),
#		(val_add, ":total_renown_in_faction", ":renown"),
		
#		(troop_set_slot, ":lord", slot_troop_temp_slot, 0),
#	(try_end),
	
#	(assign, ":total_property_points_in_faction"),
#	(try_for_range, ":village", villages_begin, villages_end),
	
#	(try_end),
	
	
	
#	(try_begin),
	
	#I needed it for myself
	
	#The one who captured it was suitably deserving 
		
	#I had not sufficiently recognized Lord X for his service
	
#	(try_end),
	
	
#	]),
	
	
	
	("courtship_poem_reactions", #parameters from dialog
	[
	(store_script_param, ":lady", 1),
	(store_script_param, ":poem", 2),	
	
	(troop_get_slot, ":lady_reputation", ":lady", slot_lord_reputation_type),

	(try_begin),
		(eq, "$cheat_mode", 1),
		(assign, reg4, ":poem"),
		(assign, reg5, ":lady_reputation"),
		(display_message, "str_poem_choice_reg4_lady_rep_reg5"),
	(try_end),
	
	(try_begin), #conventional ++, ambitious -, adventurous -
		(eq, ":poem", courtship_poem_tragic),
		(eq, ":lady_reputation", lrep_conventional),
		(str_store_string, s11, "str_ah__kais_and_layali__such_a_sad_tale_many_a_time_has_it_been_recounted_for_my_family_by_the_wandering_poets_who_come_to_our_home_and_it_has_never_failed_to_bring_tears_to_our_eyes"),
		(assign, ":result", 5),
	(else_try),
		(eq, ":poem", courtship_poem_tragic),
		(eq, ":lady_reputation", lrep_ambitious),
		(str_store_string, s11, "str_kais_and_layali_three_hundred_stanzas_of_pathetic_sniveling_if_you_ask_me_if_kais_wanted_to_escape_heartbreak_he_should_have_learned_to_live_within_his_station_and_not_yearn_for_what_he_cannot_have"),
		(assign, ":result", 0),
	(else_try),
		(eq, ":poem", courtship_poem_tragic),
		(eq, ":lady_reputation", lrep_otherworldly),
		(str_store_string, s11, "str_kais_and_layali_no_one_should_ever_have_written_such_a_sad_poem_if_it_was_the_destiny_of_kais_and_layali_to_be_together_than_their_love_should_have_conquered_all_obstacles"),
		(assign, ":result", 1),
	(else_try),
		(eq, ":poem", courtship_poem_tragic),
#		moralizing and adventurous
		(str_store_string, s11, "str_ah_kais_and_layali_a_very_old_standby_but_moving_in_its_way"),
		(assign, ":result", 3),
	#Heroic	
	(else_try), #adventurous ++, conventional -1, moralizing -1
		(eq, ":poem", courtship_poem_heroic),
		(eq, ":lady_reputation", lrep_adventurous),
		(str_store_string, s11, "str_the_saga_of_helgered_and_kara_such_happy_times_in_which_our_ancestors_lived_women_like_kara_could_venture_out_into_the_world_like_men_win_a_name_for_themselves_and_not_linger_in_their_husbands_shadow"),
		(assign, ":result", 5),
	(else_try), #adventurous ++, conventional -1, moralizing -1
		(eq, ":poem", courtship_poem_heroic),
		(eq, ":lady_reputation", lrep_ambitious),
		(str_store_string, s11, "str_ah_the_saga_of_helgered_and_kara_now_there_was_a_lady_who_knew_what_she_wanted_and_was_not_afraid_to_obtain_it"),
		(assign, ":result", 2),
	(else_try), #adventurous ++, conventional -1, moralizing -1
		(eq, ":poem", courtship_poem_heroic),
		(eq, ":lady_reputation", lrep_otherworldly),
		(str_store_string, s11, "str_the_saga_of_helgered_and_kara_a_terrible_tale__but_it_speaks_of_a_very_great_love_if_she_were_willing_to_make_war_on_her_own_family"),
		(assign, ":result", 2),
	(else_try), #adventurous ++, conventional -1, moralizing -1
		(eq, ":poem", courtship_poem_heroic),
		(eq, ":lady_reputation", lrep_moralist),
		(str_store_string, s11, "str_the_saga_of_helgered_and_kara_as_i_recall_kara_valued_her_own_base_passions_over_duty_to_her_family_that_she_made_war_on_her_own_father_i_have_no_time_for_a_poem_which_praises_such_a_woman"),
		(assign, ":result", 0),
	(else_try), #adventurous ++, conventional -1, moralizing -1
		(eq, ":poem", courtship_poem_heroic),
		(eq, ":lady_reputation", lrep_conventional),
		(str_store_string, s11, "str_the_saga_of_helgered_and_kara_how_could_a_woman_don_armor_and_carry_a_sword_how_could_a_man_love_so_ungentle_a_creature"),
		(assign, ":result", 0),
	#Comic
	(else_try), #ambitious ++, romantic -, moralizing 0
		(eq, ":poem", courtship_poem_comic),
		(eq, ":lady_reputation", lrep_otherworldly),
		(str_store_string, s11, "str_a_conversation_in_the_garden_i_cannot_understand_the_lady_in_that_poem_if_she_loves_the_man_why_does_she_tease_him_so"),
		(assign, ":result", 0),
	(else_try), #ambitious ++, romantic -, moralizing 0
		(eq, ":poem", courtship_poem_comic),
		(eq, ":lady_reputation", lrep_moralist),
		(str_store_string, s11, "str_a_conversation_in_the_garden_let_us_see__it_is_morally_unedifying_it_exalts_deception_it_ends_with_a_maiden_surrendering_to_her_base_passions_and_yet_i_cannot_help_but_find_it_charming_perhaps_because_it_tells_us_that_love_need_not_be_tragic_to_be_memorable"),
		(assign, ":result", 1),
	(else_try), #ambitious ++, romantic -, moralizing 0
		(eq, ":poem", courtship_poem_comic),
		(eq, ":lady_reputation", lrep_ambitious),
		(str_store_string, s11, "str_a_conversation_in_the_garden_now_that_is_a_tale_every_lady_should_know_by_heart_to_learn_the_subtleties_of_the_politics_she_must_practice"),
		(assign, ":result", 5),
	(else_try), #ambitious ++, romantic -, moralizing 0
		(eq, ":poem", courtship_poem_comic),
		#adventurous, conventional 
		(str_store_string, s11, "str_a_conversation_in_the_garden_it_is_droll_i_suppose__although_there_is_nothing_there_that_truly_stirs_my_soul"),
		(assign, ":result", 3),

	#Allegoric	
	(else_try), #moralizing ++, adventurous -, romantic -
		(eq, ":poem", courtship_poem_allegoric),
		(eq, ":lady_reputation", lrep_adventurous),
		(str_store_string, s11, "str_storming_the_fortress_of_love_ah_yes_the_lady_sits_within_doing_nothing_while_the_man_is_the_one_who_strives_and_achieves_i_have_enough_of_that_in_my_daily_life_why_listen_to_poems_about_it"),
		(assign, ":result", 0),
	(else_try), #moralizing ++, adventurous -, romantic -
		(eq, ":poem", courtship_poem_allegoric),
		(this_or_next|eq, ":lady_reputation", lrep_conventional),
			(eq, ":lady_reputation", lrep_moralist),
		(str_store_string, s11, "str_storming_the_fortress_of_love_ah_yes_an_uplifting_tribute_to_the_separate_virtues_of_man_and_woman"),
		(assign, ":result", 3),
	(else_try), #moralizing ++, adventurous -, romantic -
		(eq, ":poem", courtship_poem_allegoric),
		(eq, ":lady_reputation", lrep_otherworldly),
		(str_store_string, s11, "str_storming_the_fortress_of_love_ah_yes_but_although_it_is_a_fine_tale_of_virtues_it_speaks_nothing_of_passion"),
		(assign, ":result", 1),
	(else_try), #moralizing ++, adventurous -, romantic -
		(eq, ":poem", courtship_poem_allegoric),
		(eq, ":lady_reputation", lrep_ambitious),
		(str_store_string, s11, "str_storming_the_fortress_of_love_ah_a_sermon_dressed_up_as_a_love_poem_if_you_ask_me"),
		(assign, ":result", 1),

	(else_try), #romantic ++, moralizing 0, ambitious -
		(eq, ":poem", courtship_poem_mystic),
		(eq, ":lady_reputation", lrep_otherworldly),
		(str_store_string, s11, "str_a_hearts_desire_ah_such_a_beautiful_account_of_the_perfect_perfect_love_to_love_like_that_must_be_to_truly_know_rapture"),
		(assign, ":result", 4),		

	(else_try), #romantic ++, moralizing 0, ambitious -
		(eq, ":poem", courtship_poem_mystic),
		(eq, ":lady_reputation", lrep_ambitious),
		(str_store_string, s11, "str_a_hearts_desire_silly_if_you_ask_me_if_the_poet_desires_a_lady_then_he_should_endeavor_to_win_her__and_not_dress_up_his_desire_with_a_pretense_of_piety"),
		(assign, ":result", 0),		

	(else_try), #romantic ++, moralizing 0, ambitious -
		(eq, ":poem", courtship_poem_mystic),
		(eq, ":lady_reputation", lrep_moralist),
		(str_store_string, s11, "str_a_hearts_desire_hmm__it_is_an_interesting_exploration_of_earthly_and_divine_love_it_does_speak_of_the_spiritual_quest_which_brings_out_the_best_in_man_but_i_wonder_if_the_poet_has_not_confused_his_yearning_for_higher_things_with_his_baser_passions"),
		(assign, ":result", 2),		

	(else_try), #romantic ++, moralizing 0, ambitious -
		(eq, ":poem", courtship_poem_mystic),
		(str_store_string, s11, "str_a_hearts_desire_oh_yes__it_is_very_worthy_and_philosophical_but_if_i_am_to_listen_to_a_bard_strum_a_lute_for_three_hours_i_personally_prefer_there_to_be_a_bit_of_a_story"),
		(assign, ":result", 1),		
	(try_end),

	
	(try_begin),
		(eq, "$cheat_mode", 1),
		(assign, reg4, ":result"),
		(display_message, "str_result_reg4_string_s11"),
	(try_end),	
	
	
	(assign, reg0, ":result"),
	
	]),

	(
	"diplomacy_faction_get_diplomatic_status_with_faction", 
	#result: -1 faction_1 has a casus belli against faction_2. 1, faction_1 has a truce with faction_2, -2, the two factions are at war
	[
	(store_script_param, ":actor_faction", 1),
	(store_script_param, ":target_faction", 2),

	(store_add, ":truce_slot", ":target_faction", slot_faction_truce_days_with_factions_begin),
	(store_add, ":provocation_slot", ":target_faction", slot_faction_provocation_days_with_factions_begin),
	(val_sub, ":truce_slot", kingdoms_begin),
	(val_sub, ":provocation_slot", kingdoms_begin),
	
	(assign, ":result", 0),
	(assign, ":duration", 0),
	
	(try_begin),
		(store_relation, ":relation", ":actor_faction", ":target_faction"),
		(lt, ":relation", 0),
		(assign, ":result", -2),
	(else_try),
		(faction_slot_ge, ":actor_faction", ":truce_slot", 1),
		(assign, ":result", 1),

		(faction_get_slot, ":duration", ":actor_faction", ":truce_slot"),
	(else_try),
		(faction_slot_ge, ":actor_faction", ":provocation_slot", 1),
		(assign, ":result", -1),
		
		(faction_get_slot, ":duration", ":actor_faction", ":provocation_slot"),
	(try_end),
	
	(assign, reg0, ":result"),
	(assign, reg1, ":duration"),
	]),
	
	("faction_follows_controversial_policy",
	[
	(store_script_param, ":faction_no", 1),
	(store_script_param, ":policy_type", 2),
	
	(faction_get_slot, ":faction_leader", ":faction_no", slot_faction_leader),

	(try_begin),
		(ge, "$cheat_mode", 1),
		(str_store_faction_name, s3, ":faction_no"),
		(display_message, "str_calculating_effect_for_policy_for_s3"),
		
		(val_add, "$number_of_controversial_policy_decisions", 1),
	(try_end),
	
	(try_begin),
		(eq, ":policy_type", logent_policy_ruler_attacks_without_provocation),
		(assign, ":hawk_relation_effect", 0),
		(assign, ":honorable_relation_effect", -2),
		(assign, ":honor_change", -1),
		
	(else_try),
		(eq, ":policy_type", logent_policy_ruler_ignores_provocation),
		(assign, ":hawk_relation_effect", -3),
		(assign, ":honorable_relation_effect", 0),
		(assign, ":honor_change", 0),
	
	(else_try),
		(eq, ":policy_type", logent_policy_ruler_declares_war_with_justification),
		(assign, ":hawk_relation_effect", 3),
		(assign, ":honorable_relation_effect", 1),
		(assign, ":honor_change", 0),

	(else_try),
		(eq, ":policy_type", logent_policy_ruler_breaks_truce),
		(assign, ":hawk_relation_effect", 0),
		(assign, ":honorable_relation_effect", -3),
		(assign, ":honor_change", -5),

	(else_try),
		(eq, ":policy_type", logent_policy_ruler_makes_peace_too_soon),
		(assign, ":hawk_relation_effect", -5),
		(assign, ":honorable_relation_effect", 0),
		(assign, ":honor_change", 0),
		
	(try_end),
	
	(try_begin),
		(eq, ":faction_leader", "trp_player"),
		(call_script, "script_change_player_honor", ":honor_change"),
	(try_end),	
	
	(try_for_range, ":lord", active_npcs_begin, active_npcs_end),
		(troop_slot_eq, ":lord", slot_troop_occupation, slto_kingdom_hero),
		(store_faction_of_troop, ":lord_faction", ":lord"),
		(eq, ":lord_faction", ":faction_no"),
		(neq, ":lord", ":faction_leader"),
		
		(try_begin),
			(this_or_next|troop_slot_eq, ":lord", slot_lord_reputation_type, lrep_martial),
			(this_or_next|troop_slot_eq, ":lord", slot_lord_reputation_type, lrep_quarrelsome),
			(this_or_next|troop_slot_eq, ":lord", slot_lord_reputation_type, lrep_selfrighteous),
				(troop_slot_eq, ":lord", slot_lord_reputation_type, lrep_debauched),
			(call_script, "script_troop_change_relation_with_troop", ":faction_leader", ":lord", ":hawk_relation_effect"),
			(val_add, "$total_policy_dispute_changes", ":hawk_relation_effect"),
		(try_end),
		
		(try_begin),
			(this_or_next|troop_slot_eq, ":lord", slot_lord_reputation_type, lrep_martial),
			(this_or_next|troop_slot_eq, ":lord", slot_lord_reputation_type, lrep_goodnatured),
			(this_or_next|troop_slot_eq, ":lord", slot_lord_reputation_type, lrep_selfrighteous),
			(this_or_next|troop_slot_eq, ":lord", slot_lord_reputation_type, lrep_benefactor), #new for enfiefed commoners
			(this_or_next|troop_slot_eq, ":lord", slot_lord_reputation_type, lrep_custodian), #new for enfiefed commoners
				(troop_slot_eq, ":lord", slot_lord_reputation_type, lrep_upstanding),
			(call_script, "script_troop_change_relation_with_troop", ":faction_leader", ":lord", ":honorable_relation_effect"),
			(val_add, "$total_policy_dispute_changes", ":honorable_relation_effect"),
			
		(try_end),

	(try_end),
	
	]),
	
	
	("internal_politics_rate_feast_to_s9",
	[
	(store_script_param, ":householder", 1),
	(store_script_param, ":num_servings", 2),	
#	(store_script_param, ":faction", 3),	
	(store_script_param, ":consume_items", 4),	

	(val_max, ":num_servings", 1),
	
	(try_for_range, ":item", trade_goods_begin, trade_goods_end), 
		(item_set_slot, ":item", slot_item_amount_available, 0), #had no "item"
	(try_end),
	
	(troop_get_inventory_capacity, ":capacity", ":householder"),
	(try_for_range, ":inventory_slot", 0, ":capacity"),
		(troop_get_inventory_slot, ":item", ":householder", ":inventory_slot"),
		(is_between, ":item", trade_goods_begin, trade_goods_end),
	    (troop_inventory_slot_get_item_amount, ":slot_amount", ":householder", ":inventory_slot"),
		(item_get_slot, ":item_amount", ":item", slot_item_amount_available),
		(val_add, ":item_amount", ":slot_amount"),
		(item_set_slot, ":item", slot_item_amount_available, ":item_amount"),
	(try_end),
	#food
	(assign, ":food_amount", 0),
	(assign, ":food_variety", 0),
	
	(store_div, ":servings_div_by_12", ":num_servings", 12),
	(try_for_range, ":food_item", food_begin, food_end),
		(item_get_slot, ":food_in_slot", ":food_item", slot_item_amount_available),
		(val_add, ":food_amount", ":food_in_slot"),


##		(str_store_item_name, s4, ":food_item"),
##		(assign, reg3, ":food_in_slot"),
##		(assign, reg5, ":servings_div_by_12"),
##		(display_message, "str_reg3_units_of_s4_for_reg5_guests_and_retinue"),

		
		(ge, ":food_in_slot", ":servings_div_by_12"),
		(val_add, ":food_variety", 1),
	(try_end),
	
	(val_mul, ":food_amount", 100),
	(val_div, ":food_amount", ":num_servings"), #1 to 100 for each
	(val_min, ":food_amount", 100),
	
	(val_mul, ":food_variety", 85), #1 to 100 for each
	(val_div, ":food_variety", 10), 
	(val_min, ":food_variety", 100),
	
	#drink
	(assign, ":drink_amount", 0),
	(assign, ":drink_variety", 0),
	(store_div, ":servings_div_by_4", ":num_servings", 4),
	(try_for_range, ":drink_iterator", "itm_wine", "itm_smoked_fish"),
		(assign, ":drink_item", ":drink_iterator"),
		(item_get_slot, ":drink_in_slot", ":drink_item", slot_item_amount_available),
		
		(val_add, ":drink_amount", ":drink_in_slot"),
	
		(ge, ":drink_in_slot", ":servings_div_by_4"),
		(val_add, ":drink_variety", 1),
	(try_end),
	
	(val_mul, ":drink_amount", 200), #amount needed is 50% of the number of guests
	(val_max, ":num_servings", 1),
	
	(val_div, ":drink_amount", ":num_servings"), #1 to 100 for each
	(val_min, ":drink_amount", 100),
	(val_mul, ":drink_variety", 50), #1 to 100 for each

	#in the future, it might be worthwhile to add different varieties of spices
	(item_get_slot, ":spice_amount", "itm_spice", slot_item_amount_available),
	(store_mul, ":spice_percentage", ":spice_amount", 100),
	(val_max, ":servings_div_by_12", 1),
	(val_div, ":spice_amount", ":servings_div_by_12"),
	(val_min, ":spice_percentage", 100),
##	(assign, reg3, ":spice_amount"),
##	(assign, reg5, ":servings_div_by_12"),
##	(assign, reg6, ":spice_percentage"),
##	(display_message, "str_reg3_units_of_spice_of_reg5_to_be_consumed"),
	
	#oil availability. In the future, this may become an "atmospherics" category, including incenses
	(item_get_slot, ":oil_amount", "itm_oil", slot_item_amount_available),
	(store_mul, ":oil_percentage", ":oil_amount", 100),
	(val_max, ":servings_div_by_12", 1),
	(val_div, ":oil_amount", ":servings_div_by_12"),
	(val_min, ":oil_percentage", 100),
##	(assign, reg3, ":oil_amount"),
##	(assign, reg5, ":servings_div_by_12"),
##	(assign, reg6, ":oil_percentage"),
##	(display_message, "str_reg3_units_of_oil_of_reg5_to_be_consumed"),

	(store_div, ":food_amount_string", ":food_amount", 20),
	(val_add, ":food_amount_string", "str_feast_description"),
	(str_store_string, s8, ":food_amount_string"),
	(str_store_string, s9, "str_of_food_which_must_come_before_everything_else_the_amount_is_s8"),
	
	(store_div, ":food_variety_string", ":food_variety", 20),
	(val_add, ":food_variety_string", "str_feast_description"),
	(str_store_string, s8, ":food_variety_string"),
	(str_store_string, s9, "str_s9_and_the_variety_is_s8_"),

	(store_div, ":drink_amount_string", ":drink_amount", 20),
	(val_add, ":drink_amount_string", "str_feast_description"),
	(str_store_string, s8, ":drink_amount_string"),
	(str_store_string, s9, "str_s9_of_drink_which_guests_will_expect_in_great_abundance_the_amount_is_s8"),
	
	(store_div, ":drink_variety_string", ":drink_variety", 20),
	(val_add, ":drink_variety_string", "str_feast_description"),
	(str_store_string, s8, ":drink_variety_string"),
	(str_store_string, s9, "str_s9_and_the_variety_is_s8_"),
	
	(store_div, ":spice_string", ":spice_percentage", 20),
	(val_add, ":spice_string", "str_feast_description"),
	(str_store_string, s8, ":spice_string"),
	(str_store_string, s9, "str_s9_of_spice_which_is_essential_to_demonstrate_that_we_spare_no_expense_as_hosts_the_amount_is_s8_"),
	
	(store_div, ":oil_string", ":oil_percentage", 20),
	(val_add, ":oil_string", "str_feast_description"),
	(str_store_string, s8, ":oil_string"),
	(str_store_string, s9, "str_s9_of_oil_which_we_shall_require_to_light_the_lamps_the_amount_is_s8"),
	
	(store_mul, ":food_amount_cap", ":food_amount", 8),
	(store_add, ":total", ":food_amount", ":food_variety"),
	(val_mul, ":total", 2), #x4
	(val_add, ":total", ":drink_variety"),
	(val_add, ":total", ":drink_amount"), #x6
	(val_add, ":total", ":spice_amount"), #x7
	(val_add, ":total", ":oil_amount"), #x8
	(val_min, ":total", ":food_amount_cap"),
	(val_div, ":total", 8),
	(val_clamp, ":total", 1, 101),
	(store_div, ":total_string", ":total", 20),
	(val_add, ":total_string", "str_feast_description"),
	(str_store_string, s8, ":total_string"),
	(str_store_string, s9, "str_s9_overall_our_table_will_be_considered_s8"),
	
	(assign, reg0, ":total"), #zero to 100
	
	
	
	(try_begin),
		(eq, ":consume_items", 1),
		
		(assign, ":num_of_servings_to_serve", ":num_servings"),
		(try_for_range, ":unused", 0, 1999),
			(gt, ":num_of_servings_to_serve", 0),
			
			(try_for_range, ":item", trade_goods_begin, trade_goods_end),
				(item_set_slot, ":item", slot_item_is_checked, 0),
			(try_end),
			
			(troop_get_inventory_capacity, ":inv_size", ":householder"),
			(try_for_range, ":i_slot", 0, ":inv_size"),
				(troop_get_inventory_slot, ":item", ":householder", ":i_slot"),
				(this_or_next|eq, ":item", "itm_spice"),
				(this_or_next|eq, ":item", "itm_oil"),
				(this_or_next|eq, ":item", "itm_wine"),
				(this_or_next|eq, ":item", "itm_ale"),
					(is_between, ":item",  food_begin, food_end),
				(item_slot_eq, ":item", slot_item_is_checked, 0),
				(troop_inventory_slot_get_item_amount, ":cur_amount", ":householder", ":i_slot"),
				(gt, ":cur_amount", 0),
				
				(val_sub, ":cur_amount", 1),
				(troop_inventory_slot_set_item_amount, ":householder", ":i_slot", ":cur_amount"),
				(val_sub, ":num_of_servings_to_serve", 1),
				(item_set_slot, ":item", slot_item_is_checked, 1),
			(try_end),
		(try_begin),
	(try_end),
	]),

	
	("faction_get_adjective_to_s10", 
	[
	(store_script_param, ":faction_no", 1),

	(try_begin),
		(eq, ":faction_no", "fac_player_faction"),
		(assign, ":faction_no", "$players_kingdom"),
	(try_end),
	
	
	(try_begin),
		(eq, ":faction_no", "fac_player_supporters_faction"),
		(str_store_string, s10, "str_rebel"),
	(else_try),	
		(this_or_next|eq, ":faction_no", "fac_outlaws"),
		(this_or_next|eq, ":faction_no", "fac_mountain_bandits"),
		(this_or_next|eq, ":faction_no", "fac_forest_bandits"),
			(eq, ":faction_no", "fac_deserters"),
		(str_store_string, s10, "str_bandit"),	
	(else_try),
		(faction_get_slot, ":adjective_string", ":faction_no", slot_faction_adjective),
		(str_store_string, s10, ":adjective_string"),
	(try_end),			
	]),
	
	("setup_tavern_attacker", 
	[
	  (store_script_param, ":cur_entry", 1),
	  	  
	  (try_begin),
	    (neg|troop_slot_eq, "trp_hired_assassin", slot_troop_cur_center, "$g_encountered_party"),
	    (troop_slot_eq, "trp_belligerent_drunk", slot_troop_cur_center, "$g_encountered_party"),
	    (set_visitor, ":cur_entry", "trp_belligerent_drunk"),
	  (try_end),
	  
	  (try_begin),
	    (troop_slot_eq, "trp_hired_assassin", slot_troop_cur_center, "$g_encountered_party"),
	    (set_visitor, ":cur_entry", "trp_hired_assassin"),
	  (try_end),
	]),
		
	("activate_tavern_attackers", 
	[
	  (set_party_battle_mode),
	  (try_for_agents, ":cur_agent"),
	    (agent_get_troop_id, ":cur_agent_troop", ":cur_agent"),
	    (this_or_next|eq, ":cur_agent_troop", "trp_fugitive"),
	    (this_or_next|eq, ":cur_agent_troop", "trp_belligerent_drunk"),
	    (eq, ":cur_agent_troop", "trp_hired_assassin"),
	    (agent_set_team, ":cur_agent", 1),
	    (assign, "$g_main_attacker_agent", ":cur_agent"),
	    (agent_ai_set_aggressiveness, ":cur_agent", 199),
	  (try_end),
	]),
	
	("deactivate_tavern_attackers", 
	[
	  (finish_party_battle_mode),
	  (try_for_agents, ":cur_agent"),
	    (agent_get_troop_id, ":cur_agent_troop", ":cur_agent"),
	    (this_or_next|eq, ":cur_agent_troop", "trp_fugitive"),
	    (this_or_next|eq, ":cur_agent_troop", "trp_belligerent_drunk"),
	    (eq, ":cur_agent_troop", "trp_hired_assassin"),
	    (agent_set_team, ":cur_agent", 0),
	    (agent_ai_set_aggressiveness, ":cur_agent", 0),
	  (try_end),
	]),
	
	("activate_town_guard", 
	[
	  (set_party_battle_mode),
	  #(get_player_agent_no, ":player_agent"),
	  #(agent_get_team, ":player_team", ":player_agent"),
	  
	  (try_for_agents, ":cur_agent"), 
	    (agent_get_troop_id, ":troop_type", ":cur_agent"),
	    (is_between, ":troop_type", "trp_swadian_recruit", "trp_looter"),
        (agent_set_team, ":cur_agent", 1),
        #(team_give_order, 1, grc_everyone, mordr_charge), - for some reason, this freezes everyone if the player is not yet spawned
		#(try_begin),
		#	(eq, "$g_main_attacker_agent", 0),
		#	(assign, "$g_main_attacker_agent", ":cur_agent"),
		#(try_end),
	(else_try),	
		(this_or_next|is_between, ":cur_agent", walkers_begin, walkers_end),
		(is_between, ":cur_agent", armor_merchants_begin, mayors_end),
		
		(agent_clear_scripted_mode, ":cur_agent"),
		(agent_set_team, ":cur_agent", 2),
	(try_end),
	]),


	#this determines whether or not a lord is thrown into a dungeon by his captor, or is kept out on parole
	#Not currently used (ie, it always fails)
	("cf_prisoner_offered_parole", 
	[
	  (store_script_param, ":prisoner", 1),
	  
	  (eq, 1, 0), #disabled, this will always return false
	  
	  (troop_get_slot, ":captor_party", ":prisoner", slot_troop_prisoner_of_party),
	  (party_is_active, ":captor_party"),
	  (is_between, ":captor_party", walled_centers_begin, walled_centers_end),
	  (party_get_slot, ":captor", ":captor_party", slot_town_lord),
	  
	  (troop_get_slot, ":prisoner_rep", ":prisoner", slot_lord_reputation_type),
	  (troop_get_slot, ":captor_rep", ":captor", slot_lord_reputation_type),
	  
	  (neq, ":prisoner_rep", lrep_debauched),
	  (neq, ":captor_rep", lrep_debauched),
	  (neq, ":captor_rep", lrep_quarrelsome),
	
     #Prisoner is a noble, or lord is goodnatured
    (this_or_next|eq, ":captor_rep", lrep_goodnatured),
    (this_or_next|troop_slot_eq, ":prisoner", slot_troop_occupation, slto_kingdom_hero),
    (troop_slot_eq, ":prisoner", slot_troop_occupation, slto_kingdom_lady),
	
	(call_script, "script_troop_get_relation_with_troop", ":captor", ":prisoner"),
##	(display_message, "str_relation_of_prisoner_with_captor_is_reg0"),
	(ge, reg0, -10),		
	]),

	("neutral_behavior_in_fight", 
	[
      (get_player_agent_no, ":player_agent"),
      (agent_get_position, pos3, ":player_agent"),
      (agent_get_team, ":player_team", ":player_agent"),
	
      (try_begin),
        (gt, "$g_main_attacker_agent", 0),
        (agent_get_team, ":attacker_team_no", "$g_main_attacker_agent"),
        (agent_get_position, pos5, "$g_main_attacker_agent"),
      (else_try),
        (eq, ":attacker_team_no", -1),
        (agent_get_position, pos5, ":player_agent"),
      (try_end),
           
      (set_fixed_point_multiplier, 100),
	
      (try_for_agents, ":agent"),	
        (agent_get_team, ":other_team", ":agent"),
        (neq, ":other_team", ":attacker_team_no"),
        (neq, ":other_team", ":player_team"),
        
        (agent_get_troop_id, ":troop_id", ":agent"),
   		(neg|is_between, ":troop_id", "trp_swadian_recruit", "trp_looter"),
       
        (agent_get_position, pos4, ":agent"),
			
        (assign, ":best_position_score", 0),
        (assign, ":best_position", -1),
        
        (try_begin),        
          (neg|agent_slot_eq, ":agent", slot_agent_is_running_away, 0), #if agent is running away
          (agent_get_slot, ":target_entry_point_plus_one",  ":agent", slot_agent_is_running_away),
          (store_sub, ":target_entry_point", ":target_entry_point_plus_one", 1),
          (entry_point_get_position, pos6, ":target_entry_point"),
          (get_distance_between_positions, ":agent_distance_to_target", pos6, pos4),
          (lt, ":agent_distance_to_target", 100),
          (agent_set_slot, ":agent", slot_agent_is_running_away, 0),
        (try_end),
			
        (agent_slot_eq, ":agent", slot_agent_is_running_away, 0), #if agent is not already running away
        
        (try_begin), #stand in place
          (get_distance_between_positions, ":distance", pos4, pos5),
          (get_distance_between_positions, ":distance_to_player", pos4, pos3),

          (val_min, ":distance", ":distance_to_player"),
		
          (this_or_next|gt, ":distance", 700), #7 meters away from main belligerents
          (main_hero_fallen),

          (agent_set_scripted_destination, ":agent", pos4), 
        (else_try), #get out of the way			                    
          (try_for_range, ":target_entry_point", 0, 64),
            (neg|entry_point_is_auto_generated, ":target_entry_point"),
            (entry_point_get_position, pos6, ":target_entry_point"),
            (get_distance_between_positions, ":agent_distance_to_target", pos6, pos4),
            (get_distance_between_positions, ":player_distance_to_target", pos6, pos3),
            (store_sub, ":position_score", ":player_distance_to_target", ":agent_distance_to_target"),
            (ge, ":position_score", 0),
            (try_begin),
              (ge, ":agent_distance_to_target", 2000),
              (store_sub, ":extra_distance", ":agent_distance_to_target", 2000),
              (val_min, ":extra_distance", 1000),
              (val_min, ":agent_distance_to_target", 2000), #if more than 10 meters assume it is 10 meters far while calculating best run away target
              (val_sub, ":agent_distance_to_target", ":extra_distance"),
            (try_end),
            (val_mul, ":position_score", ":agent_distance_to_target"),
            (try_begin),
              (ge, ":position_score", ":best_position_score"),
              (assign, ":best_position_score", ":position_score"),
              (assign, ":best_position", ":target_entry_point"),
            (try_end),
          (try_end),
          
          (try_begin),
            (ge, ":best_position", 0),
            (entry_point_get_position, pos6, ":best_position"),
            (agent_set_speed_limit, ":agent", 10),
            (agent_set_scripted_destination, ":agent", pos6),
            (store_add, ":best_position_plus_one", ":best_position", 1),
            (agent_set_slot, ":agent", slot_agent_is_running_away, ":best_position_plus_one"),
          (try_end),
        (try_end),
	  (try_end),
	]),

	("party_inflict_attrition", #parameters from dialog
	[
	(store_script_param, ":party", 1),
	(store_script_param, ":attrition_rate", 2),	
#	(store_script_param, ":attrition_type", 3), #1 = desertion, 2 = sickness	

    (party_clear, "p_temp_casualties"),

	(party_get_num_companion_stacks, ":num_stacks", ":party"),

	#add to temp casualties
	(try_for_range, ":stack", 0, ":num_stacks"),
		(party_stack_get_troop_id, ":troop_type", ":party", ":stack"),
		(neg|troop_is_hero, ":troop_type"),
		(party_stack_get_size, ":size", ":party", ":stack"),
		(store_mul, ":casualties_x_100", ":attrition_rate", ":size"),
		(store_div, ":casualties", ":casualties_x_100", 100),
		(party_add_members, "p_temp_casualties", ":troop_type", ":casualties"),
		
		(store_mul, ":subtractor", ":casualties", 100),
		(store_sub, ":chance_of_additional_casualty", ":casualties_x_100", ":subtractor"),
	
		(try_begin),
			(gt, ":chance_of_additional_casualty", 0),
			(store_random_in_range, ":random", 0, 100),
			(lt, ":random", ":chance_of_additional_casualty"),
			(party_add_members, "p_temp_casualties", ":troop_type", ":casualties"),
		(try_end),

#		(try_begin),
#			(eq, "$cheat_mode", 1),
#			(str_store_party_name, s7, ":party"),
#           		...
#		(try_end),
	(try_end),
	
	#take temp casualties from main party
	(party_get_num_companion_stacks, ":num_stacks", "p_temp_casualties"),

	#add to temp casualties
	(try_for_range, ":stack", 0, ":num_stacks"),
		(party_stack_get_troop_id, ":troop_type", "p_temp_casualties", ":stack"),
		(party_stack_get_size, ":size", "p_temp_casualties", ":stack"),
		(party_remove_members, ":party", ":troop_type", ":size"),
		
		(eq, "$cheat_mode", 1),
		(assign, reg3, ":size"),
		(str_store_troop_name, s4, ":troop_type"),
		(str_store_party_name, s5, ":party"),
#		(display_message, "str_s5_suffers_attrition_reg3_x_s4"), 
		(str_store_string, s65, "str_s5_suffers_attrition_reg3_x_s4"), 
		(display_message, "str_s65"),
		(try_begin),
			(eq, "$debug_message_in_queue", 0),
			(call_script, "script_add_notification_menu", "mnu_debug_alert_from_s65", 0, 0),
			(assign, "$debug_message_in_queue", 1),
		(try_end),
	(try_end),
	
	]),
	
	
	
	
	("add_rumor_string_to_troop_notes", #parameters from dialog
	[
      (store_script_param, ":object_1", 1),
      (store_script_param, ":object_2", 2),	
      (store_script_param, ":string", 3),	
	
      (str_store_troop_name, s10, "$g_talk_troop"),
      (str_store_string_reg, s11, ":string"),
	
      (store_current_hours, ":hours"),
      (call_script, "script_game_get_date_text", 0, ":hours"),
	
      (str_store_string, s5, "str_s10_said_on_s1_s11__"),

      (try_begin),
        (is_between, ":object_1", active_npcs_begin, kingdom_ladies_end),
        (troop_get_slot, ":current_rumor_note", ":object_1", slot_troop_current_rumor),
        (val_add, ":current_rumor_note", 1),
        (try_begin),
          (neg|is_between, ":current_rumor_note", 3, 16),
          (assign, ":current_rumor_note", 3),
        (try_end),
        (troop_set_slot, ":object_1", slot_troop_current_rumor, ":current_rumor_note"),
		
        (add_troop_note_from_sreg, ":object_1", ":current_rumor_note", s5, 0), #troop, note slot, string, show       
		
        (try_begin),
          (eq, "$cheat_mode", 1),
          (str_store_troop_name, s3, ":object_1"),
          (assign, reg4, ":current_rumor_note"),
          (display_message, "str_rumor_note_to_s3s_slot_reg4_s5"),
        (try_end),
      (try_end),
      
      (try_begin),
        (is_between, ":object_2", active_npcs_begin, kingdom_ladies_end),
        (troop_get_slot, ":current_rumor_note", ":object_2", slot_troop_current_rumor),
        (val_add, ":current_rumor_note", 1),
        (try_begin),
          (neg|is_between, ":current_rumor_note", 3, 16),
          (assign, ":current_rumor_note", 3),
        (try_end),
        (troop_set_slot, ":object_2", slot_troop_current_rumor, ":current_rumor_note"),
        
        (add_troop_note_from_sreg, ":object_2", ":current_rumor_note", s5, 0), #troop, note slot, string, show        
        
        (try_begin),
          (eq, "$cheat_mode", 1),
          (str_store_troop_name, s3, ":object_2"),
          (assign, reg4, ":current_rumor_note"),
          (display_message, "str_rumor_note_to_s3s_slot_reg4_s5"),
        (try_end),
      (try_end),	
	]),

	("character_can_wed_character", #empty now, but might want to add mid-game
	[
	]),
	
	("troop_change_career", #empty now, but might want to add mid-game
	[
	]),
		
	("center_get_goods_availability", 
	[
	(store_script_param, ":center_no", 1),

	(str_store_party_name, s4, ":center_no"),
	
	(assign, ":hardship_index", 0),
	(try_for_range, ":cur_good", trade_goods_begin, trade_goods_end),
		
		#Must have consumption of at least 4 to be relevant
		#This prevents perishables and raw materials from having a major impact
		(try_begin),
			(is_between, ":center_no", villages_begin, villages_end),
			(item_get_slot, ":consumer_consumption", ":cur_good", slot_item_rural_demand),
		(else_try),
			(item_get_slot, ":consumer_consumption", ":cur_good", slot_item_urban_demand),
		(try_end),
		(gt, ":consumer_consumption", 2),
		
		
		(store_div, ":max_impact", ":consumer_consumption", 4), #was 4
		
		#High-demand items like grain tend to have much more dramatic price differentiation, so they yield substantially higher results than low-demand items
		
        (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, ":price", ":center_no", ":cur_good_price_slot"),
		
		(store_sub, ":price_differential", ":price", 1000),
		(gt, ":price_differential", 200), #was 100

		(val_div, ":price_differential", 200),
		(val_min, ":price_differential", ":max_impact"),
		
		(val_add, ":hardship_index", ":price_differential"),
	(try_end),
	
	(assign, reg0, ":hardship_index"),

	#(try_begin),
		#(eq, "$cheat_mode", 1),
		#(display_message, "@{!}DEBUG -- hardship index for {s4} = {reg0}"),
	#(try_end),	
	]),
	
	("lord_find_alternative_faction", #Also, make it so that lords will try to keep at least one center unassigned
	[
	  (store_script_param, ":troop_no", 1),
	  (store_faction_of_troop, ":orig_faction", ":troop_no"),
	  
	  (assign, ":new_faction", -1),
	  (assign, ":score_to_beat", -5),
	  
	  #Factions with an available center
	  (try_for_range, ":center_no", centers_begin, centers_end),
	    (this_or_next|party_slot_eq, ":center_no", slot_town_lord, stl_unassigned),
	    (party_slot_eq, ":center_no", slot_town_lord, stl_rejected_by_player),
	    (store_faction_of_party, ":center_faction", ":center_no"),
	    (neq, ":center_faction", ":orig_faction"),
	    (faction_get_slot, ":liege", ":center_faction", slot_faction_leader),
	    (this_or_next|neq, ":liege", "trp_player"),
	    (ge, "$player_right_to_rule", 25),	    
	    (call_script, "script_troop_get_relation_with_troop", ":troop_no", ":liege"),
	    (assign, ":liege_relation", reg0),
	    (gt, ":liege_relation", ":score_to_beat"),
	    (assign, ":new_faction", ":center_faction"),
	    (assign, ":score_to_beat", ":liege_relation"),
	  (try_end),
	  
	  #Factions without an available center
	  (try_begin),
	    (eq, ":new_faction", -1),
	    (assign, ":score_to_beat", 0),
	    
	    (try_for_range, ":kingdom", kingdoms_begin, kingdoms_end),
	      (faction_slot_eq, ":kingdom", slot_faction_state, sfs_active),
	      (faction_get_slot, ":liege", ":kingdom", slot_faction_leader),
	      (call_script, "script_troop_get_relation_with_troop", ":troop_no", ":liege"),
	      (assign, ":liege_relation", reg0),		
	      (gt, ":liege_relation", ":score_to_beat"),
# NE - Dark Knights do not seem to be inactive at all times during game 
# so when some lords cross over they activate the faction - quick & dirty fix
# based on invasion setting 	      
		  (try_begin),
		  (eq, ":kingdom", "fac_dark_knights"), 
		    (try_begin),
			 (gt,"$invaded",0),
			 (assign, ":new_faction", ":kingdom"),
	         (assign, ":score_to_beat", ":liege_relation"),	
			(else_try), 
             # if they haven't invaded, don't defect			
            (try_end), 			
		  (else_try),
	      (assign, ":new_faction", ":kingdom"),
	      (assign, ":score_to_beat", ":liege_relation"),		
		  (try_end),
	    (try_end),
	  (try_end),
	  
	  (assign, reg0, ":new_faction"),	
	]),
		
	("set_up_duel_with_troop", #now the setup is handled through the menu
	[
	  (store_script_param, "$g_duel_troop", 1),	
	  (assign, "$g_start_arena_fight_at_nearest_town", 1),
	  (try_begin),
	    (eq, "$g_start_arena_fight_at_nearest_town", 1),
	  (try_end),  
	  (unlock_achievement, ACHIEVEMENT_PUGNACIOUS_D),
      (jump_to_menu, "mnu_arena_duel_fight"),
	  (finish_mission),

	]),
		
	("test_player_for_career_and_marriage_incompatability", #empty now, but might want to add mid-game
	[
	#Married to a lord of one faction, while fighting for another
	#Married to one lord while holding a stipend from the king	
	]),

	("deduct_casualties_from_garrison", #after a battle in a center, deducts any casualties from "$g_encountered_party"
	[
	##(display_message, "str_totalling_casualties_caused_during_mission"),
	
	(try_for_agents, ":agent"),
		(agent_get_troop_id, ":troop_type", ":agent"),
		(is_between, ":troop_type", regular_troops_begin, regular_troops_end),
		
		(neg|agent_is_alive, ":agent"),
		
		(try_begin), #if troop not present, search for another type which is
			(store_troop_count_companions, ":number", ":troop_type", "$g_encountered_party"),
			(eq, ":number", 0),
			(assign, ":troop_type", 0),
			(try_for_range, ":new_tier", slot_faction_tier_1_troop, slot_faction_tier_5_troop),
			(faction_get_slot, ":troop_type", "$g_encountered_party_faction", ":new_tier"),
				(faction_get_slot, ":new_troop_type", "$g_encountered_party_faction", ":new_tier"),
				(store_troop_count_companions, ":number", ":new_troop_type", "$g_encountered_party"),
				(gt, ":number", 0), 
				(assign, ":troop_type", ":new_troop_type"),
			(try_end),
		(try_end),
		
		(gt, ":troop_type", 0),
			
		(party_remove_members, "$g_encountered_party", ":troop_type", 1),
		(str_store_troop_name, s4, ":troop_type"),
		(str_store_party_name, s5, "$g_encountered_party"),
	(try_end),		
	]),		
								
	("npc_decision_checklist_take_stand_on_issue",
	#Called from dialogs, and from simple_triggers
	
	#This a very inefficient checklist, and if I did it again, I would score for each troop. That way the troop could answer "why not" to an individual lord
	[
	(store_script_param, ":troop_no", 1),
	(store_faction_of_troop, ":troop_faction", ":troop_no"),
	
	(assign, ":result", -1),
	(faction_get_slot, ":faction_issue", ":troop_faction", slot_faction_political_issue),
	
	(assign, ":player_declines_honor", 0),
	(try_begin),
		(is_between, ":faction_issue", centers_begin, centers_end),
	    (gt, "$g_dont_give_fief_to_player_days", 1),
		(assign, ":player_declines_honor", 1),
	(else_try),
	    (gt, "$g_dont_give_marshalship_to_player_days", 1),
		(assign, ":player_declines_honor", 1),	
	(try_end),
	
	
	(assign, ":total_faction_renown", 0),
	(troop_set_slot, "trp_player", slot_troop_temp_slot, 0),
	(try_begin),
		(eq, "$players_kingdom", ":troop_faction"),
		(eq, "$player_has_homage", 1),
		(troop_get_slot, ":total_faction_renown", "trp_player", slot_troop_renown),
	(try_end),
	
	(try_for_range, ":active_npc", active_npcs_begin, active_npcs_end),
		(troop_set_slot, ":active_npc", slot_troop_temp_slot, 0), #reset to zero
	
		(store_faction_of_troop, ":active_npc_faction", ":active_npc"),
		(eq, ":active_npc_faction", ":troop_faction"),
		(troop_slot_eq, ":active_npc", slot_troop_occupation, slto_kingdom_hero),
		
		(troop_get_slot, ":renown", ":active_npc", slot_troop_renown),
		(val_add, ":total_faction_renown", ":renown"),
	(try_end),
	
	
	(assign, ":total_faction_center_value", 0),
	(try_for_range, ":center", centers_begin, centers_end),
		(store_faction_of_party, ":center_faction", ":center"),
		(eq, ":center_faction", ":troop_faction"),
		
		(assign, ":center_value", 1),
		(try_begin),
			(is_between, ":center", towns_begin, towns_end),
			(assign, ":center_value", 2),
		(try_end),
		
		(val_add, ":total_faction_center_value", ":center_value"),
		
		(party_get_slot, ":town_lord", ":center", slot_town_lord),
		(gt, ":town_lord", -1),
		
		(troop_get_slot, ":temp_slot", ":town_lord", slot_troop_temp_slot),
		(val_add, ":temp_slot", ":center_value"),
		(troop_set_slot, ":town_lord", slot_troop_temp_slot, ":temp_slot"),
	(try_end),
	(val_max, ":total_faction_center_value", 1),
	
	(store_div, ":average_renown_per_center_point", ":total_faction_renown", ":total_faction_center_value"),

	
	(try_begin),
		(is_between, ":faction_issue", centers_begin, centers_end),
		#NOTE -- The algorithms here might seem a bit repetitive, but are designed that way to create internal cliques among the lords in a faction.
	
	
	
		(try_begin),#If the center is a village, and a lord has no fief, choose him
			(neg|troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_debauched),
			(neg|troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_selfrighteous),
			(neg|troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_quarrelsome),
			
			(is_between, ":faction_issue", villages_begin, villages_end),
			(assign, ":favorite_lord_without_center", -1),
			(assign, ":score_to_beat", -1),
			
			
			(try_begin),
				(eq, "$players_kingdom", ":troop_faction"),
				(eq, "$player_has_homage", 1),
				(eq, ":player_declines_honor", 0),	
				
				(troop_slot_eq, "trp_player", slot_troop_temp_slot, 0),
				(call_script, "script_troop_get_relation_with_troop", "trp_player", ":troop_no"),
				(assign, ":relation", reg0),
				
				(gt, ":relation", ":score_to_beat"),
				(neg|troop_slot_ge, "trp_player", slot_troop_controversy, 75),
				(assign, ":favorite_lord_without_center", "trp_player"),
				(assign, ":score_to_beat", ":relation"),
			(try_end),
			(try_for_range, ":active_npc", active_npcs_begin, active_npcs_end),
				(store_faction_of_troop, ":active_npc_faction", ":active_npc"),
				(eq, ":active_npc_faction", ":troop_faction"),
				(troop_slot_eq, ":active_npc", slot_troop_occupation, slto_kingdom_hero),
			
				(troop_slot_eq, ":active_npc", slot_troop_temp_slot, 0),
				(try_begin),
					(eq, ":active_npc", ":troop_no"),
					(assign, ":relation", 50),
				(else_try),	
					(call_script, "script_troop_get_relation_with_troop", ":active_npc", ":troop_no"),
					(assign, ":relation", reg0),
				(try_end),
				(neg|troop_slot_ge, ":active_npc", slot_troop_controversy, 75),
				
				(gt, ":relation", ":score_to_beat"),
				(assign, ":favorite_lord_without_center", ":active_npc"),
				(assign, ":score_to_beat", ":relation"),
			(try_end),
			
			(gt, ":favorite_lord_without_center", -1),
			(assign, ":result", ":favorite_lord_without_center"),
			(assign, ":result_explainer", "str_political_explanation_lord_lacks_center"),
			
		(else_try),	#taken by troop
			(is_between, ":faction_issue", walled_centers_begin, walled_centers_end),
			(neg|troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_debauched),
			(neg|troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_selfrighteous),
			(neg|troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_cunning),
			
			(party_get_slot, ":last_taken_by_troop", ":faction_issue", slot_center_last_taken_by_troop),
			(try_begin),
				(try_begin),
					(neq, ":troop_faction", "$players_kingdom"),
					(assign, ":last_taken_by_troop", -1),
				(else_try),
					(eq, "$player_has_homage", 0),
					(assign, ":last_taken_by_troop", -1),
				(else_try),
					(eq, ":faction_issue", "$g_castle_requested_by_player"),
					(assign, ":last_taken_by_troop", "trp_player"),
				(else_try),
					(eq, ":faction_issue", "$g_castle_requested_for_troop"),
					(assign, ":last_taken_by_troop", "trp_player"),
				(else_try), #ie, the fellow who took it is no longer in the faction
					(gt, ":last_taken_by_troop", -1),
					(store_faction_of_troop, ":last_take_by_troop_faction", ":last_taken_by_troop"),
					(neq, ":last_take_by_troop_faction", ":troop_faction"),
					(assign, ":last_taken_by_troop", -1),
				(try_end),
			(try_end),	
			(gt, ":last_taken_by_troop", -1),

			(try_begin),
				(eq, "$cheat_mode", 1),
				(gt, ":last_taken_by_troop", -1),
				(str_store_troop_name, s3, ":last_taken_by_troop"),
				(display_message, "@{!}Castle taken by {s3}"),
			(try_end),

			
			(call_script, "script_troop_get_relation_with_troop", ":troop_no", ":last_taken_by_troop"),
			(ge, reg0, 0),
			
			(neg|troop_slot_ge, ":last_taken_by_troop", slot_troop_controversy, 25),
			
			(troop_get_slot, ":renown", ":last_taken_by_troop", slot_troop_renown),
			(troop_get_slot, ":center_points", ":last_taken_by_troop", slot_troop_temp_slot),
			(val_max, ":center_points", 1),
			(store_div, ":renown_divided_by_center_points", ":renown", ":center_points"),
			(val_mul, ":renown_divided_by_center_points", 6), #was five
			(val_div, ":renown_divided_by_center_points", 4),
			
			(ge, ":renown_divided_by_center_points", ":average_renown_per_center_point"),
			
			
			(assign, ":result", ":last_taken_by_troop"),
			(assign, ":result_explainer", "str_political_explanation_lord_took_center"),
			
			
		#Check self, immediate family
		#This is done instead of a single weighted score to create cliques -- groups of NPCs who support one another
		(else_try),
			(assign, ":most_deserving_close_friend", -1),
			(assign, ":score_to_beat", ":average_renown_per_center_point"),
			(val_div, ":score_to_beat", 3),
			(val_mul, ":score_to_beat", 2),
			
			(try_begin),
				(eq, "$cheat_mode", 1),
				(assign, reg3, ":score_to_beat"),
				(display_message, "@{!}Two-thirds average_renown = {reg3}"),
			(try_end),
			
			(try_begin),
				(eq, "$players_kingdom", ":troop_faction"),
				(eq, "$player_has_homage", 1),
				(eq, ":player_declines_honor", 0),	
				
				(call_script, "script_troop_get_relation_with_troop", "trp_player", ":troop_no"),
				(assign, ":relation", reg0),
				(ge, ":relation", 20),
				(neg|troop_slot_ge, "trp_player", slot_troop_controversy, 50),

				(troop_get_slot, ":renown", "trp_player", slot_troop_renown),
				(troop_get_slot, ":center_points", "trp_player", slot_troop_temp_slot),
				(val_max, ":center_points", 1),
				(store_div, ":renown_divided_by_center_points", ":renown", ":center_points"),
				
				
				(assign, ":most_deserving_close_friend", "trp_player"),
				(assign, ":score_to_beat", ":renown_divided_by_center_points"),
			(try_end),
			(try_for_range, ":active_npc", active_npcs_begin, active_npcs_end),
				(store_faction_of_troop, ":active_npc_faction", ":active_npc"),
				(eq, ":active_npc_faction", ":troop_faction"),			
				(troop_slot_eq, ":active_npc", slot_troop_occupation, slto_kingdom_hero),
				
				(call_script, "script_troop_get_relation_with_troop", ":active_npc", ":troop_no"),
				(assign, ":relation", reg0),
				
				(this_or_next|eq, ":active_npc", ":troop_no"),
					(ge, ":relation", 20),
				(neg|troop_slot_ge, ":active_npc", slot_troop_controversy, 50),
				
				(troop_get_slot, ":renown", ":active_npc", slot_troop_renown),
				(troop_get_slot, ":center_points", ":active_npc", slot_troop_temp_slot),
				(val_max, ":center_points", 1),
				(store_div, ":renown_divided_by_center_points", ":renown", ":center_points"),
				
				
				(try_begin),
					(eq, "$cheat_mode", 1),
					(str_store_troop_name, s10, ":active_npc"),
					(assign, reg3, ":renown_divided_by_center_points"),
					(display_message, "@{!}DEBUG -- Colleague test: score for {s10} = {reg3}"),
				(try_end),
				
				
				(gt, ":renown_divided_by_center_points", ":score_to_beat"),
		
				(assign, ":most_deserving_close_friend", ":active_npc"),
				(assign, ":score_to_beat", ":renown_divided_by_center_points"),
			(try_end),

			(gt, ":most_deserving_close_friend", -1),
			
			
			(assign, ":result", ":most_deserving_close_friend"),
			(assign, ":result_explainer", "str_political_explanation_most_deserving_friend"),
			

			
		(else_try),
		#Most deserving in entire faction, minus those with no relation
			(neg|troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_debauched),
			(neg|troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_selfrighteous),
			(neg|troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_quarrelsome),
		
			(assign, ":most_deserving_in_faction", -1),
			(assign, ":score_to_beat", 0),
			
			(try_begin),
				(eq, "$players_kingdom", ":troop_faction"),
				(eq, "$player_has_homage", 1),
				(eq, ":player_declines_honor", 0),	
				
				(call_script, "script_troop_get_relation_with_troop", "trp_player", ":troop_no"),
				(assign, ":relation", reg0),
				(ge, ":relation", 0),
				(troop_get_slot, ":renown", "trp_player", slot_troop_renown),
				(troop_get_slot, ":center_points", "trp_player", slot_troop_temp_slot),
				(neg|troop_slot_ge, "trp_player", slot_troop_controversy, 25),

				(val_max, ":center_points", 1),
				(store_div, ":renown_divided_by_center_points", ":renown", ":center_points"),
				
				(assign, ":most_deserving_in_faction", "trp_player"),
				(assign, ":score_to_beat", ":renown_divided_by_center_points"),
			(try_end),
			(try_for_range, ":active_npc", active_npcs_begin, active_npcs_end),
				(store_faction_of_troop, ":active_npc_faction", ":active_npc"),
				(eq, ":active_npc_faction", ":troop_faction"),			
				(troop_slot_eq, ":active_npc", slot_troop_occupation, slto_kingdom_hero),

				(call_script, "script_troop_get_relation_with_troop", ":active_npc", ":troop_no"),
				(assign, ":relation", reg0),
				(this_or_next|eq, ":active_npc", ":troop_no"),
					(ge, ":relation", 0),
				(neg|troop_slot_ge, ":active_npc", slot_troop_controversy, 25),

				(troop_get_slot, ":renown", ":active_npc", slot_troop_renown),
				(troop_get_slot, ":center_points", ":active_npc", slot_troop_temp_slot),
				(val_max, ":center_points", 1),
				
				(store_div, ":renown_divided_by_center_points", ":renown", ":center_points"),
				(gt, ":renown_divided_by_center_points", ":score_to_beat"),

				(try_begin),
					(eq, "$cheat_mode", 1),
					(str_store_string, s10, ":active_npc"),
					(assign, reg3, ":renown_divided_by_center_points"),
					(display_message, "@{!}DEBUG -- Open test: score for {s10} = {reg3}"),
				(try_end),

				
				(assign, ":most_deserving_in_faction", ":active_npc"),
				(assign, ":score_to_beat", ":renown_divided_by_center_points"),
			(try_end),

			
			(gt, ":most_deserving_in_faction", -1),
			(assign, ":result", ":most_deserving_in_faction"),
			(assign, ":result_explainer", "str_political_explanation_most_deserving_in_faction"),
		
		(else_try),
			(assign, ":result", ":troop_no"),
			(assign, ":result_explainer", "str_political_explanation_self"),
		(try_end),

		
	(else_try),
		(eq, ":faction_issue", 1),
		
		(assign, ":relationship_threshhold", 15),
		(try_begin),
			(troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_upstanding),
			(assign, ":relationship_threshhold", 5),
		(else_try),
			(troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_debauched),
			(assign, ":relationship_threshhold", 25),
		(try_end),
		
		#For marshals, score marshals according to renown divided by controversy - first for friends and family, then for everyone
		(assign, ":marshal_candidate", -1),
		(assign, ":score_to_beat", 0),
		(try_begin),
			(eq, "$players_kingdom", ":troop_faction"),
			(eq, "$player_has_homage", 1),
			(eq, "$g_player_is_captive", 0),
			(eq, ":player_declines_honor", 0),	
			
			
			(call_script, "script_troop_get_relation_with_troop", "trp_player", ":troop_no"),
			(ge, reg0, ":relationship_threshhold"),
			(assign, ":marshal_candidate", "trp_player"),
			(troop_get_slot, ":renown", "trp_player", slot_troop_renown),
			(troop_get_slot, ":controversy_divisor", "trp_player", slot_troop_controversy),
			(val_add, ":controversy_divisor", 50),
			(store_div, ":score_to_beat", ":renown", ":controversy_divisor"),
		(try_end),
		
		(try_for_range, ":active_npc", active_npcs_begin, active_npcs_end),
			(store_faction_of_troop, ":active_npc_faction", ":active_npc"),
			(eq, ":active_npc_faction", ":troop_faction"),		
			(troop_slot_eq, ":active_npc", slot_troop_occupation, slto_kingdom_hero),
			(troop_slot_eq, ":active_npc", slot_troop_prisoner_of_party, -1),
			
			(neg|faction_slot_eq, ":troop_faction", slot_faction_leader, ":active_npc"),
			
			(call_script, "script_troop_get_relation_with_troop", ":active_npc", ":troop_no"),
			(assign, ":relation", reg0),
			(this_or_next|eq, ":active_npc", ":troop_no"),
				(ge, ":relation", ":relationship_threshhold"),
				
			(troop_get_slot, ":renown", ":active_npc", slot_troop_renown),
			(troop_get_slot, ":controversy_divisor", ":active_npc", slot_troop_controversy),
			(val_add, ":controversy_divisor", 50),
			(store_div, ":score", ":renown", ":controversy_divisor"),
		
			(gt, ":score", ":score_to_beat"),
			
			(assign, ":marshal_candidate", ":active_npc"),
			(assign, ":score_to_beat", ":score"),
		
		(try_end),
		
		(assign, ":result", ":marshal_candidate"),
		(assign, ":result_explainer", "str_political_explanation_marshal"),
	(try_end),
	
	(try_begin),
		(eq, "$cheat_mode", 1),
		(gt, ":result", -1),
		(str_store_troop_name, s8, ":troop_no"),
		(str_store_troop_name, s9, ":result"),
		(str_store_string, s10, ":result_explainer"),
		(display_message, "@{!}DEBUG -- {s8} backs {s9}:{s10}"),
	(try_end),
	
	(assign, reg0, ":result"),
	(assign, reg1, ":result_explainer"),
	
	]),

	
	("npc_decision_checklist_evaluate_faction_strategy",
	[
	#Decides whether the strategy is good or bad -- to be added
	]),
	
	
	("process_player_enterprise",
    #reg0: Profit per cycle
	[
	  (store_script_param, ":item_type", 1),
	  (store_script_param, ":center", 2),
	  
	  (item_get_slot, ":price_of_labor", ":item_type", slot_item_overhead_per_run),
	  
	  (item_get_slot, ":base_price", ":item_type", slot_item_base_price),
	  (store_sub, ":cur_good_price_slot", ":item_type", trade_goods_begin),
	  (val_add, ":cur_good_price_slot", slot_town_trade_good_prices_begin),
	  (party_get_slot, ":cur_price_modifier", ":center", ":cur_good_price_slot"),
	  (store_mul, ":final_price_for_single_produced_good", ":base_price", ":cur_price_modifier"),
	  (val_div, ":final_price_for_single_produced_good", 1000),
	  (item_get_slot, ":number_of_outputs_produced", ":item_type", slot_item_output_per_run),
	  (store_mul, ":final_price_for_total_produced_goods", ":number_of_outputs_produced", ":final_price_for_single_produced_good"),
	  
	  (item_get_slot, ":primary_raw_material", ":item_type", slot_item_primary_raw_material),
	  (item_get_slot, ":base_price", ":primary_raw_material", slot_item_base_price),
	  (store_sub, ":cur_good_price_slot", ":primary_raw_material", trade_goods_begin),
	  (val_add, ":cur_good_price_slot", slot_town_trade_good_prices_begin),
	  (party_get_slot, ":cur_price_modifier", ":center", ":cur_good_price_slot"),
	  (store_mul, ":final_price_for_single_input", ":base_price", ":cur_price_modifier"),
	  (val_div, ":final_price_for_single_input", 1000),
	  (item_get_slot, ":number_of_inputs_required", ":item_type", slot_item_input_number),
	  (try_begin),
	    (lt, ":number_of_inputs_required", 0),
	    (store_div, ":final_price_for_total_inputs", ":final_price_for_single_input", 2),
	  (else_try),
	    (store_mul, ":final_price_for_total_inputs", ":final_price_for_single_input", ":number_of_inputs_required"),
	  (try_end),
	  
	  (try_begin),
	    (item_slot_ge, ":item_type", slot_item_secondary_raw_material, 1),
	    (item_get_slot, ":secondary_raw_material", ":item_type", slot_item_secondary_raw_material),	  	  
	    (item_get_slot, ":base_price", ":secondary_raw_material", slot_item_base_price),
	    (store_sub, ":cur_good_price_slot", ":secondary_raw_material", trade_goods_begin),
	    (val_add, ":cur_good_price_slot", slot_town_trade_good_prices_begin),
	    (party_get_slot, ":cur_price_modifier", ":center", ":cur_good_price_slot"),

	    (try_begin),
	      (lt, ":number_of_inputs_required", 0),
	      (store_div, ":final_price_for_secondary_input", ":final_price_for_secondary_input", 2),
	    (else_try),
	      (store_mul, ":final_price_for_secondary_input", ":final_price_for_secondary_input", ":number_of_inputs_required"),
	    (try_end),

	    (store_mul, ":final_price_for_secondary_input", ":base_price", ":cur_price_modifier"),
	    (val_div, ":final_price_for_secondary_input", 1000),
	  (else_try),
	    (assign, ":final_price_for_secondary_input", 0), 
	  (try_end),
	  
	  (store_sub, ":profit_per_cycle", ":final_price_for_total_produced_goods", ":final_price_for_total_inputs"),
	  (val_sub, ":profit_per_cycle", ":price_of_labor"),
	  (val_sub, ":profit_per_cycle", ":final_price_for_secondary_input"),
	  
	  (assign, reg0, ":profit_per_cycle"),
	  (assign, reg1, ":final_price_for_total_produced_goods"),
	  (assign, reg2, ":final_price_for_total_inputs"),
	  (assign, reg3, ":price_of_labor"),
	  (assign, reg4, ":final_price_for_single_produced_good"),
	  (assign, reg5, ":final_price_for_single_input"),
	  (assign, reg10, ":final_price_for_secondary_input"),
	]),

  # script_replace_scene_items_with_spawn_items_before_ms
  # Input: none
  # Output: none
  ("replace_scene_items_with_spawn_items_before_ms",
    [
      (try_for_range, ":item_no", all_items_begin, all_items_end),
        (scene_item_get_num_instances, ":num_instances", ":item_no"),
        (item_set_slot, ":item_no", slot_item_num_positions, 0),
        (assign, ":num_positions", 0),
        (try_for_range, ":cur_instance", 0, ":num_instances"),
          (scene_item_get_instance, ":scene_item", ":item_no", ":cur_instance"),
          (prop_instance_get_position, "$g_position_to_use_for_replacing_scene_items", ":scene_item"),
          (store_add, ":cur_slot", slot_item_positions_begin, ":num_positions"),
          (item_set_slot, ":item_no", ":cur_slot", "$g_position_to_use_for_replacing_scene_items"),
          (val_add, ":num_positions", 1),
          (val_add, "$g_position_to_use_for_replacing_scene_items", 1),
          (item_set_slot, ":item_no", slot_item_num_positions, ":num_positions"),
        (try_end),
        (replace_scene_items_with_scene_props, ":item_no", "spr_empty"),
      (try_end),
     ]),

  # script_replace_scene_items_with_spawn_items_after_ms
  # Input: none
  # Output: none
  ("replace_scene_items_with_spawn_items_after_ms",
    [
      (try_for_range, ":item_no", all_items_begin, all_items_end),
        (item_get_slot,  ":num_positions", ":item_no", slot_item_num_positions),
        (try_for_range, ":cur_position", 0, ":num_positions"),
          (store_add, ":cur_slot", slot_item_positions_begin, ":cur_position"),
          (item_get_slot, ":pos_no", ":item_no", ":cur_slot"),
          (set_spawn_position, ":pos_no"),
          (spawn_item, ":item_no", 0),
        (try_end),
      (try_end),
     ]),

  # script_cf_is_melee_weapon_for_tutorial
  # Input: arg1 = item_no
  # Output: none (can fail)
  ("cf_is_melee_weapon_for_tutorial",
    [
      (store_script_param, ":item_no", 1),
      (assign, ":result", 0),
      (try_begin),
        (this_or_next|eq, ":item_no", "itm_quarter_staff"),
        (eq, ":item_no", "itm_practice_sword"),
        (assign, ":result", 1),
      (try_end),
      (eq, ":result", 1),
     ]),

  # script_iterate_pointer_arrow
  # Input: none
  # Output: none
  ("iterate_pointer_arrow",
    [
      (store_mission_timer_a_msec, ":cur_time"),
      (try_begin),
        (assign, ":up_down", ":cur_time"),
        (assign, ":turn_around", ":cur_time"),
        (val_mod, ":up_down", 1080),
        (val_div, ":up_down", 3),
        (scene_prop_get_instance, ":prop_instance", "spr_pointer_arrow", 0),
        (prop_instance_get_position, pos0, ":prop_instance"),
        (position_set_z_to_ground_level, pos0),
        (position_move_z, pos0, "$g_pointer_arrow_height_adder", 1),
        (set_fixed_point_multiplier, 100),
        (val_mul, ":up_down", 100),
        (store_sin, ":up_down_sin", ":up_down"),
        (position_move_z, pos0, ":up_down_sin", 1),
        (position_move_z, pos0, 100, 1),
        (val_mod, ":turn_around", 2880),
        (val_div, ":turn_around", 8),
        (init_position, pos1),
        (position_rotate_z, pos1, ":turn_around"),
        (position_copy_rotation, pos0, pos1),
        (prop_instance_set_position, ":prop_instance", pos0),
      (try_end),
     ]),
  
   ("find_center_to_attack_alt",
    [
      (store_script_param, ":troop_no", 1),
      (store_script_param, ":attack_by_faction", 2),
      (store_script_param, ":all_vassals_included", 3),
      
      (assign, ":result", -1),
      (assign, ":score_to_beat", 0),
      
      (try_for_range, ":center_no", centers_begin, centers_end),            
        (call_script, "script_npc_decision_checklist_evaluate_enemy_center_for_attack",	":troop_no", ":center_no", ":attack_by_faction", ":all_vassals_included"),
        (assign, ":score", reg0),
                
        (gt, ":score", ":score_to_beat"),
        
        (assign, ":result", ":center_no"),
        (assign, ":score_to_beat", ":score"),
      (try_end),
      
      (assign, reg0, ":result"),
      (assign, reg1, ":score_to_beat"),      
	]),
	
  ("npc_decision_checklist_evaluate_enemy_center_for_attack",
    [
      #NOTES -- LAST OFFENSIVE TIME SCORE IS NOT USED
      
      (store_script_param, ":troop_no", 1),
      (store_script_param, ":potential_target", 2),
      (store_script_param, ":attack_by_faction", 3),
      (store_script_param, ":all_vassals_included", 4),
      
      (assign, ":result", -1),
      (assign, ":explainer_string", -1),
      #(assign, ":reason_is_obvious", 0),
      (assign, ":power_ratio", 0),
      #(assign, ":hours_since_last_recce", -1),
      
      #(assign, ":value_of_target", 0),
      #(assign, ":difficulty_of_capture", 0),
      (store_faction_of_troop, ":faction_no", ":troop_no"),
      
      (try_begin),
        (eq, ":attack_by_faction", 1),
        (faction_get_slot, ":faction_marshal", ":faction_no", slot_faction_marshall),
        (ge, ":faction_marshal", 0), #STEVE ADDITION TO AVOID MESSAGE SPAM
        (troop_get_slot, ":party_no", ":faction_marshal", slot_troop_leaded_party),
      (else_try),
        (troop_get_slot, ":party_no", ":troop_no", slot_troop_leaded_party),
      (try_end),
      
      (assign, "$g_use_current_ai_object_as_s8", 0),
            
      #THE FIRST BATCH OF DISQUALIFYING CONDITIONS DO NOT REQUIRE THE ATTACKING PARTY TO HAVE CURRENT INTELLIGENCE ON THE TARGET
      (try_begin),
        (neg|party_is_active, ":party_no"),
        
        (assign, ":result", -1),
        (assign, ":explainer_string", "str_center_party_not_active"),
        #(assign, ":reason_is_obvious", 1),
      (else_try), 
        (store_faction_of_party, ":potential_target_faction", ":potential_target"),
        (store_relation, ":relation", ":potential_target_faction", ":faction_no"),
        (ge, ":relation", 0),
        
        (assign, ":result", -1),
        (assign, ":explainer_string", "str_center_is_friendly"),
        #(assign, ":reason_is_obvious", 1),
      (else_try),
        (is_between, ":potential_target", walled_centers_begin, walled_centers_end),
        (assign, ":faction_of_besieger_party", -1),
        (try_begin),
          (neg|party_slot_eq, ":potential_target", slot_center_is_besieged_by, -1), 
          (party_get_slot, ":besieger_party", ":potential_target", slot_center_is_besieged_by),
          (party_is_active, ":besieger_party"),
          (store_faction_of_party, ":faction_of_besieger_party", ":besieger_party"),
        (try_end),
        
        (neq, ":faction_of_besieger_party", -1),
        (neq, ":faction_of_besieger_party", ":faction_no"),	
        
        (assign, ":result", -1),
        (assign, ":explainer_string", "str_center_is_already_besieged"),
        #(assign, ":reason_is_obvious", 1),
      (else_try),
        (is_between, ":potential_target", villages_begin, villages_end),
        (assign, ":village_is_looted_or_raided_already", 0),
        (try_begin),
          (party_slot_eq, ":potential_target", slot_village_state, svs_being_raided),
          (party_get_slot, ":raider_party", ":potential_target", slot_village_raided_by),
		  (party_is_active, ":raider_party"),
          (store_faction_of_party, ":raider_faction", ":raider_party"),
          (neq, ":raider_faction", ":faction_no"),
          (assign, ":raiding_by_one_other_faction", 1),
        (else_try),
          (assign, ":raiding_by_one_other_faction", 0),
        (try_end),
        
        (try_begin),
          (this_or_next|party_slot_eq, ":potential_target", slot_village_state, svs_looted),
          (eq, ":raiding_by_one_other_faction", 1),
          (assign, ":village_is_looted_or_raided_already", 1),
        (try_end),
        
        (eq, ":village_is_looted_or_raided_already", 1),
        
        (assign, ":result", -1),
        (assign, ":explainer_string", "str_center_is_looted_or_raided_already"),
        #(assign, ":reason_is_obvious", 1),
      (else_try),
        (this_or_next|troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_upstanding),
        (troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_goodnatured),
        
        (is_between, ":potential_target", villages_begin, villages_end),	
        (assign, ":result", -1),
        (assign, ":explainer_string", "str_center_marshal_does_not_want_to_attack_innocents"),
      (else_try),
        (assign, ":distance_from_our_closest_walled_center", 1000),
        (try_for_range, ":cur_center", walled_centers_begin, walled_centers_end),
           (store_faction_of_party, ":cur_center_faction", ":cur_center"),
           (eq, ":cur_center_faction", ":faction_no"),
           (store_distance_to_party_from_party, ":distance_from_cur_center", ":cur_center", ":potential_target"),
           (lt, ":distance_from_cur_center", ":distance_from_our_closest_walled_center"),
           (assign, ":distance_from_our_closest_walled_center", ":distance_from_cur_center"),
        (try_end),
                                                
        (gt, ":distance_from_our_closest_walled_center", 75),
        (this_or_next|troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_upstanding),
        (this_or_next|troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_debauched),
        (this_or_next|troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_goodnatured),
        (troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_cunning),
        
        (assign, ":result", -1),
        (assign, ":explainer_string", "str_center_far_away_our_cautious_marshal_does_not_wish_to_reconnoiter"),				
      #RECONNOITERING BEGINS HERE - VALUE WILL BE TEN OR LESS
      (else_try),
        (gt, ":distance_from_our_closest_walled_center", 90),
        
        (assign, ":result", -1),
        (assign, ":explainer_string", "str_center_far_away_even_for_our_aggressive_marshal_to_reconnoiter"),
        #(assign, ":reason_is_obvious", 1),	
      (else_try),
        (is_between, ":potential_target", walled_centers_begin, walled_centers_end),
        (neg|troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_martial),
        (neg|troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_quarrelsome),
        (neg|troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_selfrighteous),
        
        (assign, ":close_center_found", 0),
        (try_for_range, ":friendly_walled_center", walled_centers_begin, walled_centers_end),
          (eq, ":close_center_found", 0),
          (store_faction_of_party, ":friendly_walled_center_faction", ":friendly_walled_center"),
          (eq, ":friendly_walled_center_faction", ":faction_no"),
          (store_distance_to_party_from_party, ":distance_from_walled_center", ":potential_target", ":friendly_walled_center"),
          (lt, ":distance_from_walled_center", 60),
          (assign, ":close_center_found", 1),
        (try_end),
        (eq, ":close_center_found", 0),
        
        (assign, ":result", -1),
        (assign, ":explainer_string", "str_center_is_indefensible"),	
      #(else_try),
        #For now it is removed as Armagan's decision, we can add this option in later patchs. I and Armagan accept it has good potential. But this system needs also
        #scouting quests and scouting AI added together. If we only add this then we limit AI very much, it can attack only very few of centers, this damages 
        #variability of game and surprise attacks of AI. Player can predict where AI will attack and he can full garnisons of only this center. 
        #We can add asking travellers about how good defended center X by paying 100 denars for example to equalize situations of AI and human player.
        #But these needs much work and detailed AI tests so Armagan decided to skip this for now.
        
        #(store_sub, ":faction_recce_slot", ":faction_no", kingdoms_begin),
        #(val_add, ":faction_recce_slot", slot_center_last_reconnoitered_by_faction_time),
        #(party_get_slot, ":last_recce_time", ":potential_target", ":faction_recce_slot"),
        #(store_current_hours, ":hours_since_last_recce"),
        #(val_sub, ":hours_since_last_recce", ":last_recce_time"),
        
        #(this_or_next|eq, ":last_recce_time", 0),
        #(gt, ":hours_since_last_recce", 96), #Information is presumed to be accurate for four days
        
        #(store_sub, ":150_minus_distance_div_by_10", 150, ":distance_from_party"),
        #(val_div, ":150_minus_distance_div_by_10", 10),
        
        #(assign, ":result", ":150_minus_distance_div_by_10"),
        #(assign, ":explainer_string", "str_center_has_not_been_scouted"),
      #DECISIONS BASED ON ENEMY STRENGTH BEGIN HERE
      (else_try),
        (party_get_slot, ":party_strength", ":party_no", slot_party_cached_strength),
        (party_get_slot, ":follower_strength", ":party_no", slot_party_follower_strength),
        (party_get_slot, ":strength_of_nearby_friend", ":party_no", slot_party_nearby_friend_strength),                
        
        (store_add, ":total_strength", ":party_strength", ":follower_strength"),
        (val_add, ":total_strength", ":strength_of_nearby_friend"),
        
        #(party_get_slot, ":potential_target_nearby_enemy_exact_strength", ":potential_target", slot_party_nearby_friend_strength),
        #(assign, ":potential_target_nearby_enemy_strength", ":potential_target_nearby_enemy_exact_strength"),                
        (try_begin),
          (is_between, ":potential_target", villages_begin, villages_end),
          (assign, ":enemy_strength", 10),
        (else_try),
          (party_get_slot, ":enemy_strength", ":potential_target", slot_party_cached_strength),
          (party_get_slot, ":enemy_strength_nearby", ":potential_target", slot_party_nearby_friend_strength),
          (val_add, ":enemy_strength", ":enemy_strength_nearby"),
        (try_end),
        (val_max, ":enemy_strength", 1),                

        (this_or_next|troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_martial),
        (this_or_next|troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_quarrelsome),
        (troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_selfrighteous),
        
        (store_mul, ":power_ratio", ":total_strength", 100),
        (val_div, ":power_ratio", ":enemy_strength"),
        (lt, ":power_ratio", 150), 
        
        (assign, ":result", -1),
        (assign, ":explainer_string", "str_center_protected_by_enemy_army_aggressive"),
      (else_try),
        (ge, ":enemy_strength", ":total_strength"), #if enemy is powerful
        
        (assign, ":result", -1),
        (assign, ":explainer_string", "str_center_protected_by_enemy_army_cautious"),
      (else_try),               
        (store_mul, ":power_ratio", ":total_strength", 100),
        (val_div, ":power_ratio", ":enemy_strength"),
        (lt, ":power_ratio", 185), 
        
        (this_or_next|troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_upstanding),
        (this_or_next|troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_debauched),
        (this_or_next|troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_goodnatured),
        (troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_cunning),
        
        #equations here
        (assign, ":result", -1),
        (assign, ":explainer_string", "str_center_cautious_marshal_believes_center_too_difficult_to_capture"),
      (else_try),
        (lt, ":power_ratio", 140), #it was 140
        
        (assign, ":result", -1),
        (assign, ":explainer_string", "str_center_even_aggressive_marshal_believes_center_too_difficult_to_capture"),
      #To Steve - I moved below two if statement here from upper places, to enable in answering different different answers even 
      #if we are close to an unlooted enemy village. For example now it can say "center X" is too far too while our army is 
      #looting a village because of its closeness.
      (else_try),
        #if the party has already started the siege
        (faction_slot_eq, ":faction_no", slot_faction_ai_state, sfai_raiding_village),
        (faction_get_slot, ":current_object", ":faction_no", slot_faction_ai_object),
        (is_between, ":current_object", villages_begin, villages_end),
        (neq, ":potential_target", ":current_object"),
        (party_slot_eq, ":current_object", slot_village_state, svs_under_siege),
        
        (store_current_hours, ":hours_since_siege_began"),
        (party_get_slot, ":hour_that_siege_began", ":current_object", slot_center_siege_begin_hours),
        (val_sub, ":hours_since_siege_began", ":hour_that_siege_began"),
        (gt, ":hours_since_siege_began", 4),
        
        (call_script, "script_npc_decision_checklist_evaluate_enemy_center_for_attack", ":troop_no", ":current_object", ":attack_by_faction", 0),
        (gt, reg0, -1),
        
        (assign, ":result", -1),
        (assign, ":explainer_string", "str_center_we_have_already_committed_too_much_time_to_our_present_siege_to_move_elsewhere"),
      (else_try),
        #If the party is close to an unlooted village
        (faction_slot_eq, ":faction_no", slot_faction_ai_state, sfai_raiding_village),
        (faction_get_slot, ":current_object", ":faction_no", slot_faction_ai_object),       
        (neq, ":potential_target", ":current_object"),
        (is_between, ":current_object", villages_begin, villages_end),
        (store_distance_to_party_from_party, ":distance_to_cur_object", ":party_no", ":current_object"),
        (lt, ":distance_to_cur_object", 10),
        
        (call_script, "script_npc_decision_checklist_evaluate_enemy_center_for_attack", ":troop_no", ":current_object", ":attack_by_faction", 0),
        (gt, reg0, -1),
        
        (assign, "$g_use_current_ai_object_as_s8", 1),
                
        (assign, ":result", -1),
        (assign, ":explainer_string", "str_center_we_are_already_here_we_should_at_least_loot_the_village"),
      #DECISION TO ATTACK IS HERE
      #(else_try),
        #To Steve - I removed below lines, as here decided. We will use pre-function to evaluate assailability scores for centers rather than below lines to make AI 
        #selecting better targets. If you want to make some marshals to select not-best options I can add that option into script_calculate_center_assailability_score, 
        #for that we can need seed values for each center and for each lord, so we can add these seed values to create variability, clever marshals have seeds with less 
        #standard deviation and less values and less-clever marshals have bigger seeds. Then probability of some lords to disagree marshal increases because their seed 
        #values will be different from marshal's. If Steve wants it from me to implement I can add this.
      
        #(try_begin),
        #  (is_between, ":potential_target", villages_begin, villages_end),
        #  (party_get_slot, ":score", ":potential_target", slot_town_prosperity),
        #  (val_add, ":score", 50), #average 100
        #(else_try),
        #  (is_between, ":potential_target", castles_begin, castles_end),
        #  (assign, ":score", ":power_ratio"), #ie, at least 140
        #(else_try),	
        #  (party_get_slot, ":score", ":potential_target", slot_town_prosperity),
        #  (val_add, ":score", 75),
        #  (val_mul, ":score", ":power_ratio"),
        #  (val_div, ":score", 100), #ie, at least about 200
        #(try_end),
        # 
        #(val_sub, ":score", ":distance_from_party"),
        #(lt, ":score", -1),
      
        #(assign, ":result", -1),
        #(assign, ":explainer_string", "str_center_value_outweighed_by_difficulty_of_capture"),
      (else_try),
        (try_begin),
          (eq, "$cheat_mode", 1),
          (eq, ":faction_no", "fac_kingdom_3"),
          (store_faction_of_party, ":potential_target_faction", ":potential_target"),
          (store_relation, ":relation", ":potential_target_faction", ":faction_no"),
          (lt, ":relation", 0),
        (try_end),  

        (call_script, "script_calculate_center_assailability_score", ":troop_no", ":potential_target", ":all_vassals_included"),
        (assign, ":score", reg0),
        (assign, ":power_ratio", reg1),
        #(assign, ":distance_score", reg2),
      
        (assign, ":result", ":score"),
      
        (try_begin),
          (le, ":power_ratio", 100),
          (try_begin),
            (this_or_next|troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_upstanding),
            (this_or_next|troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_debauched),
            (this_or_next|troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_goodnatured),
            (troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_cunning),	      	      
            (assign, ":explainer_string", "str_center_cautious_marshal_believes_center_too_difficult_to_capture"),
          (else_try),
            (assign, ":explainer_string", "str_center_even_aggressive_marshal_believes_center_too_difficult_to_capture"),
          (try_end),
        (else_try),
          (le, ":power_ratio", 150),
        
          (try_begin),
	        (this_or_next|troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_upstanding),
	        (this_or_next|troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_debauched),
	        (this_or_next|troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_goodnatured),
	        (troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_cunning),	      	      
	        (assign, ":explainer_string", "str_center_protected_by_enemy_army_cautious"),
	      (else_try),
	        (assign, ":explainer_string", "str_center_protected_by_enemy_army_aggressive"),
	      (try_end),
	    (else_try),
	      (try_begin),
	        (le, ":score", "$g_faction_object_score"),
	        (assign, ":explainer_string", "str_center_value_outweighed_by_difficulty_of_capture"),
	      (else_try),
	        #To Steve, does not this sentence needs to explain why we are not attacking that city? 
	        #This sentence says it justifies, so why we are not attacking?
	        (assign, ":explainer_string", "str_center_value_justifies_the_difficulty_of_capture"),
	      (try_end),
	    (try_end),
	  (try_end),
	  	  
	  (assign, reg0, ":result"),
	  (assign, reg1, ":explainer_string"),
	  (assign, reg2, ":power_ratio"),	  	  
     ]),
              
 	(
	"npc_decision_checklist_faction_ai_alt", #This is called from within decide_faction_ai, or from 
	[
		(store_script_param, ":troop_no", 1),
		
		(store_faction_of_troop, ":faction_no", ":troop_no"),
		
		(str_store_troop_name, s4, ":troop_no"),
		(str_store_faction_name, s33, ":faction_no"),
		(try_begin),
			(eq, "$cheat_mode", 1),
		    (display_message, "@{!}DEBUG -- {s4} produces a faction strategy for {s33}"),
		(try_end),
		  		  
		#INFORMATIONS COLLECTING STEP 0: Here we obtain general information about current faction like how much parties that faction has, which lord is the marshall, current ai state and current ai target object
		#(faction_get_slot, ":faction_strength", ":faction_no", slot_faction_number_of_parties),
		(faction_get_slot, ":faction_marshal", ":faction_no", slot_faction_marshall),
		(faction_get_slot, ":current_ai_state", ":faction_no", slot_faction_ai_state),
		(faction_get_slot, ":current_ai_object", ":faction_no", slot_faction_ai_object),
		
		(assign, ":marshal_party", -1),
		(assign, ":marshal_party_strength", 0),
		  
		(try_begin),
		  (gt, ":faction_marshal", 0),
		  (troop_get_slot, ":marshal_party", ":faction_marshal", slot_troop_leaded_party),
		  (party_is_active, ":marshal_party"),
		  (party_get_slot, ":marshal_party_itself_strength", ":marshal_party", slot_party_cached_strength),
		  (party_get_slot, ":marshal_party_follower_strength", ":marshal_party", slot_party_follower_strength),
		  (store_add, ":marshal_party_strength", ":marshal_party_itself_strength", ":marshal_party_follower_strength"),
	    (try_end),
					
	    #INFORMATIONS COLLECTING STEP 1: Here we are learning how much hours past from last offensive situation/feast concluded/current state started
	    (store_current_hours, ":hours_since_last_offensive"),
	    (faction_get_slot, ":last_offensive_time", ":faction_no", slot_faction_last_offensive_concluded),
	    (val_sub, ":hours_since_last_offensive", ":last_offensive_time"),
	      
	    (store_current_hours, ":hours_since_last_feast_start"),
	    (faction_get_slot, ":last_feast_time", ":faction_no", slot_faction_last_feast_start_time),
	    (val_sub, ":hours_since_last_feast_start", ":last_feast_time"),
	      
	    (store_current_hours, ":hours_at_current_state"),
	    (faction_get_slot, ":current_state_started", ":faction_no", slot_faction_ai_current_state_started),
	    (val_sub, ":hours_at_current_state", ":current_state_started"),
	      
	    (store_current_hours, ":hours_since_last_faction_rest"),
	    (faction_get_slot, ":last_rest_time", ":faction_no", slot_faction_ai_last_rest_time),
	    (val_sub, ":hours_since_last_faction_rest", ":last_rest_time"),
			  
	    (try_begin), #calculating ":last_offensive_time_score", this will be used in #11 and #12
	        (ge, ":hours_since_last_offensive", 1080), #more than 45 days (100p)
	        (assign, ":last_offensive_time_score", 100),
	    (else_try),
	        (ge, ":hours_since_last_offensive", 480), #more than 20 days (65p..99p)
	        (store_sub, ":last_offensive_time_score", ":hours_since_last_offensive", 480),
	        (val_div, ":last_offensive_time_score", 20), 
	        (val_add, ":last_offensive_time_score", 64),
	    (else_try),
	        (ge, ":hours_since_last_offensive", 240), #more than 10 days (41p..64p)
	        (store_sub, ":last_offensive_time_score", ":hours_since_last_offensive", 240),
	        (val_div, ":last_offensive_time_score", 10), 
	        (val_add, ":last_offensive_time_score", 40),
	    (else_try), #less than 10 days (0p..40p)
	        (store_div, ":last_offensive_time_score", ":hours_since_last_offensive", 6), #0..40
	    (try_end),
	    (try_begin),
	        (eq, ":faction_no", "fac_dark_knights"),
	        (val_mul, ":last_offensive_time_score", 2),
	        (val_min, ":last_offensive_time_score", 100),
	    (try_end),
									
	    #INFORMATION COLLECTING STEP 3: Here we are finding the most threatened center
	    (call_script, "script_find_center_to_defend", ":troop_no"),
	    (assign, ":most_threatened_center", reg0),
	    (assign, ":threat_danger_level", reg1),
	    (assign, ":enemy_strength_near_most_threatened_center", reg2), #NOTE! This will be off by as much as 50%
		  		 	      		
	    #INFORMATION COLLECTING STEP 4: Here we are finding number of vassals who are already following the marshal, and the assigned vassal ratio of current faction.
	    (assign, ":vassals_already_assembled", 0),
	    (assign, ":total_vassals", 0),	
	    (try_for_range, ":lord", active_npcs_begin, active_npcs_end),
	        (store_faction_of_troop, ":lord_faction", ":lord"),
	        (eq, ":lord_faction", ":faction_no"),
	        (troop_get_slot, ":led_party", ":lord", slot_troop_leaded_party),
	        (party_is_active, ":led_party"),
	        (val_add, ":total_vassals", 1),
			
	        (party_slot_eq, ":led_party", slot_party_ai_state, spai_accompanying_army),
	        (party_slot_eq, ":led_party", slot_party_ai_object, ":marshal_party"),
			
	        (party_is_active, ":marshal_party"),
	        (store_distance_to_party_from_party, ":distance_to_marshal", ":led_party", ":marshal_party"),
	        (lt, ":distance_to_marshal", 15),
	        (val_add, ":vassals_already_assembled", 1),
	    (try_end),
	    (assign, ":ratio_of_vassals_assembled", -1),
	    (try_begin),
	        (gt, ":total_vassals", 0),
	        (store_mul, ":ratio_of_vassals_assembled", ":vassals_already_assembled", 100),
	        (val_div, ":ratio_of_vassals_assembled", ":total_vassals"),
	    (try_end),
		
	    #50% of vassals means that the campaign hour limit is ten days
	    (store_mul, ":campaign_hour_limit", ":ratio_of_vassals_assembled", 3),
	    (val_add, ":campaign_hour_limit", 90), 
	    
	    #To Steve - I understand your concern about some marshals will gather army and some will not be able to find any valueable center to attack after gathering,
	    #and these marshals will be questioned by other marshals ext. This is ok but if we search for a target without adding all other vassals what if 
	    #AI cannot find any target for long time because of its low power ratio if enemy cities are equal defended? Do not forget if we do not count other vassals in 
	    #faction while making target search we can only add marshal army's power and vassals around him. And if there is any threat in our centers even it is smaller, 
	    #its threat_danger_level will be more than target_value_level if marshal new started gathering for ofensive. Because we only assume marshal and around vassals 
	    #will join attack. And in our scenarios currently there are less vassals are around him. So power ratio will be low and any small threat will be enought to stop 
	    #an offensive. Then when players finds out this they periodically will take under siege to enemy's any center and they will be saved from any kind of newly started 
	    #offensive they will be faced. So we have to calculate both attack levels and select highest one to compare with threat level. Please do not change this part.
		
		(try_begin),
		  (ge, ":faction_marshal", 0),
		  (ge, ":marshal_party", 0),
		  (party_is_active, ":marshal_party"),

		  (call_script, "script_party_count_fit_for_battle", ":marshal_party"),
		  (assign, ":number_of_fit_soldiers_in_marshal_party", reg0),
		  (ge, ":number_of_fit_soldiers_in_marshal_party", 40),
		  
		  (call_script, "script_find_center_to_attack_alt", ":troop_no", 1, 0),
		  (assign, ":center_to_attack_all_vassals_included", reg0),
		  (assign, ":target_value_level_all_vassals_included", reg1),
		  
		  (call_script, "script_find_center_to_attack_alt", ":troop_no", 1, 1),
		  (assign, ":center_to_attack_only_marshal_and_followers", reg0),
		  (assign, ":target_value_level_only_marshal_and_followers", reg1),
		(else_try),  
		  (assign, ":target_value_level_all_vassals_included", 0),
		  (assign, ":target_value_level_only_marshal_and_followers", 0),
		  (assign, ":center_to_attack_all_vassals_included", -1),
		  (assign, ":center_to_attack_only_marshal_and_followers", -1),
		(try_end),
		
		(try_begin),
		  (ge, ":target_value_level_all_vassals_included", ":center_to_attack_only_marshal_and_followers"),
		  (assign, ":center_to_attack", ":center_to_attack_all_vassals_included"),
		  (assign, ":target_value_level", ":target_value_level_all_vassals_included"),
		(else_try),  
		  (assign, ":center_to_attack", ":center_to_attack_only_marshal_and_followers"),
		  (assign, ":target_value_level", ":target_value_level_only_marshal_and_followers"),
		(try_end),
		  		  
		(try_begin),
		  (eq, ":current_ai_state", sfai_attacking_center),
		  (val_mul, ":target_value_level", 3),
		  (val_div, ":target_value_level", 2),
		(try_end),

		(try_begin),
		  (eq, "$cheat_mode", 1),
		  (try_begin),
		    (is_between, ":center_to_attack", centers_begin, centers_end),
		    (str_store_party_name, s4, ":center_to_attack"),
		    (display_message, "@{!}Best offensive target {s4} has value level of {reg1}"),
		  (else_try),
		    (display_message, "@{!}No center found to attack"),
		  (try_end),	
		
		  (try_begin),
		    (is_between, ":most_threatened_center", centers_begin, centers_end),
		    (str_store_party_name, s4, ":most_threatened_center"),
		    (assign, reg1, ":threat_danger_level"),
		    (display_message, "@{!}Best threat of {s4} has value level of {reg1}"),
		  (else_try),
		    (display_message, "@{!}No center found to defend"),
		  (try_end),  
		(try_end),
		
		(try_begin),
		  (eq, "$cheat_mode", 1),
		  
		  (try_begin),
  		    (is_between, ":most_threatened_center", centers_begin, centers_end),
 		    (str_store_party_name, s4, ":most_threatened_center"),
		    (assign, reg1, ":threat_danger_level"),
		    (display_message, "@Best threat of {s4} has value level of {reg1}"),
		  (else_try),
		    (display_message, "@No center found to defend"),
		  (try_end),  
		(try_end),  
				
	    (assign, "$g_target_after_gathering", -1),
	    
	    (store_current_hours, ":hours"),	      
	    (try_begin),
	      (ge, ":target_value_level", ":threat_danger_level"),
	      (faction_set_slot, ":faction_no", slot_faction_last_safe_hours, ":hours"),	  
	    (try_end),  
	    (faction_get_slot, ":last_safe_hours", ":faction_no", slot_faction_last_safe_hours),
	    (try_begin),
	      (eq, ":last_safe_hours", 0),
	      (faction_set_slot, ":faction_no", slot_faction_last_safe_hours, ":hours"),	  
	    (try_end),
	    (faction_get_slot, ":last_safe_hours", ":faction_no", slot_faction_last_safe_hours),
	    (store_sub, ":hours_since_days_defensive_started", ":hours", ":last_safe_hours"),
	    (str_store_faction_name, s7, ":faction_no"),

		(assign, ":at_peace_with_everyone", 1),
		(try_for_range, ":faction_at_war", kingdoms_begin, kingdoms_end),
			(store_relation, ":relation", ":faction_no", ":faction_at_war"),
			(lt, ":relation", 0),
			(assign, ":at_peace_with_everyone", 0),
		(try_end),

	    
	    #INFORMATIONS ARE COLLECTED, NOW CHECK ALL POSSIBLE ACTIONS AND DECIDE WHAT TO DO	NEXT
		#Player marshal
		(try_begin), # a special case to end long-running feasts
			(eq, ":troop_no", "trp_player"),
				
			(eq, ":current_ai_state", sfai_feast),
			(ge, ":hours_at_current_state", 72),
		
			(assign, ":action", sfai_default),
			(assign, ":object", -1),
			
			#Normally you are not supposed to set permanent values in this state, but this is a special case to end player-called feasts
			(assign, "$player_marshal_ai_state", sfai_default),
			(assign, "$player_marshal_ai_object", -1),
		(else_try), #another special state, to make player-called feasts last for a while when the player is the leader of the faction, but not the marshal
			(eq, "$players_kingdom", "fac_player_supporters_faction"),
			(faction_slot_eq, "$players_kingdom", slot_faction_leader, "trp_player"),
			(neq, ":troop_no", "trp_player"),
			
			(eq, ":current_ai_state", sfai_feast),
			(le, ":hours_at_current_state", 48),
			
			(party_slot_eq, ":current_ai_object", slot_town_lord, "trp_player"),
			(store_faction_of_party, ":current_ai_object_faction", ":current_ai_object"),
			(eq, ":current_ai_object_faction", "$players_kingdom"),
			
			(assign, ":action", sfai_feast),
			(assign, ":object", ":current_ai_object"),

			
		(else_try), #this is the main player marshal state
			(eq, ":troop_no", "trp_player"),
			
			(str_clear, s14),
			(assign, ":action", "$player_marshal_ai_state"),
			(assign, ":object", "$player_marshal_ai_object"),
			
	    #1-RESTING IF NEEDED 
	    #If not currently attacking a besieging a center and vassals did not rest for long time, let them rest.
	    #If we do not take this part to toppest level, tired vassals already did not accept any order, so that 
	    #faction cannot do anything already. So first let vassals rest if they need. Thats why it should be toppest.
		(else_try),
			(neq, ":current_ai_state", sfai_default),
			(neq, ":current_ai_state", sfai_feast),
			(party_is_active, ":marshal_party"),
		
			(party_slot_eq, ":marshal_party", slot_party_ai_state, spai_retreating_to_center),
			
			(assign, ":action", sfai_default),
			(assign, ":object", -1),
			(str_store_string, s14, "str_the_enemy_temporarily_has_the_field"),
				
		(else_try), 
		    (neq, ":current_ai_state", sfai_feast),
		    
		    (assign, ":currently_besieging", 0),
		    (try_begin),
			    (eq, ":current_ai_state", sfai_attacking_center),
			    (is_between, ":current_ai_object", walled_centers_begin, walled_centers_end),
			    (party_get_slot, ":besieger_party", ":current_ai_object", slot_center_is_besieged_by),
			    (party_is_active, ":besieger_party"),
			    (store_faction_of_party, ":besieger_faction", ":besieger_party"),
			    (eq, ":besieger_faction", ":faction_no"),
			    (assign, ":currently_besieging", 1),
		    (try_end),
		    
		    (assign, ":currently_defending_center", 0),
	        (try_begin),
		        (eq, ":current_ai_state", sfai_attacking_enemies_around_center),
		        (gt, ":marshal_party", 0),
		        (party_is_active, ":marshal_party"),

				(assign, ":besieged_center", -1),          
				(try_begin),
					(party_slot_eq, ":marshal_party", slot_party_ai_state, spai_holding_center), #if commander is holding a center
					(party_get_slot, ":marshal_object", ":marshal_party", slot_party_ai_object), #get commander's ai object (center they are holding)
					(party_get_battle_opponent, ":besieger_enemy", ":marshal_object"), #get this object's battle opponent
					(ge, ":besieger_enemy", 0),
					(assign, ":besieged_center", ":marshal_object"),
				(else_try),
					(party_slot_eq, ":marshal_party", slot_party_ai_state, spai_engaging_army), #if commander is engaging an army
					(party_get_slot, ":marshal_object", ":marshal_party", slot_party_ai_object), #get commander's ai object (army which they engaded)
					(ge, ":marshal_object", 0), #if commander has an object
					(neg|is_between, ":marshal_object", centers_begin, centers_end), #if this object is not a center, so it is a party
					(party_is_active, ":marshal_object"),
					(party_get_battle_opponent, ":besieged_center", ":marshal_object"), #get this object's battle opponent
				(try_end),
	          
				(eq, ":besieged_center", ":current_ai_object"),
				(assign, ":currently_defending_center", 1),
	        (try_end),

		    (eq, ":currently_besieging", 0),	    
		    (eq, ":currently_defending_center", 0),
		    (ge, ":hours_since_last_faction_rest", 1240),

			(assign, ":action", sfai_default),
			(assign, ":object", -1),
			(str_store_string, s14, "str_the_vassals_are_tired_we_let_them_rest_for_some_time"),	    
		
	  #2-DEFENSIVE ACTIONS : GATHERING ARMY FOR DEFENDING
          (else_try),
            (party_is_active, ":marshal_party"),
			(eq, ":at_peace_with_everyone", 0),
            
            (is_between, ":most_threatened_center", centers_begin, centers_end),
            (this_or_next|eq, ":current_ai_state", sfai_default),    #MOTO not going to attack anyway 
            (this_or_next|eq, ":current_ai_state", sfai_feast),    #MOTO not going to attack anyway (THIS is the emergency to stop feast) 
            (gt, ":threat_danger_level", ":target_value_level"),
                        
            (assign, ":continue_gathering", 0),
            (assign, ":start_gathering", 0),
            
            (try_begin),
              (is_between, ":most_threatened_center", villages_begin, villages_end),

              (assign, ":continue_gathering", 0),
            (else_try),
              (try_begin),
                (lt, ":hours_since_days_defensive_started", 3),
                (assign, ":multiplier", 150),
              (else_try),
                (lt, ":hours_since_days_defensive_started", 6),
                (assign, ":multiplier", 140),
              (else_try),
                (lt, ":hours_since_days_defensive_started", 9),
                (assign, ":multiplier", 132),
              (else_try),
                (lt, ":hours_since_days_defensive_started", 12),
                (assign, ":multiplier", 124),
              (else_try),
                (lt, ":hours_since_days_defensive_started", 15),
                (assign, ":multiplier", 118),
              (else_try),
                (lt, ":hours_since_days_defensive_started", 18),
                (assign, ":multiplier", 114),
              (else_try),
                (lt, ":hours_since_days_defensive_started", 21),
                (assign, ":multiplier", 110),
              (else_try),
                (lt, ":hours_since_days_defensive_started", 24),
                (assign, ":multiplier", 106),
              (else_try),
                (lt, ":hours_since_days_defensive_started", 27),
                (assign, ":multiplier", 102),
              (else_try),
                (lt, ":hours_since_days_defensive_started", 31), 
                (assign, ":multiplier", 98),
              (else_try),
                (lt, ":hours_since_days_defensive_started", 34),
                (assign, ":multiplier", 94),
              (else_try),
                (lt, ":hours_since_days_defensive_started", 37),
                (assign, ":multiplier", 90),
              (else_try),
                (lt, ":hours_since_days_defensive_started", 40),
                (assign, ":multiplier", 86),
              (else_try),
                (lt, ":hours_since_days_defensive_started", 43),
                (assign, ":multiplier", 82),
              (else_try),
                (lt, ":hours_since_days_defensive_started", 46),
                (assign, ":multiplier", 79),
              (else_try),
                (lt, ":hours_since_days_defensive_started", 49),
                (assign, ":multiplier", 76),
              (else_try),
                (lt, ":hours_since_days_defensive_started", 52),
                (assign, ":multiplier", 73),
              (else_try),
                (lt, ":hours_since_days_defensive_started", 56),
                (assign, ":multiplier", 70),
              (else_try),
                (lt, ":hours_since_days_defensive_started", 60),
                (assign, ":multiplier", 68),
              (else_try),
                (lt, ":hours_since_days_defensive_started", 66),
                (assign, ":multiplier", 66),
              (else_try),
                (lt, ":hours_since_days_defensive_started", 72),
                (assign, ":multiplier", 64),
              (else_try),
                (lt, ":hours_since_days_defensive_started", 80),
                (assign, ":multiplier", 62),
              (else_try),
                (lt, ":hours_since_days_defensive_started", 90),
                (assign, ":multiplier", 60),
              (else_try),
                (lt, ":hours_since_days_defensive_started", 100),
                (assign, ":multiplier", 58),
              (else_try),
                (assign, ":multiplier", 56),
              (try_end),
		  
              (store_mul, ":enemy_strength_multiplied", ":enemy_strength_near_most_threatened_center", ":multiplier"),
              (val_div, ":enemy_strength_multiplied", 100),
		  
              (try_begin),		  
                (lt, ":marshal_party_strength", ":enemy_strength_multiplied"),
                (assign, ":continue_gathering", 1),
              (try_end),
            (else_try),  
              (eq, ":current_ai_state", sfai_attacking_enemies_around_center),
              (neq, ":most_threatened_center", ":current_ai_object"),
		  
              (assign, ":marshal_is_already_defending_a_center", 0),
              (try_begin),
                (gt, ":marshal_party", 0),
                (party_is_active, ":marshal_party"),
       
                (assign, ":besieged_center", -1),          
                (try_begin),
                  (party_slot_eq, ":marshal_party", slot_party_ai_state, spai_holding_center), #if commander is holding a center
                  (party_get_slot, ":marshal_object", ":marshal_party", slot_party_ai_object), #get commander's ai object (center they are holding)
                  (party_get_battle_opponent, ":besieger_enemy", ":marshal_object"), #get this object's battle opponent
                  (ge, ":besieger_enemy", 0),
                  (assign, ":besieged_center", ":marshal_object"),
                (else_try),              
                  (party_slot_eq, ":marshal_party", slot_party_ai_state, spai_engaging_army), #if commander is engaging an army
                  (party_get_slot, ":marshal_object", ":marshal_party", slot_party_ai_object), #get commander's ai object (army which they engaded)
                  (ge, ":marshal_object", 0), #if commander has an object
                  (neg|is_between, ":marshal_object", centers_begin, centers_end), #if this object is not a center, so it is a party
				  (party_is_active, ":marshal_object"),
                  (party_get_battle_opponent, ":besieged_center", ":marshal_object"), #get this object's battle opponent
                (try_end),

                (eq, ":besieged_center", ":current_ai_object"),
            
                (assign, ":marshal_is_already_defending_a_center", 1),
              (try_end),
                    
              (eq, ":marshal_is_already_defending_a_center", 0),
		  
              (store_mul, ":enemy_strength_multiplied", ":enemy_strength_near_most_threatened_center", 80),
              (val_div, ":enemy_strength_multiplied", 100),
              (lt, ":marshal_party_strength", ":enemy_strength_multiplied"),
              
              (this_or_next|is_between, ":most_threatened_center", walled_centers_begin, walled_centers_end),
              (neq, ":faction_no", "$players_kingdom"),              
              
              (assign, ":start_gathering", 1),
            (try_end),
		
            (this_or_next|eq, ":continue_gathering", 1),
            (eq, ":start_gathering", 1),
		
            (assign, ":action", sfai_gathering_army),
            (assign, ":object", -1),		
            (str_store_party_name, s21, ":most_threatened_center"),
            (str_store_string, s14, "str_we_should_prepare_to_defend_s21_but_we_should_gather_our_forces_until_we_are_strong_enough_to_engage_them"),
            
            (try_begin),
              (eq, ":faction_no", "$players_kingdom"),
              (assign, "$g_gathering_reason", ":most_threatened_center"),
            (try_end),
			
	    #3-DEFENSIVE ACTIONS : RIDE TO BREAK ENEMY SIEGE / DEFEAT ENEMIES NEAR OUR CENTER
		(else_try),
			(party_is_active, ":marshal_party"),
			(is_between, ":most_threatened_center", walled_centers_begin, walled_centers_end),
                        (this_or_next|eq, ":current_ai_state", sfai_default),    #MOTO not going to attack anyway 
                        (this_or_next|eq, ":current_ai_state", sfai_feast),    #MOTO not going to attack anyway (THIS is the emergency to stop feast)
			(ge, ":threat_danger_level", ":target_value_level"),
			(party_slot_ge, ":most_threatened_center", slot_center_is_besieged_by, 0),

			(assign, ":action", sfai_attacking_enemies_around_center),
			(assign, ":object", ":most_threatened_center"),
						
			(str_store_party_name, s21, ":most_threatened_center"),
			(str_store_string, s14, "str_we_should_ride_to_break_the_siege_of_s21"),
			
		#3b - DEFEAT ENEMIES NEAR CENTER - similar to above, but a different string
		(else_try),
			(party_is_active, ":marshal_party"),
                        (this_or_next|eq, ":current_ai_state", sfai_default),    #MOTO not going to attack anyway 
                        (this_or_next|eq, ":current_ai_state", sfai_feast),    #MOTO not going to attack anyway (THIS is the emergency to stop feast)                
			(ge, ":threat_danger_level", ":target_value_level"),
			(is_between, ":most_threatened_center", villages_begin, villages_end),
		
			(assign, ":action", sfai_attacking_enemies_around_center),
			(assign, ":object", ":most_threatened_center"),
			(str_store_party_name, s21, ":most_threatened_center"),
			(str_store_string, s14, "str_we_should_ride_to_defeat_the_enemy_gathered_near_s21"),
				
		#4-DEMOBILIZATION
		#Let vassals attend their own business
		(else_try),
			(this_or_next|eq, ":current_ai_state", sfai_gathering_army), 				
			(this_or_next|eq, ":current_ai_state", sfai_attacking_center),
			(eq, ":current_ai_state", sfai_raiding_village),

			(ge, ":hours_since_last_faction_rest", ":campaign_hour_limit"), #Effected by ratio of vassals
			(ge, ":hours_at_current_state", 24),
			
			#Ozan : I am adding some codes here because sometimes armies demobilize during last seconds of an important event like taking a castle, ext.
			(assign, ":there_is_an_important_situation", 0),
			(try_begin), #do not demobilize during taking a castle/town (fighting in the castle)
				(is_between, ":current_ai_object", walled_centers_begin, walled_centers_end),
				(party_get_battle_opponent, ":besieger_party", ":current_ai_object"),
				(party_is_active, ":besieger_party"),
				(store_faction_of_party, ":besieger_faction", ":besieger_party"),
				(this_or_next|eq, ":besieger_faction", ":faction_no"),
				(eq, ":besieger_faction", "fac_player_faction"),
				(assign, ":there_is_an_important_situation", 1),
			(else_try), #do not demobilize during besieging a siege (holding around castle)
				(is_between, ":current_ai_object", walled_centers_begin, walled_centers_end),
				(party_get_slot, ":besieger_party", ":current_ai_object", slot_center_is_besieged_by),
				(party_is_active, ":besieger_party"),
				(store_faction_of_party, ":besieger_faction", ":besieger_party"),
				(this_or_next|eq, ":besieger_faction", ":faction_no"),
				(eq, ":besieger_faction", "fac_player_faction"),		  
				(assign, ":there_is_an_important_situation", 1),
			(else_try), #do not demobilize during raiding a village (holding around village)
				(is_between, ":current_ai_object", centers_begin, centers_end),
				(neg|is_between, ":current_ai_object", walled_centers_begin, walled_centers_end),		  
				(party_slot_eq, ":current_ai_object", slot_village_state, svs_being_raided),
				(assign, ":there_is_an_important_situation", 1),
			(try_end),
			
			(eq, ":there_is_an_important_situation", 0),
			#end addition ozan
						
			(assign, reg7, ":hours_since_last_faction_rest"),
			(assign, reg8, ":campaign_hour_limit"),
		
			(str_store_string, s14, "str_this_offensive_needs_to_wind_down_soon_so_the_vassals_can_attend_to_their_own_business"),		
			(assign, ":action", sfai_default),
			(assign, ":object", -1),
			
		#6-GATHERING BECAUSE OF NO REASON
		#Start to gather the army
		(else_try),
			(party_is_active, ":marshal_party"),
			(eq, ":at_peace_with_everyone", 0),
			
			
			(eq, ":current_ai_state", sfai_default),
			(ge, ":hours_since_last_offensive", 60),
			(lt, ":hours_since_last_faction_rest", 120),
			
			#There should not be a center as a precondition for attack	
			#Otherwise, we are unlikely to have a situation in which the army gathers, but does nothing -- which is important to have for role-playing purposes
			
			(assign, ":action", sfai_gathering_army),
			(assign, ":object", -1),	
			(str_store_string, s14, "str_it_is_time_to_go_on_the_offensive_and_we_must_first_assemble_the_army"),
		
            (try_begin),
              (eq, ":faction_no", "$players_kingdom"),
              (assign, "$g_gathering_reason", -1),
            (try_end),

		#7-OFFENSIVE ACTIONS : CONTINUE GATHERING
		(else_try),		
			(party_is_active, ":marshal_party"),
			(eq, ":current_ai_state", sfai_gathering_army),
			(eq, ":at_peace_with_everyone", 0),

			(lt, ":hours_at_current_state", 54), #gather army for 54 hours
			
			(lt, ":ratio_of_vassals_assembled", 12),

			(str_store_string, s14, "str_we_must_continue_to_gather_the_army_before_we_ride_forth_on_an_offensive_operation"),
			(assign, ":action", sfai_gathering_army),
			(assign, ":object", -1),

		#7-OFFENSIVE ACTIONS PART 2 : CONTINUE GATHERING
		(else_try),
		    (assign, ":minimum_possible_attackable_target_value_level", 50),
			(eq, ":at_peace_with_everyone", 0),

            (try_begin), #agressive marshal            
			  (troop_get_slot, ":reputation", ":troop_no", slot_lord_reputation_type),
			  (this_or_next|eq, ":reputation", lrep_martial),
			  (this_or_next|eq, ":reputation", lrep_quarrelsome),
			  (eq, ":reputation", lrep_selfrighteous),
			  (val_mul, ":minimum_possible_attackable_target_value_level", 9),
			  (val_div, ":minimum_possible_attackable_target_value_level", 10),
            (try_end),		              

			(party_is_active, ":marshal_party"),
			(eq, ":current_ai_state", sfai_gathering_army),
								
			(try_begin),
				(lt, ":hours_at_current_state", 6),
				(assign, ":minimum_needed_target_value_level", 1500),
			(else_try),
				(lt, ":hours_at_current_state", 10),
				(assign, ":minimum_needed_target_value_level", 1000),
			(else_try),  
		        (lt, ":hours_at_current_state", 14),
		        (assign, ":minimum_needed_target_value_level", 720),
			(else_try),  
				(lt, ":hours_at_current_state", 18),
				(assign, ":minimum_needed_target_value_level", 480),
			(else_try),  
				(lt, ":hours_at_current_state", 22),
				(assign, ":minimum_needed_target_value_level", 360),
			(else_try),  
				(lt, ":hours_at_current_state", 26),
				(assign, ":minimum_needed_target_value_level", 240),
			(else_try),  
				(lt, ":hours_at_current_state", 30),
				(assign, ":minimum_needed_target_value_level", 180),
			(else_try),  
				(lt, ":hours_at_current_state", 34),
				(assign, ":minimum_needed_target_value_level", 120),
			(else_try),  
				(lt, ":hours_at_current_state", 38),
				(assign, ":minimum_needed_target_value_level", 100),
			(else_try),  
				(lt, ":hours_at_current_state", 42),
				(assign, ":minimum_needed_target_value_level", 80),
			(else_try),  
				(lt, ":hours_at_current_state", 46),
				(assign, ":minimum_needed_target_value_level", 65),
			(else_try),  
				(lt, ":hours_at_current_state", 50),
				(assign, ":minimum_needed_target_value_level", 55),
			(else_try),	
				(assign, ":minimum_needed_target_value_level", ":minimum_possible_attackable_target_value_level"),
			(try_end),  

            (try_begin), #agressive marshal            
			  (troop_get_slot, ":reputation", ":troop_no", slot_lord_reputation_type),
			  (this_or_next|eq, ":reputation", lrep_martial),
			  (this_or_next|eq, ":reputation", lrep_quarrelsome),
			  (eq, ":reputation", lrep_selfrighteous),
			  (val_mul, ":minimum_needed_target_value_level", 9),
			  (val_div, ":minimum_needed_target_value_level", 10),
            (try_end),		  
						
			(le, ":target_value_level", ":minimum_needed_target_value_level"),
			(le, ":hours_at_current_state", 54),
		
			(str_store_string, s14, "str_we_have_assembled_some_vassals"),
			(assign, ":action", sfai_gathering_army),
			(assign, ":object", -1),
				
		#8-ATTACK AN ENEMY CENTER case 1, reconnaissance against walled center
		#(else_try),
			#(party_is_active, ":marshal_party"),
			#(neq, ":current_ai_state", sfai_default),
			#(neq, ":current_ai_state", sfai_feast),
			#(is_between, ":center_to_attack", walled_centers_begin, walled_centers_end),

			#(store_sub, ":faction_recce_slot", ":faction_no", kingdoms_begin),
			#(val_add, ":faction_recce_slot", slot_center_last_reconnoitered_by_faction_time),
			#(store_current_hours, ":hours_since_last_recon"),			
			#(party_get_slot, ":last_recon_time", ":center_to_attack", ":faction_recce_slot"), 
			#(val_sub, ":hours_since_last_recon", ":last_recon_time"),
			#(this_or_next|eq, ":last_recon_time", 0),
			#(gt, ":hours_since_last_recon", 96),
						
		    #(assign, ":action", sfai_attacking_center),
			#(assign, ":object", ":center_to_attack"),
			#(str_store_string, s14, "str_we_are_conducting_recce"),
			
		#8-ATTACK AN ENEMY CENTER case 2, reconnaissance against village
		#(else_try),  
			#(party_is_active, ":marshal_party"),
			#(neq, ":current_ai_state", sfai_default),
			#(neq, ":current_ai_state", sfai_feast),
			#(is_between, ":center_to_attack", villages_begin, villages_end),

			#(store_sub, ":faction_recce_slot", ":faction_no", kingdoms_begin),
			#(val_add, ":faction_recce_slot", slot_center_last_reconnoitered_by_faction_time),
			#(store_current_hours, ":hours_since_last_recon"),
			#(party_get_slot, ":last_recon_time", ":center_to_attack", ":faction_recce_slot"), 
			#(val_sub, ":hours_since_last_recon", ":last_recon_time"),
			#(this_or_next|eq, ":last_recon_time", 0),
			#(gt, ":hours_since_last_recon", 96),

			
			#(assign, ":action", sfai_raiding_village),
			#(assign, ":object", ":center_to_attack"),
			#(str_store_string, s14, "str_we_are_conducting_recce"),
		(else_try),
			(party_is_active, ":marshal_party"),
			(neq, ":current_ai_state", sfai_default),
			(neq, ":current_ai_state", sfai_feast),
			
			(assign, ":center_to_attack", ":center_to_attack_only_marshal_and_followers"),
			
			(is_between, ":center_to_attack", walled_centers_begin, walled_centers_end),
			
			(ge, ":target_value_level", ":minimum_possible_attackable_target_value_level"),
						
		    (assign, ":action", sfai_attacking_center),
			(assign, ":object", ":center_to_attack"),
			(str_store_string, s14, "str_we_believe_the_fortress_will_be_worth_the_effort_to_take_it"),
		(else_try),
			(party_is_active, ":marshal_party"),
			(neq, ":current_ai_state", sfai_default),
			(neq, ":current_ai_state", sfai_feast),
			
			(assign, ":center_to_attack", ":center_to_attack_only_marshal_and_followers"),
			
			(is_between, ":center_to_attack", villages_begin, villages_end),
			
			(ge, ":target_value_level", ":minimum_possible_attackable_target_value_level"),
		
			(assign, ":action", sfai_raiding_village),
			(assign, ":object", ":center_to_attack"),
			(str_store_string, s14, "str_we_shall_leave_a_fiery_trail_through_the_heart_of_the_enemys_lands_targeting_the_wealthy_settlements_if_we_can"),
		
		#9 -- DISBAND THE ARMY
		(else_try),
			(eq, ":current_ai_state", sfai_gathering_army),			

			(str_store_string, s14, "str_the_army_will_be_disbanded_because_we_have_been_waiting_too_long_without_a_target"),

			(assign, ":action", sfai_default),
			(assign, ":object", -1),
		#OFFENSIVE OPERATIONS END

		#FEAST-RELATED OPERATIONS BEGIN
		#10-CONCLUDE CURRENT FEAST
		(else_try),
			(eq, ":current_ai_state", sfai_feast),
			(gt, ":hours_at_current_state", 72),
		
			(assign, ":action", sfai_default),
			(assign, ":object", -1),		
			(str_store_string, s14, "str_it_is_time_for_the_feast_to_conclude"),

		#11-CONTINE FEAST UNLESS THERE IS AN EMERGENCY
		(else_try),
			(eq, ":current_ai_state", sfai_feast),
			(le, ":hours_at_current_state", 72),
			
			(assign, ":action", sfai_feast),
			(assign, ":object", ":current_ai_object"),		
			(str_store_string, s14, "str_we_should_continue_the_feast_unless_there_is_an_emergency"),
		
		#12-HOLD A FEAST BECAUSE THE PLAYER WANTS TO ORGANIZE ONE
		(else_try),
			(check_quest_active, "qst_organize_feast"),
			(eq, "$players_kingdom", ":faction_no"),
		
			(quest_get_slot, ":target_center", "qst_organize_feast", slot_quest_target_center),
			
			(assign, ":action", sfai_feast),
			(assign, ":object", ":target_center"),		
			(str_store_string, s14, "str_you_had_wished_to_hold_a_feast"),
		
		#13-HOLD A FEAST BECAUSE FEMALE PLAYER SCHEDULED TO GET MARRIED
		(else_try),
			(check_quest_active, "qst_wed_betrothed_female"),
				 
			(quest_get_slot, ":groom", "qst_wed_betrothed_female", slot_quest_giver_troop),
			(troop_slot_eq, ":groom", slot_troop_prisoner_of_party, -1),
		
			(store_faction_of_troop, ":groom_faction", ":groom"),
			(eq, ":groom_faction", ":faction_no"),
				 
			(faction_get_slot, ":faction_leader", ":groom_faction", slot_faction_leader),
				 
			(assign, ":location_feast", -1),
			(try_for_range, ":possible_location", walled_centers_begin, walled_centers_end),
			   (eq, ":location_feast", -1),
			    (party_slot_eq, ":possible_location", slot_town_lord, ":groom"),
			    (party_slot_ge, ":possible_location", slot_center_is_besieged_by, 0),
			    (assign, ":location_feast", ":possible_location"),
			(try_end),
			
			(try_for_range, ":possible_location", walled_centers_begin, walled_centers_end),
				(eq, ":location_feast", -1),
				(party_slot_eq, ":possible_location", slot_town_lord, ":faction_leader"),
				(party_slot_ge, ":possible_location", slot_center_is_besieged_by, 0),
				(assign, ":location_feast", ":possible_location"),
			(try_end),
		 
			(is_between, ":location_feast", walled_centers_begin, walled_centers_end),

			(assign, ":action", sfai_feast),
			(assign, ":object", ":location_feast"),		
			(str_store_string, s14, "str_your_wedding_day_approaches_my_lady"),
		
		#14-HOLD A FEAST BECAUSE A MALE CHARACTER WANTS TO GET MARRIED
		(else_try),
			(check_quest_active, "qst_wed_betrothed"),
			(neg|quest_slot_ge, "qst_wed_betrothed", slot_quest_expiration_days, 362),
		
			(quest_get_slot, ":bride", "qst_wed_betrothed", slot_quest_target_troop),
			(call_script, "script_get_kingdom_lady_social_determinants", ":bride"),
			(assign, ":feast_host", reg0),
			(store_faction_of_troop, ":feast_host_faction", ":feast_host"),
			(eq, ":feast_host_faction", ":faction_no"),
		
			(troop_slot_eq, ":feast_host", slot_troop_prisoner_of_party, -1),
			(assign, ":wedding_venue", reg1),
		
			(is_between, ":wedding_venue", centers_begin, centers_end),
			(party_slot_eq, ":wedding_venue", slot_center_is_besieged_by, -1),
		
			(assign, ":action", sfai_feast),
			(assign, ":object", ":wedding_venue"),		
			(str_store_string, s14, "str_your_wedding_day_approaches"),
		
		#15-HOLD A FEAST BECAUSE AN NPC WANTS TO GET MARRIED
		(else_try),	
            (ge, ":hours_since_last_feast_start", 192), #If at least eight days past last feast start time
		
			(assign, ":location_feast", -1),
		
			(try_for_range, ":kingdom_lady", kingdom_ladies_begin, kingdom_ladies_end),
				(troop_get_slot, ":groom", ":kingdom_lady", slot_troop_betrothed),
				(gt, ":groom", 0), #not the player

				(store_faction_of_troop, ":lady_faction", ":kingdom_lady"),
				(store_faction_of_troop, ":groom_faction", ":groom"),
				
				(try_begin), #The groom checks if he wants to continue or break off relations. This causes actions, rather than just returns a value, so it probably should be moved elsewhere
					(troop_slot_ge, ":groom", slot_troop_prisoner_of_party, 0),		
				(else_try),
					(neq, ":groom_faction", ":lady_faction"),
					(neq, ":groom_faction", "fac_player_faction"),
					(call_script, "script_courtship_event_lady_break_relation_with_suitor", ":kingdom_lady", ":groom"),
				(else_try),
		            (eq, ":lady_faction", ":faction_no"),
		            (store_current_hours, ":hours_since_betrothal"),
		            (troop_get_slot, ":betrothal_time", ":kingdom_lady", slot_troop_betrothal_time),
		            (val_sub, ":hours_since_betrothal", ":betrothal_time"),
		            (ge, ":hours_since_betrothal", 719), #30 days
							
					(call_script, "script_get_kingdom_lady_social_determinants", ":kingdom_lady"), 
					(assign, ":wedding_venue", reg1),
				
		            (assign, ":location_feast", ":wedding_venue"),
		            (assign, ":final_bride", ":kingdom_lady"),
		            (assign, ":final_groom", ":groom"),
				(try_end),	
			(try_end),
		
			(ge, ":location_feast", centers_begin),
				 
			(assign, ":action", sfai_feast),
			(assign, ":object", ":location_feast"),
				
			(str_store_troop_name, s22, ":final_bride"),
			(str_store_troop_name, s23, ":final_groom"),		
			(str_store_string, s14, "str_s22_and_s23_wish_to_marry"),

		#16-HOLD A FEAST ANYWAY
		(else_try),
		    (neq, ":faction_no", "fac_dark_knights"), # Disable random feasts for Dark Knights
			(eq, ":current_ai_state", sfai_default),
            (gt, ":hours_since_last_feast_start", 240), #If at least 10 days past after last feast. (added by ozan)

			(assign, ":location_high_score", 0),
			(assign, ":location_feast", -1),
        
			(try_for_range, ":location", walled_centers_begin, walled_centers_end),
				(store_faction_of_party, ":location_faction", ":location"),
				(eq, ":location_faction", ":faction_no"),

				(try_begin),
			        (neg|party_slot_eq, ":location", slot_village_state, svs_under_siege),
		            (party_get_slot, ":location_lord", ":location", slot_town_lord),
		            (is_between, ":location_lord", active_npcs_begin, active_npcs_end),
		            (troop_get_slot, ":location_score", ":location_lord", slot_troop_renown),
		            (store_random_in_range, ":random", 0, 1000), #will probably be king or senior lord
		            (val_add, ":location_score", ":random"),
		            (gt, ":location_score", ":location_high_score"),
		            (assign, ":location_high_score", ":location_score"),
		            (assign, ":location_feast", ":location"),				
				(else_try), #do not start new feasts if any place is under siege or being raided
		            (this_or_next|party_slot_eq, ":location", slot_village_state, svs_under_siege),
						(party_slot_eq, ":location", slot_village_state, svs_being_raided),
		            (assign, ":location_high_score", 9999),
		            (assign, ":location_feast", -1),
				(try_end),
			(try_end),

			(is_between, ":location_feast", walled_centers_begin, walled_centers_end),
			(party_get_slot, ":feast_host", ":location_feast", slot_town_lord),
			(troop_slot_eq, ":feast_host", slot_troop_prisoner_of_party, -1),
		
			(assign, ":action", sfai_feast),
			(assign, ":object", ":location_feast"),		
			(str_store_string, s14, "str_it_has_been_a_long_time_since_the_lords_of_the_realm_gathered_for_a_feast"),	
		
		#17-DO NOTHING
		(else_try),
			(neq, ":current_ai_state", sfai_default),
		
			(assign, ":action", sfai_default),
			(assign, ":object", -1),		
			(str_store_string, s14, "str_the_circumstances_which_led_to_this_decision_no_longer_apply_so_we_should_stop_and_reconsider_shortly"),	
	
		#18-DO NOTHING
		(else_try),
			(eq, ":current_ai_state", sfai_default),

			(eq, ":at_peace_with_everyone", 1),
				
		    (assign, ":action", sfai_default),
		    (assign, ":object", -1),		
			(str_store_string, s14, "str_we_are_currently_at_peace"),		
		(else_try),
			(eq, ":current_ai_state", sfai_default),
			(faction_slot_eq, ":faction_no", slot_faction_marshall, -1),				
		    (assign, ":action", sfai_default),
		    (assign, ":object", -1),		
			(str_store_string, s14, "str_we_are_waiting_for_selection_of_marshal"),		
		
		(else_try),
			(eq, ":current_ai_state", sfai_default),
								
		    (assign, ":action", sfai_default),
		    (assign, ":object", -1),		
			(str_store_string, s14, "str_the_vassals_still_need_time_to_attend_to_their_own_business"),		
		(try_end),
				
		(assign, reg0, ":action"),
		(assign, reg1, ":object"),		
	]),
  
 	(
	"faction_last_reconnoitered_center", #This is called from within decide_faction_ai, or from 
	[
		(store_script_param, ":faction_no", 1), 
		(store_script_param, ":center_no", 2), 
		
		(store_sub, ":faction_recce_slot", ":faction_no", kingdoms_begin),
		(val_add, ":faction_recce_slot", slot_center_last_reconnoitered_by_faction_time),
		(store_current_hours, ":hours_since_last_recon"),
		(party_get_slot, ":last_recon_time", ":center_no", ":faction_recce_slot"), 
		
		(try_begin),
			(lt, ":last_recon_time", 1),
			(assign, ":hours_since_last_recon", 1000),
		(else_try),	
			(val_sub, ":hours_since_last_recon", ":last_recon_time"),
		(try_end),
 
		(assign, reg0, ":hours_since_last_recon"),
		(assign, reg1, ":last_recon_time"),		
	]),
 	
 	(
	"reduce_exact_number_to_estimate",
	#This is used to simulate limited intelligence
	#It is roughly analogous to the descriptive strings which the player will receive from alarms
	#Information is presumed to be accurate for four days
	#This is obviously cheating for the AI, as the AI will have exact info for four days, and no info at all after that.
	#It would be fairly easy to log the strength at a center when it is scouted, if we want, but I have not done that at this point,
	#The AI also has a hive mind -- ie, each party knows what its allies are thinking. In this, AI factions have an advantage over the player
	#It would be a simple matter to create a set of arrays in which each party's knowledge is individually updated, but that would also take up a lot of data space
	
	[
		(store_script_param, ":exact_number", 1), 
		
		(try_begin),
			(lt, ":exact_number", 500),
			(assign, ":estimate", 0),
		(else_try),
			(lt, ":exact_number", 1000),
			(assign, ":estimate", 750),
		(else_try),
			(lt, ":exact_number", 2000),
			(assign, ":estimate", 1500),
		(else_try),
			(lt, ":exact_number", 4000),
			(assign, ":estimate", 3000),
		(else_try),
			(lt, ":exact_number", 8000),
			(assign, ":estimate", 6000),
		(else_try),
			(lt, ":exact_number", 16000),
			(assign, ":estimate", 12000),
		(else_try),
			(assign, ":estimate", 24000),
		(try_end),
				
		(assign, reg0, ":estimate"),		
	]),

   #script_calculate_castle_prosperities_by_using_its_villages
 	(
	"calculate_castle_prosperities_by_using_its_villages", #This is called from within decide_faction_ai, or from 
	[	  	
	  (try_for_range, ":cur_castle", castles_begin, castles_end),	  
	    (assign, ":total_prosperity", 0),
	    (assign, ":total_villages", 0),
	    
	    (try_for_range, ":cur_village", villages_begin, villages_end),	  
	      (party_get_slot, ":bound_center", ":cur_village", slot_village_bound_center),
	      (eq, ":cur_castle", ":bound_center"),
	      
	      (party_get_slot, ":village_prosperity", ":cur_village", slot_town_prosperity),
	      
	      (val_add, ":total_prosperity", ":village_prosperity"),
	      (val_add, ":total_villages", 1),
	    (try_end),
	    
	    (try_begin),
	      (store_div, ":castle_prosperity", ":total_prosperity", ":total_villages"),
	    (else_try),  
	      (assign, ":castle_prosperity", 50),
	    (try_end),
	    
	    (party_set_slot, ":cur_castle", slot_town_prosperity, ":castle_prosperity"),
	  (try_end),
	]),
      
   #script_initialize_tavern_variables
   (
   "initialize_tavern_variables",
   [
     (assign, "$g_main_attacker_agent", 0),
     (assign, "$g_attacker_drawn_weapon", 0),
     (assign, "$g_start_belligerent_drunk_fight", 0),
     (assign, "$g_start_hired_assassin_fight", 0),
     (assign, "$g_belligerent_drunk_leaving", 0),   
   ]),
   
   #script_prepare_alley_to_fight
   (
   "prepare_alley_to_fight",
   [
     (party_get_slot, ":scene_no", "$current_town", slot_town_alley),
     
     #(store_faction_of_party, ":faction_no", "$current_town"),     
     
     (modify_visitors_at_site, ":scene_no"),
     
     (reset_visitors),
     (set_visitor, 0, "trp_player"),
     
     #(try_begin),
     #  (eq, ":faction_no", "fac_kingdom_1"), #swadian
     #  (assign, ":bandit_troop", "trp_steppe_bandit"),
     #(else_try),
     #  (eq, ":faction_no", "fac_kingdom_2"), #vaegir
     #  (assign, ":bandit_troop", "trp_taiga_bandit"),
     #(else_try),
     #  (eq, ":faction_no", "fac_kingdom_3"), #khergit
     #  (assign, ":bandit_troop", "trp_mountain_bandit"),
     #(else_try),
     #  (eq, ":faction_no", "fac_kingdom_4"), #nord
     #  (assign, ":bandit_troop", "trp_sea_raider"),
     #(else_try),
     #  (eq, ":faction_no", "fac_kingdom_5"), #rhodok
     #  (assign, ":bandit_troop", "trp_forest_bandit"),
     #(else_try),
     #  (eq, ":faction_no", "fac_kingdom_6"), #sarradin
     #  (assign, ":bandit_troop", "trp_desert_bandit"),
     #(try_end),  
               
     #(set_visitor, 3, ":bandit_troop"),
     (set_visitor, 3, "trp_bandit"),

     (assign, "$talked_with_merchant", 0),
     (set_jump_mission, "mt_alley_fight"),
     (jump_to_scene, ":scene_no"),
     (change_screen_mission),         
   ]),

   #script_prepare_town_to_fight
   (
   "prepare_town_to_fight",
   [
     (str_store_party_name_link, s9, "$g_starting_town"),
     (str_store_string, s2, "str_save_town_from_bandits"),        
     (call_script, "script_start_quest", "qst_save_town_from_bandits", "$g_talk_troop"),
  
     (assign, "$g_mt_mode", tcm_default),
     (store_faction_of_party, ":town_faction", "$current_town"),
     (faction_get_slot, ":tier_2_troop", ":town_faction", slot_faction_tier_3_troop),
     (faction_get_slot, ":tier_3_troop", ":town_faction", slot_faction_tier_3_troop),
     (faction_get_slot, ":tier_4_troop", ":town_faction", slot_faction_tier_4_troop),
     
     (party_get_slot, ":town_scene", "$current_town", slot_town_center),
     (modify_visitors_at_site, ":town_scene"),
     (reset_visitors),
    
     #people spawned at #32, #33, #34, #35, #36, #37, #38 and #39 are town walkers.
     (try_begin),
       #(eq, "$town_nighttime", 0),
       (try_for_range, ":walker_no", 0, num_town_walkers),
         (store_add, ":troop_slot", slot_center_walker_0_troop, ":walker_no"),
         (party_get_slot, ":walker_troop_id", "$current_town", ":troop_slot"),
         (gt, ":walker_troop_id", 0),                        
         (store_add, ":entry_no", town_walker_entries_start, ":walker_no"),
         (set_visitor, ":entry_no", ":walker_troop_id"),
       (try_end),  
     (try_end),  

     #guards will be spawned at #25, #26 and #27 
     (set_visitors, 25, ":tier_2_troop", 1),
     (set_visitors, 26, ":tier_3_troop", 1),
     (set_visitors, 27, ":tier_4_troop", 1),
    
     (set_visitors, 10, "trp_looter", 1),
     (set_visitors, 11, "trp_bandit", 1),
     (set_visitors, 12, "trp_looter", 1),    

     (store_faction_of_party, ":starting_town_faction", "$g_starting_town"),    
     (try_begin),
       (eq, ":starting_town_faction", "fac_kingdom_1"),
       (assign, ":troop_of_merchant", "trp_swadian_merchant"),
       #(assign, ":troop_of_bandit", "trp_forest_bandit"),
     (else_try),  
       (eq, ":starting_town_faction", "fac_kingdom_2"),
       (assign, ":troop_of_merchant", "trp_vaegir_merchant"),
       #(assign, ":troop_of_bandit", "trp_mountain_bandit"),
     (else_try),                   
       (eq, ":starting_town_faction", "fac_kingdom_3"),
       (assign, ":troop_of_merchant", "trp_khergit_merchant"),
       #(assign, ":troop_of_bandit", "trp_steppe_bandit"),
     (else_try),  
       (eq, ":starting_town_faction", "fac_kingdom_4"),
       (assign, ":troop_of_merchant", "trp_nord_merchant"),
       #(assign, ":troop_of_bandit", "trp_sea_raider"),
     (else_try),  
       (eq, ":starting_town_faction", "fac_kingdom_5"),
       (assign, ":troop_of_merchant", "trp_rhodok_merchant"),
       #(assign, ":troop_of_bandit", "trp_mountain_bandit"),
     (else_try),  
       (eq, ":starting_town_faction", "fac_kingdom_6"),
       (assign, ":troop_of_merchant", "trp_sarranid_merchant"),
       #(assign, ":troop_of_bandit", "trp_desert_bandit"),
     (try_end),
     (str_store_troop_name, s10, ":troop_of_merchant"),
    
     (set_visitors, 24, "trp_looter", 1),
     (set_visitors, 2, "trp_looter", 2),
     (set_visitors, 4, "trp_looter", 1),
     (set_visitors, 5, "trp_looter", 2),
     (set_visitors, 6, "trp_looter", 1),
     (set_visitors, 7, "trp_looter", 1),
    
     (set_visitors, 3, ":troop_of_merchant", 1),    
    
     (set_jump_mission,"mt_town_fight"),
     (jump_to_scene, ":town_scene"),
     (change_screen_mission),   
   ]),
  
   (
   "change_player_right_to_rule",
   [
     (store_script_param_1, ":right_to_rule_dif"),
     (val_add, "$player_right_to_rule", ":right_to_rule_dif"),
     (val_clamp, "$player_right_to_rule", 0, 100),
     (try_begin),
       (gt, ":right_to_rule_dif", 0),
       (display_message, "@You gain right to rule."),
     (else_try),
       (lt, ":right_to_rule_dif", 0),
       (display_message, "@You lose right to rule."),
     (try_end),
   ]),   
   
   ("indict_lord_for_treason",#originally included in simple_triggers. Needed to be moved here to allow player to indict
   [
    (store_script_param, ":troop_no", 1),
    (store_script_param, ":faction", 2),
	
	(troop_get_type, reg4, ":troop_no"),
	  
	(try_for_range, ":center", centers_begin, centers_end), #transfer properties to liege
		(party_slot_eq, ":center", slot_town_lord, ":troop_no"),
		(party_set_slot, ":center", slot_town_lord, stl_unassigned), 
	(try_end),
	
	(faction_get_slot, ":faction_leader", ":faction", slot_faction_leader),
	(call_script, "script_troop_get_relation_with_troop", ":troop_no", ":faction_leader"),
	(assign, ":liege_to_lord_relation", reg0),
	(store_sub, ":base_relation_modifier", -150, ":liege_to_lord_relation"), 
	(val_div, ":base_relation_modifier", 40),#-1 at -100, -2 at -70, -3 at -30,etc. 
	(val_min, ":base_relation_modifier", -1),

	#Indictments, cont: Influence relations
	(try_for_range, ":active_npc", active_npcs_begin, active_npcs_end), #this effects all lords in all factions
		(store_faction_of_troop, ":active_npc_faction", ":active_npc"),
		(eq, ":faction", ":active_npc_faction"),

		(call_script, "script_troop_get_family_relation_to_troop", ":troop_no", ":active_npc"),
		(assign, ":family_relation", reg0),

		(assign, ":relation_modifier", ":base_relation_modifier"),
		(try_begin),
			(gt, ":family_relation", 1),
			(store_div, ":family_multiplier", reg0, 3),
			(val_sub, ":relation_modifier", ":family_multiplier"),
		(try_end),
		
		(lt, ":relation_modifier", 0),
		
		(call_script, "script_troop_change_relation_with_troop", ":faction_leader", ":active_npc", ":relation_modifier"),
		(val_add, "$total_indictment_changes", ":relation_modifier"),
		(try_begin),
			(eq, "$cheat_mode", 1),
			(str_store_troop_name, s17, ":active_npc"),
			(str_store_troop_name, s18, ":faction_leader"),

			(assign, reg3, ":relation_modifier"),
			(display_message, "str_trial_influences_s17s_relation_with_s18_by_reg3"),
		(try_end),
	(try_end),

	#Indictments, cont: Check for other factions
	(assign, ":new_faction", "fac_outlaws"),
	(try_begin),
		(eq, ":troop_no", "trp_player"),
		(assign, ":new_faction", 0), #kicked out of faction
	(else_try),	
		(call_script, "script_lord_find_alternative_faction", ":troop_no"),		
		(assign, ":new_faction", reg0),
	(try_end),
	  
	#Indictments, cont: Finalize where the lord goes
	(try_begin),
		(is_between, ":new_faction", kingdoms_begin, kingdoms_end),
		
		
		(try_begin),
			(ge, "$cheat_mode", 1),
			(str_store_troop_name, s4, ":troop_no"),
			(display_message, "@{!}DEBUG - {s4} faction changed in indictment"), 
		(try_end),		
		
		(call_script, "script_change_troop_faction", ":troop_no", ":new_faction"),
		(try_begin), #new-begin
		  (neq, ":new_faction", "fac_player_supporters_faction"),
		  (troop_slot_eq, ":troop_no", slot_troop_occupation, slto_inactive), 
		  (troop_set_slot, ":troop_no", slot_troop_occupation, slto_kingdom_hero), 
		(try_end), #new-end
		(str_store_faction_name, s10, ":new_faction"),
		(str_store_string, s11, "str_with_the_s10"),
	(else_try),
		(neq, ":troop_no", "trp_player"),
		(call_script, "script_change_troop_faction", ":troop_no", "fac_outlaws"),
		(str_store_string, s11, "str_outside_calradia"),
	(else_try),
		(eq, ":troop_no", "trp_player"),
		(call_script, "script_player_leave_faction", 1),
	(try_end),
	  
	#Indictments, cont: Set up string
	(try_begin),
		(eq, ":troop_no", "trp_player"),
		(str_store_string, s9, "str_you_have_been_indicted_for_treason_to_s7_your_properties_have_been_confiscated_and_you_would_be_well_advised_to_flee_for_your_life"),
	(else_try),	
		(str_store_troop_name, s4, ":troop_no"),
		(str_store_faction_name, s5, ":faction"),
		(str_store_troop_name, s6, ":faction_leader"),
		
		(troop_get_type, reg4, ":troop_no"),
		(str_store_string, s9, "str_by_order_of_s6_s4_of_the_s5_has_been_indicted_for_treason_the_lord_has_been_stripped_of_all_reg4herhis_properties_and_has_fled_for_reg4herhis_life_he_is_rumored_to_have_gone_into_exile_s11"),
	(try_end),
	(display_message, "@{!}{s9}"),
	  
	#Indictments, cont: Remove party 
	(troop_get_slot, ":led_party", ":troop_no", slot_troop_leaded_party),
	(try_begin),
		(party_is_active, ":led_party"),
		(neq, ":led_party", "p_main_party"),
		(remove_party, ":led_party"),
		(troop_set_slot, ":troop_no", slot_troop_leaded_party, -1),
	(try_end),
				
	(try_begin),
		(eq, "$cheat_mode", 1),
		(this_or_next|eq, ":faction", "$players_kingdom"),
			(eq, ":new_faction", "$players_kingdom"),
		(call_script, "script_add_notification_menu", "mnu_notification_treason_indictment", ":troop_no", ":faction"),
	(try_end),   
   ]),


  # script_give_center_to_faction_aux
  # Input: arg1 = center_no, arg2 = faction
  ("give_center_to_faction_while_maintaining_lord",
    [
      (store_script_param_1, ":center_no"),
      (store_script_param_2, ":faction_no"),

      (store_faction_of_party, ":old_faction", ":center_no"),
      (party_set_slot, ":center_no", slot_center_ex_faction, ":old_faction"),
      (party_set_faction, ":center_no", ":faction_no"),

      (try_begin),
        (party_slot_eq, ":center_no", slot_party_type, spt_village),
        (party_get_slot, ":farmer_party", ":center_no", slot_village_farmer_party),
        (gt, ":farmer_party", 0),
        (party_is_active, ":farmer_party"),
        (party_set_faction, ":farmer_party", ":faction_no"),
      (try_end),

      (call_script, "script_update_faction_notes", ":faction_no"),
      (call_script, "script_update_center_notes", ":center_no"),

      (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_while_maintaining_lord", ":other_center", ":faction_no"),
      (try_end),
  ]),   

  # script_check_concilio_calradi_achievement  
  ("check_concilio_calradi_achievement",
  [
   (try_begin),
     (eq, "$players_kingdom", "fac_player_supporters_faction"),
     (faction_get_slot, ":player_faction_king", "fac_player_supporters_faction", slot_faction_leader),
     (eq, ":player_faction_king", "trp_player"),
     (assign, ":number_of_vassals", 0),
     (try_for_range, ":cur_troop", active_npcs_begin, active_npcs_end),
       (troop_slot_eq, ":cur_troop", slot_troop_occupation, slto_kingdom_hero),
       (store_faction_of_troop, ":cur_faction", ":cur_troop"),
       (eq, ":cur_faction", "fac_player_supporters_faction"),
       (val_add, ":number_of_vassals", 1),
     (try_end),
     (ge, ":number_of_vassals", 3),
     (unlock_achievement, ACHIEVEMENT_CONCILIO_CALRADI),
   (try_end),  

   ]),   


  # NE finance
    # script_adjust_finances - Jinnai
  # Input1: finance slot
  # Input2: amount
  # Output: none
  ("adjust_finances",
    [
      (store_script_param, ":finance", 1),
      (store_script_param, ":amount", 2),
      (troop_get_slot, ":value", "trp_finances_array_this", ":finance"),
      (val_add,":value",":amount"),
      (troop_set_slot, "trp_finances_array_this", ":finance", ":value"),
      ]),
	
  # NE end finance
# NE kt0
# kt0's autoresolve scripts

# start kt0

      ( "kt_init_troop_slots", kt_python_init_troop_slots() ),
	
   # kt0:  new strength calculation
   # this script makes use of new slots that are filled out at init time with
   # script code that was generated at compile time.  the range of the values
   # coming out of this script are much larger (about 100x) than the original
   # range.  furthermore, we add a defense calculation and troop count to the
   # returns.
   # INPUT: 
   #      arg1:  party_id
   #      arg2:  exclude leader
   #      arg3:  is siege
   # OUTPUT:
   #      reg0:  offense value
   #      reg1:  defense value (damage redux in percent)
   #      reg2:  troop count
   ( "kt_party_calculate_strength",
   [
      # remember our params
      (store_script_param_1, ":party"),   # party id
      (store_script_param_2, ":exclude_leader"), # also a party id apparently
      (store_script_param, ":is_siege", 3), # so we don't count horses for sieges

      # clear out our returns and temps
      (assign, reg0, 0),
      (assign, reg1, 0),
      (assign, reg2, 0),

      # figure out which stack to start with and how many we have
      (party_get_num_companion_stacks, ":num_stacks", ":party"),
      (assign, ":first_stack", 0),
      (try_begin),
         (neq, ":exclude_leader", 0),
         (assign, ":first_stack", 1),
      (try_end),

 
      # for each stack that we care about, grab the offense, defense and count
      # and stuff the values into our return registers. 
      (try_for_range, ":i_stack", ":first_stack", ":num_stacks"),
         (party_stack_get_troop_id, ":stack_troop", ":party", ":i_stack"),
		 
 
		 
         (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"),
         (gt, ":stack_size", 0),
         (assign, ":o_val", 0),
         (assign, ":d_val", 0),
         (assign, ":h_val", 0),
         (assign, ":tr_type", 0),
         (try_begin),
            # if this is not a hero, just read slots
            (neg|troop_is_hero, ":stack_troop"),
            (troop_get_slot, ":o_val", ":stack_troop", kt_slot_troop_o_val),
            (troop_get_slot, ":d_val", ":stack_troop", kt_slot_troop_d_val),
            (troop_get_slot, ":h_val", ":stack_troop", kt_slot_troop_h_val),
            (troop_get_slot, ":tr_type", ":stack_troop", kt_slot_troop_type),

            # zero out horse bonuses for mounted archers.  they aren't
            # supposed to be charging into the fray.
            (try_begin),
               (eq, ":tr_type", kt_troop_type_mtdarcher),
               (assign, ":h_val", 0),
            (try_end),
            # mul by stack size
            (val_mul, ":o_val", ":stack_size"),
            (val_mul, ":d_val", ":stack_size"),
            (val_mul, ":h_val", ":stack_size"),
         (else_try),
            # todo:  heroes have different rules since they don't have troop
            # templates.  for now, we'll use 50 + level*3 for o_val and
            # 20 + level*2 for d_val.  in the future, this should be replaced
            # by a gear lookup.
            (store_character_level, ":level", ":stack_troop"),
            (store_mul, ":o_val", ":level", 3),
            (val_add, ":o_val", 50),
            (store_mul, ":d_val", ":level", 2),
            (val_add, ":d_val", 20),
         (try_end),
         
         # siege checks
         (try_begin),
            # if not sieging, mounted guys get a bonus.
            (eq, ":is_siege", 0),
            (try_begin),
               # mounted archers only get 50% more defense
               (eq, ":tr_type", kt_troop_type_mtdarcher),
               (val_mul, ":d_val", 3),
			   (try_begin), 
			   (neq, ":d_val", 0),
               (val_div, ":d_val", 2),
			   (try_end), 
            (else_try),
               # cavalry get 50% more attack and defense and add h_val to o_val
               (eq, ":tr_type", kt_troop_type_cavalry),
               (val_mul, ":o_val", 3),
			   (try_begin), 
			   (neq, ":o_val", 0),
               (val_div, ":o_val", 2),
			   (try_end), 
               (val_add, ":o_val", ":h_val"),
               (val_mul, ":d_val", 3),
			   (try_begin), 
			   (neq, ":d_val", 0),
               (val_div, ":d_val", 2),
			   (try_end), 
			  
            (try_end),
            (val_add, ":o_val", ":h_val"),
         (try_end),
   
	  
         # add stuff up
         (val_add, reg0, ":o_val"),
         (val_add, reg1, ":d_val"),
         (val_add, reg2, ":stack_size"),
#debug		 
#	    (display_message, "@ Total Offense {reg0}, defense {reg1}, Stack size: {reg2}", 0xFFFFFF00),		
				  
      (try_end),
      
      # calculate damage redux from defense
	  (try_begin), 
	  (neq, reg2, 0), 
      (val_div, reg1, reg2), # avg defense
	  (try_end), 
      (val_clamp, reg1, 0, 90), # values outside this range don't work well
      (store_sub, reg1, 100, reg1), # opponent offense should be multiplied by this %
   ]),

   # kt0:  this is a helper that basically calls kt_party_calculate_strength
   # for each attachment to the given party. 
   # INPUT:
   #      arg1:  party_id
   #      arg2:  exclude leader of given stack (not attachments)
   #      arg3:  is_siege
   # OUTPUT:
   #      reg0:  aggregate strength
   #      reg1:  number of attached parties
   ( "kt_party_calculate_strength_with_attachments",
   [
      # remember our params and set some initial values
      (store_script_param_1, ":root_party"),
      (store_script_param_2, ":exclude_leader"),
      (store_script_param, ":is_siege", 3),

      # call the counting script for the given party
      (call_script, "script_kt_party_calculate_strength", ":root_party", ":exclude_leader", ":is_siege"),
      (assign, ":strength_so_far", reg0),
      (assign, ":def_so_far", reg1),
      (assign, ":count_so_far", reg2),
      (val_mul, ":def_so_far", ":count_so_far"),

      # for every attached party, do the same      
      (party_get_num_attached_parties, ":attached_count", ":root_party"),
      (try_for_range, ":rank", 0, ":attached_count"),
         (party_get_attached_party_with_rank, ":attached_party", ":root_party", ":rank"),
         (call_script, "script_kt_party_calculate_strength", ":attached_party", 0, ":is_siege"),
         (val_add, ":strength_so_far", reg0),
         (store_mul, ":def_this_party", reg1, reg2),
         (val_add, ":def_so_far", ":def_this_party"),
         (val_add, ":count_so_far", reg2),
      (try_end),

      # fill out our returns
      (assign, reg0, ":strength_so_far"),
      (val_div, ":def_so_far", ":count_so_far"),
      (assign, reg1, ":def_so_far"),      
      (assign, reg2, ":count_so_far"),
   ]),

   # kt0:  there seem to be multiple ways to calculate how many fit troops
   # there are in an encounter and they all do something slightly different
   # but seem to be used for the same things.  this is a simple consolidation
   # attempt that counts guys the same way that we calculate party strengths.
   # INPUT: 
   #      arg1:  party_id
   #      arg2:  exclude leader
   # OUTPUT:
   #      reg0:  viable troop count
   ( "kt_count_viable_troops",
   [
      # remember our params
      (store_script_param_1, ":party"),   # party id
      (store_script_param_2, ":exclude_leader"), # also a party id apparently

      # clear out our return
      (assign, reg0, 0),

      # figure out which stack to start with and how many we have
      (party_get_num_companion_stacks, ":num_stacks", ":party"),
      (assign, ":first_stack", 0),
      (try_begin),
         (neq, ":exclude_leader", 0),
         (assign, ":first_stack", 1),
      (try_end),

      (try_for_range, ":i_stack", ":first_stack", ":num_stacks"),
         (party_stack_get_troop_id, ":stack_troop", ":party", ":i_stack"),
         (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"),
         (try_begin),
            (gt, ":stack_size", 0),
            (try_begin),
               # if this stack is a hero, check health vs. the viable thresh.
               (troop_is_hero, ":stack_troop"),
               (neg|troop_is_wounded, ":stack_troop"),
               (val_add, reg0, 1),
            (else_try),
               # otherwise just add
               (val_add, reg0, ":stack_size"),
            (try_end),
         (try_end),
      (try_end),

      # reg0 should have the battle-ready count
   ]),
   
   # kt0:  this is a helper that basically calls kt_count_viable_troops for
   # each attachment to the given party.  if the party has no attachments,
   # it just returns the given party's count.
   # INPUT:
   #      arg1:  party_id
   #      arg2:  exclude leader of given stack (not attachments)
   # OUTPUT:
   #      reg0:  viable troop count
   #      reg1:  number of attached parties
   ( "kt_count_viable_troops_with_attachments",
   [
      # remember our params and set some initial values
      (store_script_param_1, ":root_party"),
      (store_script_param_2, ":exclude_leader"),

      # call the counting script for the given party
      (call_script, "script_kt_count_viable_troops", ":root_party", ":exclude_leader"),
      (assign, ":count_so_far", reg0),

      # for every attached party, do the same      
      (party_get_num_attached_parties, ":attached_count", ":root_party"),
      (try_for_range, ":rank", 0, ":attached_count"),
         (party_get_attached_party_with_rank, ":attached_party", ":root_party", ":rank"),
         (call_script, "script_kt_count_viable_troops", ":attached_party", 0),
         (val_add, ":count_so_far", reg0),
      (try_end),

      # fill out our returns
      (assign, reg0, ":count_so_far"),
      (assign, reg1, ":attached_count"),
   ]),

# ne end kt0

# NE quests
	 
	 #v585 Josefgirl
	  #script_update_villages_infested_by_wedding
  # INPUT: none
  # OUTPUT: none
  ("update_villages_infested_by_wedding",
    [(try_for_range, ":village_no", villages_begin, villages_end),
       (try_begin),
         (check_quest_active, "qst_hunt_down_girl"),
		 (neg|check_quest_succeeded,  "qst_hunt_down_girl"),
         (quest_slot_eq, "qst_hunt_down_girl", slot_quest_target_center, ":village_no"),
         (assign, ":bandit_troop", "trp_wedding_guest"),
         (party_set_slot, ":village_no", slot_village_infested_by_wedding , ":bandit_troop"),

         (try_begin),
           (eq, "$cheat_mode", 1),
           (str_store_party_name, s1, ":village_no"),
           (display_message, "@{s1} is holding a wedding."),
         (try_end),
 
       (try_end),
     (try_end),
     ]), 
	 
	 
	 #endv585 Josef

	 #v585 Josefgirl	 

  #script_get_girl_name_from_dna_to_s50
  # INPUT: arg1 = dna
  # OUTPUT: s50 = name
  ("get_girl_name_from_dna_to_s50",
    [(store_script_param, ":dna", 1),
     (store_sub, ":num_names", girl_names_end, girl_names_begin),
     (store_sub, ":num_surnames", girl_surnames_end, girl_surnames_begin),
     (assign, ":selected_name", ":dna"),
     (val_mod, ":selected_name", ":num_names"),
     (assign, ":selected_surname", ":dna"),
     (val_div, ":selected_surname", ":num_names"),
     (val_mod, ":selected_surname", ":num_surnames"),
     (val_add, ":selected_name", girl_names_begin),
     (val_add, ":selected_surname", girl_surnames_begin),
     (str_store_string, s50, ":selected_name"),
     (str_store_string, s50, ":selected_surname"),
     ]),

  #end v585 Josef
  # NE end quests 
  
  # Ne conscription
  ##Melissa's Conscription

  #script_cf_village_conscript_volunteers_cond
  # INPUT: none
  # OUTPUT: none
  ("cf_village_conscript_volunteers_cond",
    [(neg|party_slot_eq, "$current_town", slot_village_state, svs_looted),
     (neg|party_slot_eq, "$current_town", slot_village_state, svs_being_raided),
     (neg|party_slot_ge, "$current_town", slot_village_infested_by_bandits, 1),
	 #v585 Josefgirl
	      (neg|party_slot_ge, "$current_town", slot_village_infested_by_bandits, 1),
		  #end v585 Josef
     (store_faction_of_party, ":village_faction", "$current_town"),
     (party_get_slot, ":center_relation", "$current_town", slot_center_player_relation),
     (store_relation, ":village_faction_relation", ":village_faction", "fac_player_faction"),
     (ge, ":center_relation", 0),
     (this_or_next|ge, ":center_relation", 5),
     (this_or_next|eq, ":village_faction", "$players_kingdom"),
     (this_or_next|ge, ":village_faction_relation", 0),
     (this_or_next|eq, ":village_faction", "$supported_pretender_old_faction"),
     (             eq, "$players_kingdom", 0),
     (party_slot_ge, "$current_town", slot_center_volunteer_troop_amount, 0),
     (party_slot_ge, "$current_town", slot_center_volunteer_troop_type, 1),
     (party_get_free_companions_capacity, ":free_capacity", "p_main_party"),
     (ge, ":free_capacity", 1),
     ]),

  #script_conscript_troops_in_village
  # INPUT: arg1 = center_no
  # OUTPUT: none
  ("conscript_troops_in_village",
    [
     (party_get_slot, ":center_culture", "$current_town", slot_center_culture),
     (faction_get_slot, ":volunteer_troop", ":center_culture", slot_faction_tier_1_troop),
     (party_get_slot, ":volunteer_amount", "$current_town", slot_center_volunteer_troop_amount),
     (val_max,":volunteer_amount",10),
     (party_get_free_companions_capacity, ":free_capacity", "p_main_party"),
     (val_min, ":volunteer_amount", ":free_capacity"),
     (store_troop_gold, ":gold", "trp_player"),
     (store_div, ":gold_capacity", ":gold", 2),#2 denars per man
     (val_min, ":volunteer_amount", ":gold_capacity"),
     (party_add_members, "p_main_party", ":volunteer_troop", ":volunteer_amount"),
     (party_set_slot, "$current_town", slot_center_volunteer_troop_amount, -1),
     (store_mul, ":cost", ":volunteer_amount", 2),#2 denars per man
     (troop_remove_gold, "trp_player", ":cost"),
     (val_mul,":cost",-1),
     (call_script, "script_adjust_finances", slot_finance_wages, ":cost"),
     (call_script, "script_change_player_relation_with_center", "$current_town",-10),
     ]),	 
	 
	 
	 
	 # Ne end conscription

	 # NE lords
## Companion lord support scripts begin - Jinnai

  ("companion_to_lord",[
    (store_script_param, ":companion", 1),
    (remove_member_from_party, ":companion"),
    (troop_set_slot, ":companion", slot_troop_occupation, slto_kingdom_hero),
    (troop_set_slot, ":companion", slot_troop_readiness_to_join_army, 100),
    (troop_set_slot, ":companion", slot_troop_readiness_to_follow_orders, 100),
    (troop_set_slot, ":companion", slot_troop_player_order_state, spai_undefined),
    (troop_set_slot, ":companion", slot_troop_player_relation, 25),
    (troop_set_slot, ":companion", slot_troop_player_order_object, -1),
    (troop_set_slot, ":companion", slot_troop_change_to_faction, 0),
    (troop_set_slot, ":companion", slot_troop_spawned_before, 1),
    (troop_set_faction, ":companion", fac_player_supporters_faction),
    (troop_set_slot, ":companion", slot_troop_prisoner_of_party, -1),
    (set_spawn_radius,1),
    (troop_get_slot, ":player_party", "trp_player", slot_troop_leaded_party),
    (spawn_around_party,":player_party","pt_kingdom_hero_party"),
    (assign, "$pout_party", reg0),
    (party_set_faction, "$pout_party", fac_player_supporters_faction),
    (party_set_slot, "$pout_party", slot_party_type, spt_kingdom_hero_party),
    (call_script, "script_party_set_ai_state", "$pout_party", spai_undefined, -1),
    (troop_set_slot, ":companion", slot_troop_leaded_party, "$pout_party"),
    (party_add_leader, "$pout_party", ":companion"),
    (str_store_troop_name, s5, ":companion"),
    (party_set_name, "$pout_party", "str_s5_s_party"),
    (party_set_slot, "$pout_party", slot_party_commander_party, -1),
    (call_script, "script_update_all_notes"),
  ]),

  ("lord_to_companion",[
    (store_script_param, ":companion", 1),
    (troop_get_slot, ":party", ":companion", slot_troop_leaded_party),
    (troop_set_slot, ":companion", slot_troop_leaded_party, -1),
    (troop_set_faction, ":companion", fac_commoners),
    (store_faction_of_party, ":faction_receiving_prisoners", ":party"),
    (party_get_num_prisoner_stacks, ":num_stacks", ":party"),
    (try_for_range, ":troop_iterator", 0, ":num_stacks"),
      (party_prisoner_stack_get_troop_id, ":cur_troop_id", ":party", ":troop_iterator"),
      (troop_is_hero, ":cur_troop_id"),
      (party_remove_prisoners, ":party", ":cur_troop_id", 1),
      (call_script, "script_remove_troop_from_prison", ":cur_troop_id"),
      (store_troop_faction, ":cur_troop_faction", ":cur_troop_id"),
      (str_store_troop_name_link, s1, ":cur_troop_id"),
      (str_store_faction_name_link, s2, ":faction_receiving_prisoners"),
      (str_store_faction_name_link, s3, ":cur_troop_faction"),
      (display_log_message,"str_hero_freed"),
    (try_end),
    (troop_set_slot, ":companion", slot_troop_occupation, 0),
    (troop_set_slot, ":companion", slot_troop_playerparty_history, pp_history_indeterminate),
    (troop_get_slot, ":town_no", ":companion", slot_troop_first_encountered),
    (troop_set_slot, ":companion", slot_troop_cur_center, ":town_no"),
    (remove_party, ":party"),
    (call_script, "script_update_all_notes"),
  ]),

## Companion lord support scripts end	 
	 
	 # NE end lords

# NE assassin
# Josef v586 assassins! 

  # script_cf_enter_center_location_assassin_check
  # Input: inside or outside, used for castle exterior or hall
  # Output: none
  ("cf_enter_center_location_assassin_check",
    [
	
	  (store_script_param_1, ":interior"),
	  
	  # check that the player isn't a mercenary
      (neq, "$mercenary_now", 1), 

	  
	  # add one to global variable
	  # UNCOMMENT LATER - THIS FOR TESTING, ANY TOWN OR CASTLE SCENE WILL TRIGGER ASSASSINS
	  (store_random_in_range, ":rand", 0, 20),
	  (val_add, ":rand", "$days"), #a random no. between 0 and 20 is added to the day count between assassin attacks
	  #pc 
	  #(assign,  ":rand", 51),  #pc
      (gt, ":rand", 50), # if that number is >50, then trigger an assassin attack. Generally every 31-50 days, but weighted towards 35-45
	  (assign, "$days", 0), # reset global variable days
	  # end comment out
      (eq, "$g_defending_against_siege", 0),#Skip if the center is under siege (because of resting)
      (eq, "$sneaked_into_town", 0),#Skip if sneaked
	   # UNCOMMENT LATER - THIS FOR TESTING, ANY TOWN OR CASTLE SCENE WILL TRIGGER ASSASSINS
	   # Assassins - pc have to figure out how to disable this if Mercenary
	  (neq, "$players_kingdom", 0), #player must be either a vassal or have his own kingdom
	  
      # (try_begin),
        # (party_slot_eq, "$current_town", slot_party_type, spt_village),
        # (party_get_slot, ":cur_scene", "$current_town", slot_castle_exterior),
      # (else_try),		
      (try_begin),	  
        (party_slot_eq, "$current_town", slot_party_type, spt_castle),
		(try_begin), 
		(eq, ":interior", 0), #lord's hall
        (party_get_slot, ":cur_scene", "$current_town", slot_town_castle),	
		(else_try),  #courtyard
		(party_get_slot, ":cur_scene", "$current_town", slot_castle_exterior),	
		(try_end), 
# otherwise town centre       
      (else_try),
        (party_get_slot, ":cur_scene", "$current_town", slot_town_center),
      (try_end),
      (modify_visitors_at_site, ":cur_scene"), 
      (reset_visitors),
	  
	  
# get 'lordship' factor - village, castle, or town lord. Or King.
	  (call_script, "script_cf_player_character_attributes", "trp_player"),	  	  
	  (assign, ":result", reg1), 
	      
      (set_jump_mission, "mt_assassins"),
# attacks only happen in castles or towns   
	  (try_begin), 
	    # castle attack
        (party_slot_eq, "$current_town", slot_party_type, spt_castle),
	(try_begin), #interior or exterior
			(eq, ":interior", 1), # attack happens in courtyard
			    (try_begin), 
				(eq, ":result", 1), 
				(assign, ":bandit_troop", "trp_assassin1"),
				(assign, ":spawn_amount", 1),
				(set_visitors, 40, ":bandit_troop", ":spawn_amount"),
				(else_try), 
				(eq, ":result", 2), 
				(assign, ":bandit_troop", "trp_assassin2"),
				(assign, ":spawn_amount", 1),
				(set_visitors, 40, ":bandit_troop", ":spawn_amount"),
				(assign, ":bandit_troop", "trp_assassin1"),
				(set_visitors, 41, ":bandit_troop", ":spawn_amount"),
				(store_random_in_range, ":random_no", 0, 100),
				(lt, ":random_no", 50),
				(assign, ":bandit_troop", "trp_assassin2"),
				(assign, ":spawn_amount", 1),
				(set_visitors, 42, ":bandit_troop", ":spawn_amount"),
				(else_try), 
				(eq, ":result", 3), 
				(assign, ":bandit_troop", "trp_assassin2"),
				(assign, ":spawn_amount", 2),
				(set_visitors, 40, ":bandit_troop", ":spawn_amount"),
				(set_visitors, 41, ":bandit_troop", ":spawn_amount"),
				(store_random_in_range, ":random_no", 0, 100),
				(lt, ":random_no", 50),
				(assign, ":spawn_amount", 1),
				(set_visitors, 42, ":bandit_troop", ":spawn_amount"),
				(else_try), 
				(eq, ":result", 4), 
				(assign, ":bandit_troop", "trp_assassin_royal"),
				(assign, ":spawn_amount", 1),
				(set_visitors, 40, ":bandit_troop", ":spawn_amount"),
				(set_visitors, 41, ":bandit_troop", ":spawn_amount"),
				(store_random_in_range, ":random_no", 0, 100),
				(lt, ":random_no", 50),
				(assign, ":spawn_amount", 2),
				(set_visitors, 40, ":bandit_troop", ":spawn_amount"),
				(set_visitors, 41, ":bandit_troop", ":spawn_amount"),
				(try_end),
		
				# (set_visitors, 16, ":bandit_troop", ":spawn_amount"),
				(assign, "$num_center_bandits", ":spawn_amount"),
				(set_jump_entry, 2),		
			(else_try), #attack happens in lord's hall	
				(try_begin), 
				(eq, ":result", 1), 
				(assign, ":bandit_troop", "trp_assassin1"),
				(assign, ":spawn_amount", 1),
				(set_visitors, 19, ":bandit_troop", ":spawn_amount"),
				(else_try), 
				(eq, ":result", 2), 
				(assign, ":bandit_troop", "trp_assassin1"),
				(assign, ":spawn_amount", 1),
				(set_visitors, 19, ":bandit_troop", ":spawn_amount"),
				(set_visitors, 18, ":bandit_troop", ":spawn_amount"),
				(store_random_in_range, ":random_no", 0, 100),
				(lt, ":random_no", 50),
				(assign, ":spawn_amount", 1),
				(set_visitors, 20, ":bandit_troop", ":spawn_amount"),
				(else_try), 
				(eq, ":result", 3), 
				(assign, ":bandit_troop", "trp_assassin1"),
				(assign, ":spawn_amount", 1),
				(set_visitors, 19, ":bandit_troop", ":spawn_amount"),
				(set_visitors, 18, ":bandit_troop", ":spawn_amount"),
				(set_visitors, 20, ":bandit_troop", ":spawn_amount"),
				(set_visitors, 22, ":bandit_troop", ":spawn_amount"),
				(set_visitors, 24, ":bandit_troop", ":spawn_amount"),
				(store_random_in_range, ":random_no", 0, 100),
				(lt, ":random_no", 50),
				(assign, ":spawn_amount", 1),
				(set_visitors, 17, ":bandit_troop", ":spawn_amount"),
				(else_try), 
				(eq, ":result", 4), 
				(assign, ":bandit_troop", "trp_assassin_royal"),
				(assign, ":spawn_amount", 1),
				(set_visitors, 19, ":bandit_troop", ":spawn_amount"),
				(set_visitors, 18, ":bandit_troop", ":spawn_amount"),
				(store_random_in_range, ":random_no", 0, 100),
				(lt, ":random_no", 50),
				(assign, ":spawn_amount", 1),
				(set_visitors, 22, ":bandit_troop", ":spawn_amount"),
				(try_end), 		
				# (set_visitors, 16, ":bandit_troop", ":spawn_amount"),
				(assign, "$num_center_bandits", ":spawn_amount"),
				(set_jump_entry, 0),
			(try_end), #interior or exterior end 	

     (else_try),
	 # city attack
	    (try_begin), 
	    (eq, ":result", 1), 
	    (assign, ":bandit_troop", "trp_assassin1"),
		(assign, ":spawn_amount", 1),
	    (set_visitors, 11, ":bandit_troop", ":spawn_amount"),
	    (else_try), 
	    (eq, ":result", 2), 
	    (assign, ":bandit_troop", "trp_assassin1"),
		(assign, ":spawn_amount", 2),
		(set_visitors, 11, ":bandit_troop", ":spawn_amount"),
		(store_random_in_range, ":random_no", 0, 100),
        (lt, ":random_no", 50),
		# (assign, ":spawn_amount", 3),
		(set_visitors, 27, ":bandit_troop", 1),
		(else_try), 
	    (eq, ":result", 3), 
	    (assign, ":bandit_troop", "trp_assassin1"),
		(assign, ":spawn_amount", 4),
		(set_visitors, 11, ":bandit_troop", 2),	
		(set_visitors, 27, ":bandit_troop", 2),		
		(store_random_in_range, ":random_no", 0, 100),
        (lt, ":random_no", 50),
		# (assign, ":spawn_amount", 5),
		(set_visitors, 23, ":bandit_troop", 1),	
		(else_try), 
	    (eq, ":result", 4), 
	    (assign, ":bandit_troop", "trp_assassin_royal"),
		(assign, ":spawn_amount", 2),
		(set_visitors, 11, ":bandit_troop", 1),	
		(set_visitors, 27, ":bandit_troop", 1),				
		(store_random_in_range, ":random_no", 0, 100),
        (lt, ":random_no", 50),
		# (assign, ":spawn_amount", 4),
		(set_visitors, 23, ":bandit_troop", 1),		
		(set_visitors, 24, ":bandit_troop", 1),		
	    (try_end), 			
# horrified onlookers
		(set_visitors, 32, "trp_town_walker_1", 1),
		(set_visitors, 33, "trp_town_walker_2", 1),
		(set_visitors, 34, "trp_town_walker_1", 1),
		(set_visitors, 35, "trp_town_walker_2", 1),
		(set_visitors, 36, "trp_town_walker_1", 1),
		(set_visitors, 37, "trp_town_walker_2", 1),
	    (set_visitors, 38, "trp_town_walker_1", 1),
		(set_visitors, 39, "trp_town_walker_2", 1),
		(set_visitors, 37, "trp_town_walker_1", 1),				
		
		(set_jump_entry, 0),
       (try_end),
				
        (assign, "$town_entered", 1),
        (assign, "$all_doors_locked", 1),
      #(try_end),


      (display_message, "@You become uneasy as you note the strange absence of Guards nearby..", 0xFFFFFF00),
      (display_message, "@..and realise you have walked into a trap! Assassins!", 0xFFFFFF00),
	  
      (jump_to_scene, ":cur_scene"),
      (change_screen_mission),
      ]),
	  
# end Josef v586

# josef v586 character summary
   # INPUT:
   #      arg1:  troop_id
   # OUTPUT:
   #      reg1:  status based on fiefs owned
   #      reg2:  honour rating  
   #      reg3:  renown
   
   ( "cf_player_character_attributes",
   [
    (store_script_param_1, ":troop_no"), 

	# how many towns, castles, villages, does player own?
	# use this to determine 'lordship' level 
	# Player is a baron (village) - 1 killer
	# Player is a count (1+ castle) - 2-3 killer
	# Player is a duke (1+ town) - 4-5 killer
	# Player is a king - 2-4 royal assassins.
	
      (assign, reg1, 0), 
	  
      #villages
	  (try_begin), 
      (assign, ":result", 0),
      (try_for_range, ":center_no", villages_begin, villages_end),
        (party_slot_eq, ":center_no", slot_town_lord, ":troop_no"),
        (val_add, ":result", 1),
      (try_end),
	  (ge, ":result", 1), 
	  (assign, reg1, 1), # "1" equates to baron
	  #(display_message, "@{!}Baron"),
	  (try_end), 
	  
	  #castles
	  (try_begin), 
      (assign, ":result", 0),
      (try_for_range, ":center_no", castles_begin, castles_end),
        (party_slot_eq, ":center_no", slot_town_lord, ":troop_no"),
        (val_add, ":result", 1),
      (try_end),
	  (ge, ":result", 1), 
	  (assign, reg1, 2), #  castle = 2 = equates to count
      #(display_message, "@{!}Count"),
	  (try_end),
		  
	  #cities
	  (try_begin), 
	  (assign, ":result", 0),
      (try_for_range, ":center_no", towns_begin, towns_end),
        (party_slot_eq, ":center_no", slot_town_lord, ":troop_no"),
		
        (val_add, ":result", 1),
      (try_end),
	  (ge, ":result", 1), 
	  (assign, reg1, 3), #   town= 3 = equates to duke
	  #(display_message, "@{!}Duke"),
	  (try_end),  
	  
     # King
     (try_begin), 
     (eq, "$players_kingdom", "fac_player_supporters_faction"),	 
	 (ge, reg1, 3), #i.e. if the player has a town and his own faction, he's a king
     (assign, reg1, 4), #   King
     #(display_message, "@{!}King"),
	 (try_end),
	 
		
    # get honour and renown 	
	# (troop_get_slot, reg2, "trp_player", slot_troop_renown),

    # for player level if needed later
	# (store_character_level, ":level", "trp_player"),

   ]),
   
# NE end assassin 


#############################################################################################
#############################################################################################
#############################################################################################
#############################################################################################
#############################################################################################
#############################################################################################
#############################################################################################
#############################################################################################
#############################################################################################
#############################################################################################
# DK AI 

  # script_decide_faction_ai
  # Input: arg1: faction_no
  # Output: none
  #called from triggers
  ("decide_faction_ai_dk2",
  #This handles political issues and faction issues
   [
    (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_marshal", ":faction_no", slot_faction_marshall),

	 
	#Remove marshal if he has become too controversial,, or he has defected, or has been taken prisoner
	(try_begin),
        (faction_slot_eq, ":faction_no", slot_faction_state, sfs_active),
		(neq, ":faction_no", "fac_player_supporters_faction"),
		(ge, ":faction_marshal", "trp_player"),
		
		(store_faction_of_troop, ":marshal_faction", ":faction_marshal"),
		(try_begin),
			(eq, ":faction_marshal", "trp_player"),
			(assign, ":marshal_faction", "$players_kingdom"),
		(try_end),
		
		
		(assign, ":player_marshal_is_prisoner", 0),
		(try_begin),
			(eq, ":faction_marshal", "trp_player"),
			(eq, "$g_player_is_captive", 1),
			(assign, ":player_marshal_is_prisoner", 1),
		(try_end),
		
		
		#High controversy level, or marshal has defected, or is prisoner
		(this_or_next|neq, ":marshal_faction", ":faction_no"),		
		(this_or_next|troop_slot_ge, ":faction_marshal", slot_troop_controversy, 80),
		(this_or_next|eq, ":player_marshal_is_prisoner", 1),
			(troop_slot_ge, ":faction_marshal", slot_troop_prisoner_of_party, 0),
		
		(assign, ":few_following_player_campaign", 0),
		(try_begin),
			(eq, ":faction_marshal", "trp_player"),
			(assign, ":vassals_following_player_campaign", 0),
			(gt, "$g_player_days_as_marshal", 1),
			(try_for_range, ":vassal", active_npcs_begin, active_npcs_end),
				(troop_slot_eq, ":vassal", slot_troop_occupation, slto_kingdom_hero),
				(store_faction_of_troop, ":vassal_faction", ":vassal"),
				(eq, ":vassal_faction", ":faction_no"),
				(call_script, "script_npc_decision_checklist_troop_follow_or_not", ":vassal"),
				(eq, reg0, 1),
				(val_add, ":vassals_following_player_campaign", 1),
			(try_end),
			(lt, ":vassals_following_player_campaign", 4),
			(assign, ":few_following_player_campaign", 1),
		(try_end),
		
		#Only remove marshal for controversy if offensive campaign in progress
		(this_or_next|eq, ":old_faction_ai_state", sfai_default),
		(this_or_next|eq, ":old_faction_ai_state", sfai_feast),		
		(this_or_next|neq, ":marshal_faction", ":faction_no"),
		(this_or_next|eq, ":few_following_player_campaign", 1),
		(this_or_next|eq, ":player_marshal_is_prisoner", 1),
			(troop_slot_ge, ":faction_marshal", slot_troop_prisoner_of_party, 0),
		
		#No current issue on the agenda
		(this_or_next|faction_slot_eq, ":faction_no", slot_faction_political_issue, 0),
		(this_or_next|eq, ":player_marshal_is_prisoner", 1),
			(troop_slot_ge, ":faction_marshal", slot_troop_prisoner_of_party, 0),
		
		(faction_set_slot, ":faction_no", slot_faction_political_issue, 1), #Appointment of marshal
		(store_current_hours, ":hours"),
		(val_max, ":hours", 0),
		(faction_set_slot, ":faction_no", slot_faction_political_issue_time, ":hours"), #Appointment of marshal
		
        (faction_get_slot, ":old_marshall", ":faction_no", slot_faction_marshall),
        (try_begin),
		  (ge, ":old_marshall", 0),
		  (troop_get_slot, ":old_marshall_party", ":old_marshall", slot_troop_leaded_party),
          (party_is_active, ":old_marshall_party"),
          (party_set_marshall, ":old_marshall_party", 0),
          (call_script, "script_set_icon_for_lord_party", ":old_marshall"),
        (try_end),  

		(try_begin),
			(eq, "$players_kingdom", ":faction_no"),
			(faction_slot_eq, "$players_kingdom", slot_faction_marshall, "trp_player"),
			(call_script, "script_add_notification_menu", "mnu_notification_relieved_as_marshal", 0, 0),
		(else_try),
			(neq, ":old_marshall", "trp_player"),
			(call_script, "script_change_troop_renown", ":old_marshall", 15),
		(try_end),
		(faction_set_slot, ":faction_no", slot_faction_marshall, -1),
		(assign, ":faction_marshal", -1),
		
		
		
		(try_for_range, ":active_npc", active_npcs_begin, active_npcs_end),
			(store_faction_of_troop, ":active_npc_faction", ":active_npc"),
			(eq, ":active_npc_faction", ":faction_no"),
			(troop_set_slot, ":active_npc", slot_troop_stance_on_faction_issue, -1),
		(try_end),		
		(try_begin),
			(eq, "$players_kingdom", ":faction_no"),
			(troop_set_slot, "trp_player", slot_troop_stance_on_faction_issue, -1),
		(try_end),
		
	(else_try),	 #If marshal not present, and not already on agenda, make political issue
		(eq, ":faction_marshal", -1),
		(neg|faction_slot_ge, ":faction_no", slot_faction_political_issue, 1), #This to avoid resetting votes every time
	
        (faction_slot_eq, ":faction_no", slot_faction_state, sfs_active),
		(neq, ":faction_no", "fac_player_supporters_faction"),
		
		(faction_set_slot, ":faction_no", slot_faction_political_issue, 1), #Appointment of marshal
		(store_current_hours, ":hours"),
		(val_max, ":hours", 0),
		(faction_set_slot, ":faction_no", slot_faction_political_issue_time, ":hours"), #Appointment of marshal
		
		(try_for_range, ":active_npc", active_npcs_begin, active_npcs_end),
			(store_faction_of_troop, ":active_npc_faction", ":active_npc"),
			(eq, ":active_npc_faction", ":faction_no"),
			(troop_set_slot, ":active_npc", slot_troop_stance_on_faction_issue, -1),
		(try_end),		
		(try_begin),
			(eq, "$players_kingdom", ":faction_no"),
			(troop_set_slot, "trp_player", slot_troop_stance_on_faction_issue, -1),
		(try_end),
		
		
	(else_try),	#If player is marshal, but not part of faction
		(eq, ":faction_marshal", "trp_player"),
		(neq, "$players_kingdom", ":faction_no"),

		(faction_set_slot, ":faction_no", slot_faction_political_issue, 1), #Appointment of marshal
		(store_current_hours, ":hours"),
		(val_max, ":hours", 0),
		(faction_set_slot, ":faction_no", slot_faction_political_issue_time, ":hours"), #Appointment of marshal

        (faction_get_slot, ":old_marshall", ":faction_no", slot_faction_marshall),
        (try_begin),
		  (ge, ":old_marshall", 0),
		  (troop_get_slot, ":old_marshall_party", ":old_marshall", slot_troop_leaded_party),
          (party_is_active, ":old_marshall_party"),
          (party_set_marshall, ":old_marshall_party", 0),
          (call_script, "script_set_icon_for_lord_party", ":old_marshall"),
        (try_end),  

		(faction_set_slot, ":faction_no", slot_faction_marshall, -1),
		(assign, ":faction_marshal", -1),
		
		(try_for_range, ":active_npc", active_npcs_begin, active_npcs_end),
			(store_faction_of_troop, ":active_npc_faction", ":active_npc"),
			(eq, ":active_npc_faction", ":faction_no"),
			(troop_set_slot, ":active_npc", slot_troop_stance_on_faction_issue, -1),
		(try_end),		
		(try_begin),
			(eq, "$players_kingdom", ":faction_no"),
			(troop_set_slot, "trp_player", slot_troop_stance_on_faction_issue, -1),
		(try_end),
		
	(try_end),
	 
	#If the faction issue is a center no longer under faction control, remove and reset 
	(try_begin), 
		(faction_get_slot, ":faction_political_issue", ":faction_no", slot_faction_political_issue),
		(is_between, ":faction_political_issue", centers_begin, centers_end),
		(store_faction_of_party, ":disputed_center_faction", ":faction_political_issue"),
		(neq, ":disputed_center_faction", ":faction_no"),
		
		(try_begin),
			(eq, "$cheat_mode", 1),
			(str_store_faction_name, s4, ":faction_no"),
			(str_store_party_name, s5, ":disputed_center_faction"),
			(display_message, "@{!}DEBUG -- {s4} drops {s5} as issue as it has changed hands"),
		(try_end),
		
		#Reset political issue
		(faction_set_slot, ":faction_no", slot_faction_political_issue, 0),
		(try_for_range, ":active_npc", active_npcs_begin, active_npcs_end),
			(store_faction_of_troop, ":active_npc_faction", ":active_npc"),
			(eq, ":active_npc_faction", ":faction_no"),
			(troop_set_slot, ":active_npc", slot_troop_stance_on_faction_issue, -1),
		(try_end),		
		(try_begin),
			(eq, "$players_kingdom", ":faction_no"),
			(troop_set_slot, "trp_player", slot_troop_stance_on_faction_issue, -1),
		(try_end),
		
	(try_end),
	
	
	#Resolve the political issue on the agenda
	(try_begin),
		(faction_slot_ge, ":faction_no", slot_faction_political_issue, 1),
		(neq, ":faction_no", "fac_player_supporters_faction"),
		
		#Do not switch marshals during a campaign
		(this_or_next|faction_slot_ge, ":faction_no", slot_faction_political_issue, centers_begin),
		(this_or_next|faction_slot_eq, ":faction_no", slot_faction_ai_state, sfai_default),
			(faction_slot_eq, ":faction_no", slot_faction_ai_state, sfai_feast),
		
		
		(faction_get_slot, ":faction_leader", ":faction_no", slot_faction_leader),
		
		(assign, ":total_lords", 0),
		(assign, ":lords_who_have_voted", 0),
		(assign, ":popular_favorite", -1),
	
		#Reset number of votes
		(troop_set_slot, "trp_player", slot_troop_temp_slot, 0),
		(try_for_range, ":active_npc", active_npcs_begin, active_npcs_end),
			(troop_set_slot, ":active_npc", slot_troop_temp_slot, 0),
		(try_end),

		#Tabulate votes
		(try_for_range, ":voting_lord", active_npcs_begin, active_npcs_end),
			(store_faction_of_troop, ":voting_lord_faction", ":voting_lord"),
			(eq, ":voting_lord_faction", ":faction_no"),
			(val_add, ":total_lords", 1),
			(troop_get_slot, ":lord_chosen_candidate", ":voting_lord", slot_troop_stance_on_faction_issue),								
			(gt, ":lord_chosen_candidate", -1),									
			(val_add, ":lords_who_have_voted", 1),			
			(troop_get_slot, ":total_votes", ":lord_chosen_candidate", slot_troop_temp_slot),
			(val_add, ":total_votes", 1),
			(troop_set_slot, ":lord_chosen_candidate", slot_troop_temp_slot, ":total_votes"),			
			(try_begin),
				(gt, ":popular_favorite", -1),
				(troop_get_slot, ":current_winner_votes", ":popular_favorite", slot_troop_temp_slot),
				(gt, ":total_votes", ":current_winner_votes"),
				(assign, ":popular_favorite", ":lord_chosen_candidate"),
			(else_try),	
				(eq, ":popular_favorite", -1),
				(assign, ":popular_favorite", ":lord_chosen_candidate"),
			(try_end),
		(try_end),	

		#Check to see if enough lords have voted
		(store_div, ":number_required_for_quorum", ":total_lords", 5),
		(val_mul, ":number_required_for_quorum", 4),
		
		
#		(gt, ":lords_who_have_voted", ":number_required_for_quorum"),

		(store_current_hours, ":hours_on_agenda"),
		(faction_get_slot, ":hours_when_put_on_agenda", ":faction_no", slot_faction_political_issue_time), #Appointment of marshal
		(val_sub, ":hours_on_agenda", ":hours_when_put_on_agenda"),
		
		(this_or_next|gt, ":lords_who_have_voted", ":number_required_for_quorum"),
			(ge, ":hours_on_agenda", 10), #Ne 120 to 10

		(try_begin),
			(eq, "$cheat_mode", 1),
			(assign, reg4, ":lords_who_have_voted"),
			(assign, reg5, ":number_required_for_quorum"),
			(assign, reg7, ":hours_on_agenda"),
			(str_store_faction_name, s4, ":faction_no"),
			(display_message, "@{!}DEBUG -- Issue resolution for {s4}: {reg4} votes for a quorum of {reg5}, {reg7} hours on agenda"),
		(try_end),


		(try_begin),
		  (eq, "$cheat_mode", 1),
		  (display_message, "@{!}DEBUG -- Faction resolves political issue"),
		(try_end),

	
		#Resolve faction political issue
		(assign, ":winning_candidate", -1),
		(try_begin),
			(call_script, "script_troop_get_relation_with_troop", ":faction_leader", ":popular_favorite"),
			
			(this_or_next|ge, reg0, 10),
			(this_or_next|troop_slot_eq, ":faction_leader", slot_troop_stance_on_faction_issue, ":popular_favorite"),
				(troop_slot_eq, ":faction_leader", slot_troop_stance_on_faction_issue, -1),
						
			(assign, ":winning_candidate", ":popular_favorite"),
		(else_try),#Lord overrules lords' opinion		
			(gt, ":faction_leader", -1), #not sure why this is necessary
			(troop_get_slot, ":liege_choice", ":faction_leader", slot_troop_stance_on_faction_issue),
			(ge, ":liege_choice", -1),
							
			(assign, ":winning_candidate", ":liege_choice"),
		(try_end),

		#Carry out faction decision
		(try_begin), #Nothing happens
			(eq, ":winning_candidate", -1),
			
		(else_try), #For player, create a menu to accept or refuse
			(eq, ":winning_candidate", "trp_player"),
			(eq, "$players_kingdom", ":faction_no"),
			(call_script, "script_add_notification_menu", "mnu_notification_player_faction_political_issue_resolved_for_player", 0, 0),
		(else_try),
			(eq, ":winning_candidate", "trp_player"),
			(neq, "$players_kingdom", ":faction_no"),

			(try_begin),
				(eq, "$cheat_mode", 1),
				(str_store_faction_name, s4, ":faction_no"),
				(str_store_party_name, s5, ":winning_candidate"),
				(display_message, "@{!}DEBUG -- {s4} drops {s5} as winner, for having changed sides"),
			(try_end),
			
			(try_for_range, ":active_npc", active_npcs_begin, active_npcs_end),
				(store_faction_of_troop, ":active_npc_faction", ":active_npc"),
				(eq, ":active_npc_faction", ":faction_no"),
				(troop_set_slot, ":active_npc", slot_troop_stance_on_faction_issue, -1),
			(try_end),		
			(try_begin),
				(eq, "$players_kingdom", ":faction_no"),
				(troop_set_slot, "trp_player", slot_troop_stance_on_faction_issue, -1),
			(try_end),
			
		(else_try),	#If candidate is not of winning faction, reset lrod votes
			(store_faction_of_troop, ":winning_candidate_faction", ":winning_candidate"),
			(neq, ":winning_candidate_faction", ":faction_no"),
			
			(try_begin),
				(eq, "$cheat_mode", 1),
				(str_store_faction_name, s4, ":faction_no"),
				(str_store_party_name, s5, ":winning_candidate"),
				(display_message, "@{!}DEBUG -- {s4} drops {s5} as winner, for having changed sides"),
			(try_end),
			
			(try_for_range, ":active_npc", active_npcs_begin, active_npcs_end),
				(store_faction_of_troop, ":active_npc_faction", ":active_npc"),
				(eq, ":active_npc_faction", ":faction_no"),
				(troop_set_slot, ":active_npc", slot_troop_stance_on_faction_issue, -1),
			(try_end),		
			(try_begin),
				(eq, "$players_kingdom", ":faction_no"),
				(troop_set_slot, "trp_player", slot_troop_stance_on_faction_issue, -1),
			(try_end),
			
		(else_try), #Honor awarded to another
			(faction_get_slot, ":issue_on_table", ":faction_no", slot_faction_political_issue),
			(try_begin), #A marshalship awarded to another
				(eq, ":issue_on_table", 1),
				(is_between, ":winning_candidate", active_npcs_begin, active_npcs_end),
				
				(this_or_next|is_between, ":winning_candidate", active_npcs_begin, active_npcs_end), #Prevents bug in which player given marshaldom of kingdom of which he/she is not a member
					(eq, "$players_kingdom", ":faction_no"),
				
				(assign, ":faction_marshal", ":winning_candidate"),
			(else_try), #A fief awarded to another
				(is_between, ":issue_on_table", centers_begin, centers_end),
				
				#If given to the player, resolved above
				(call_script, "script_give_center_to_lord", ":issue_on_table", ":winning_candidate", 0), #Zero means don't add garrison
				
				#If the player had requested a captured castle
				(try_begin),
					(eq, ":issue_on_table", "$g_castle_requested_by_player"),
					(party_slot_ge, ":issue_on_table", slot_town_lord, active_npcs_begin),
					(store_faction_of_party, ":faction_of_issue", ":issue_on_table"),
					(eq, ":faction_of_issue", "$players_kingdom"),
					(assign, "$g_center_to_give_to_player", ":issue_on_table"),
					(try_begin),
						(troop_get_slot, ":husband", "trp_player", slot_troop_spouse),
						(is_between, ":husband", active_npcs_begin, active_npcs_end),
						(eq, "$g_castle_requested_for_troop", ":husband"),
						(neq, ":winning_candidate", ":husband"),
						(jump_to_menu, "mnu_requested_castle_granted_to_another_female"),
					(else_try),
						(jump_to_menu, "mnu_requested_castle_granted_to_another"),
					(try_end),	
				(try_end),
				
			(try_end),
		
			(try_begin),
				(eq, ":faction_no", "$players_kingdom"),
				(call_script, "script_add_notification_menu", "mnu_notification_player_faction_political_issue_resolved", ":issue_on_table", ":winning_candidate"),
			(try_end),
		
		#Reset political issue
			(faction_set_slot, ":faction_no", slot_faction_political_issue, 0),
			(try_for_range, ":active_npc", active_npcs_begin, active_npcs_end),
				(store_faction_of_troop, ":active_npc_faction", ":active_npc"),
				(eq, ":active_npc_faction", ":faction_no"),
				(troop_set_slot, ":active_npc", slot_troop_stance_on_faction_issue, -1),
			(try_end),
			(try_begin),
				(eq, "$players_kingdom", ":faction_no"),
				(troop_set_slot, "trp_player", slot_troop_stance_on_faction_issue, -1),
			(try_end),			
		(try_end),
	(try_end),

	#Add fief to faction issues
	(try_begin),
		(faction_get_slot, ":faction_issue", ":faction_no", slot_faction_political_issue),
		(le, ":faction_issue", 0),
		
		(assign, ":landless_lords", 0),
		(assign, ":unassigned_centers", 0),
		(assign, ":first_unassigned_center_found", 0),
		
		(troop_set_slot, "trp_player", slot_troop_temp_slot, 0),
		(try_for_range, ":active_npc", active_npcs_begin, active_npcs_end),
			(troop_set_slot, ":active_npc", slot_troop_temp_slot, 0),
		(try_end),
		
		(try_for_range, ":center", centers_begin, centers_end),
			(store_faction_of_party, ":center_faction", ":center"),
			(eq, ":center_faction", ":faction_no"),
			
			(party_get_slot, ":town_lord", ":center", slot_town_lord),
			
			(try_begin),
				(lt, ":town_lord", 0),
				(val_add, ":unassigned_centers", 1),
				(try_begin),
					(eq, ":first_unassigned_center_found", 0),
					(assign, ":first_unassigned_center_found", ":center"),
				(try_end),
			(else_try),
				(troop_set_slot, ":town_lord", slot_troop_temp_slot, 1),			
			(try_end),
		(try_end),
		
		(store_add, ":landless_lords_plus_unassigned_centers", ":landless_lords", ":unassigned_centers"),
		(ge, ":landless_lords_plus_unassigned_centers", 2),		
			
		(faction_set_slot, ":faction_no", slot_faction_political_issue, ":first_unassigned_center_found"),	
		(store_current_hours, ":hours"),
		(faction_set_slot, ":faction_no", slot_faction_political_issue_time, ":hours"), #Fief put on agenda
		
		(try_for_range, ":active_npc", active_npcs_begin, active_npcs_end),
			(store_faction_of_troop, ":active_npc_faction", ":active_npc"),
			(eq, ":active_npc_faction", ":faction_no"),
			(troop_set_slot, ":active_npc", slot_troop_stance_on_faction_issue, -1),
		(try_end),
		(try_begin),
			(eq, "$players_kingdom", ":faction_no"),
			(troop_set_slot, "trp_player", slot_troop_stance_on_faction_issue, -1),
		(try_end),				
	(try_end),
	 
	 
    (try_begin), #If the marshal is changed
       (neg|faction_slot_eq, ":faction_no", slot_faction_marshall, ":faction_marshal"),
       #(assign, ":marshall_changed", 1),
       (eq, "$players_kingdom", ":faction_no"),
       (str_store_troop_name_link, s1, ":faction_marshal"),
       (str_store_faction_name_link, s2, ":faction_no"),
       (display_message, "@{s1} is the new marshal of {s2}."),
       (call_script, "script_check_and_finish_active_army_quests_for_faction", ":faction_no"),       
    (try_end),	 
	 
    (try_begin), #If the marshal is changed
       (neg|faction_slot_eq, ":faction_no", slot_faction_marshall, ":faction_marshal"),
	   (gt, ":faction_marshal", -1),
       (call_script, "script_appoint_faction_marshall", ":faction_no", ":faction_marshal"),   
    (try_end),	 
		 
	#DO FACTION AI HERE
	(try_begin),
		(eq, ":faction_no", "$players_kingdom"),
		(eq, ":faction_marshal", "trp_player"),
	    (assign, ":faction_ai_decider", "trp_player"),
	(else_try),
		(is_between, ":faction_marshal", active_npcs_begin, active_npcs_end),
		(assign, ":faction_ai_decider", ":faction_marshal"),
	(else_try),
		(faction_get_slot, ":faction_ai_decider", ":faction_no", slot_faction_leader),
	(try_end),
 
    (call_script, "script_npc_decision_checklist_faction_ai_alt_dk2",  ":faction_ai_decider"),
    (assign, ":new_strategy", reg0),
    (assign, ":new_object", reg1),
    	     
    ###new ozan
    (try_begin),
       (neq, ":new_strategy", ":old_faction_ai_state"),
       (eq, ":new_strategy", sfai_gathering_army),
       (faction_get_slot, ":faction_marshal", ":faction_no", slot_faction_marshall),
       (troop_get_slot, ":marshal_party", ":faction_marshal", slot_troop_leaded_party),
       (party_set_slot, ":marshal_party", slot_party_ai_object, -1),
       (assign, "$g_gathering_new_started", 1),
       (call_script, "script_npc_decision_checklist_party_ai", ":faction_marshal"), #This handles AI for both marshal and other parties		
       (call_script, "script_party_set_ai_state", ":marshal_party", reg0, reg1),
       (assign, "$g_gathering_new_started", 0),
    (else_try),      
       #check if marshal arrived his target city during active gathering
       
       #for now i disabled below lines because after always/active gathering armies become very large.
       #in current style marshal makes active gathering only at first, it travels to a city and waits there.
       
       (eq, ":new_strategy", ":old_faction_ai_state"),
       (eq, ":new_strategy", sfai_gathering_army),
       (faction_get_slot, ":faction_marshal", ":faction_no", slot_faction_marshall),
       (troop_get_slot, ":marshal_party", ":faction_marshal", slot_troop_leaded_party),
       (party_get_slot, ":party_ai_object", ":marshal_party", slot_party_ai_object),
       (ge, ":party_ai_object", 0),
       (store_distance_to_party_from_party, ":dist", ":marshal_party", ":party_ai_object"),
       (le, ":dist", 5),
       (party_set_slot, ":marshal_party", slot_party_ai_object, -1),
    (try_end),
     ##end ozan
	   	   	   
     #The following logic is mostly transplanted to the new decision_checklist 
     #Decision_checklist is used because I want to be able to reproduce the logic for strings
     #(call_script, "script_old_faction_ai"), 
     #ozan - I collected all comment-out lines in here (faction ai script) and placed most bottom of scripts.py to avoid confusing.	   		 	
     
    (faction_set_slot, ":faction_no", slot_faction_ai_state, ":new_strategy"),
    (faction_set_slot, ":faction_no", slot_faction_ai_object, ":new_object"),

    (call_script, "script_update_report_to_army_quest_note", ":faction_no", ":new_strategy", ":old_faction_ai_state"),

    (try_begin),
       (eq, ":new_strategy", sfai_feast),
       
       (store_current_hours, ":hours"),
       (faction_set_slot, ":faction_no", slot_faction_last_feast_start_time, ":hours"), #new
       
       (try_begin),
         (eq, "$g_player_eligible_feast_center_no", ":new_object"),
         (assign, "$g_player_eligible_feast_center_no", -1), #reset needed
       (try_end),
       (try_begin),
         (is_between, ":new_object", towns_begin, towns_end),
         (party_set_slot, ":new_object", slot_town_has_tournament, 2),
       (try_end),
    (try_end),	
	
     #Change of strategy
    (try_begin),
       (neq, ":new_strategy", ":old_faction_ai_state"),
		
       (try_begin),
         (ge, "$cheat_mode", 1),
         (str_store_faction_name, s5, ":faction_no"),
         (display_message, "str_s5_decides_s14"),
       (try_end),
		
       (store_current_hours, ":hours"),
       (faction_set_slot, ":faction_no", slot_faction_ai_current_state_started, ":hours"),

       #Feast ends
       (try_begin),
         (eq, ":old_faction_ai_state", sfai_feast),
         (call_script, "script_faction_conclude_feast", ":faction_no", ":old_faction_ai_object"),
       (try_end),

	   
       #Feast begins
       (try_begin),
         (eq, ":new_strategy", sfai_feast),
         (faction_get_slot, ":faction_object", ":faction_no", slot_faction_ai_object),
		 
##         (str_store_faction_name, s1, ":faction_no"),
##         (str_store_party_name, s2, ":faction_object"),
##         (display_message, "str_lords_of_the_s1_gather_for_a_feast_at_s2"),
		
         (party_get_slot, ":feast_host", ":faction_object", slot_town_lord),

         (try_begin),
           (check_quest_active, "qst_wed_betrothed"),
		   
           (quest_slot_eq, "qst_wed_betrothed", slot_quest_giver_troop, ":feast_host"),
           (neg|quest_slot_ge, "qst_wed_betrothed", slot_quest_expiration_days, 362),
           (call_script, "script_add_notification_menu", "mnu_notification_player_wedding_day", ":feast_host", ":faction_object"),
		 (else_try),
           (check_quest_active, "qst_wed_betrothed_female"),
		   
           (quest_get_slot, ":player_betrothed", "qst_wed_betrothed", slot_quest_giver_troop),
		   (store_faction_of_troop, ":player_betrothed_faction", ":player_betrothed"),
		   (eq, ":player_betrothed_faction", ":faction_no"),
           (neg|quest_slot_ge, "qst_wed_betrothed", slot_quest_expiration_days, 362),
           (call_script, "script_add_notification_menu", "mnu_notification_player_kingdom_holds_feast", ":feast_host", ":faction_object"),
         (else_try),
           (eq, "$players_kingdom", ":faction_no"),
           (troop_slot_ge, "trp_player", slot_troop_renown, 150),
		   
		   
           (party_get_slot, ":feast_host", ":faction_object", slot_town_lord),
           (call_script, "script_add_notification_menu", "mnu_notification_player_kingdom_holds_feast", ":feast_host", ":faction_object"),
         (try_end),
       (try_end),
		

       #Offensive begins
       (try_begin),
         (eq, ":old_faction_ai_state", sfai_gathering_army),
         (is_between, ":new_strategy", sfai_attacking_center, sfai_feast),
		 (try_begin),
			(eq, "$cheat_mode", 1),
			(str_store_faction_name, s5, ":faction_no"),
			(display_message, "str_s5_begins_offensive"),
		 (try_end),
			
         #Appoint screening party
         (try_begin),
           (assign, ":total_lords_participating", 0),
           (assign, ":best_screening_party", -1),
           (assign, ":score_to_beat", 30), #closest in size to 50
           (troop_get_slot, ":faction_marshal_party", ":faction_marshal", slot_troop_leaded_party),
           (party_is_active, ":faction_marshal_party"),							

           (try_for_range, ":screen_leader", active_npcs_begin, active_npcs_end),
             (store_faction_of_troop, ":screen_leader_faction", ":screen_leader"),
             (eq, ":screen_leader_faction", ":faction_no"),
			 
             (troop_get_slot, ":screening_party", ":screen_leader_faction", slot_troop_leaded_party), 
             (party_is_active, ":screening_party"),			
             (party_slot_eq, ":screening_party", slot_party_ai_state, spai_accompanying_army),
             (party_slot_eq, ":screening_party", slot_party_ai_object, ":faction_marshal_party"),
             (val_add, ":total_lords_participating", 1),

		     (try_begin),
			  (ge, "$cheat_mode", 1),
		      (str_store_party_name, s4, ":screening_party"),
			  (display_message, "@{!}DEBUG -- {s4} participates in offensive"),
		     (try_end),

			 
             (store_party_size_wo_prisoners, ":screening_party_score", ":screening_party"),
             (val_sub, ":screening_party_score", 50),
			 (val_abs, ":screening_party_score"),
			 
			 
			 (lt, ":screening_party_score", ":score_to_beat"),

             #set party and score
             (assign, ":best_screening_party", ":screening_party"),
             (assign, ":score_to_beat", ":screening_party_score"),
           (try_end),			

           (gt, ":total_lords_participating", 2),
           (party_is_active, ":best_screening_party"),
           (party_is_active, ":faction_marshal_party"),
           (call_script, "script_party_set_ai_state", ":best_screening_party", spai_screening_army, ":faction_marshal_party"),
		   (try_begin),
			(ge, "$cheat_mode", 1),
		    (str_store_party_name, s4, ":best_screening_party"),
			(display_message, "@{!}DEBUG -- {s4} chosen as screen"),
		   (try_end),
           #after this - dialogs on what doing, npc_decision_checklist
         (try_end),	
		 
       #Offensive concludes
       (else_try),
	     (store_current_hours, ":hours"),
         (this_or_next|eq, ":old_faction_ai_state", sfai_gathering_army),
         (this_or_next|eq, ":old_faction_ai_state", sfai_attacking_center),
         (this_or_next|eq, ":old_faction_ai_state", sfai_raiding_village),
		 #(this_or_next|eq, ":old_faction_ai_state", sfai_attacking_enemies_around_center),
			(eq, ":old_faction_ai_state", sfai_attacking_enemy_army),
		 
         (this_or_next|eq, ":new_strategy", sfai_default),
			(eq, ":new_strategy", sfai_feast),				
						
         (call_script, "script_check_and_finish_active_army_quests_for_faction", ":faction_no"),       		 
         (faction_set_slot, ":faction_no", slot_faction_last_offensive_concluded, ":hours"),
        (try_end),
    (try_end),
	
    (try_begin),
       (eq, "$players_kingdom", ":faction_no"),
       (neg|faction_slot_eq, ":faction_no", slot_faction_ai_state, sfai_attacking_center),
       (check_quest_active, "qst_join_siege_with_army"),
       (call_script, "script_abort_quest", "qst_join_siege_with_army", 0),
    (try_end),

    (try_begin),
       #old condition to rest, I changed below part - ozan, to rest (a faction's old strategy should be feast or default) and (a faction's new strategy should be feast or default)
       #(this_or_next|eq, ":new_strategy", sfai_default),
       #(this_or_next|eq, ":new_strategy", sfai_feast),
       #(this_or_next|eq, ":old_faction_ai_state", sfai_default),
       #(eq, ":old_faction_ai_state", sfai_feast),
       
       #new condition to rest, (a faction's new strategy should be feast or default) and (":hours_at_current_state" > 20)
       (this_or_next|eq, ":new_strategy", sfai_default),
		(eq, ":new_strategy", sfai_feast),                            
              
       (store_current_hours, ":hours_at_current_state"),
       (faction_get_slot, ":current_state_started", ":faction_no", slot_faction_ai_current_state_started), 
       (val_sub, ":hours_at_current_state", ":current_state_started"),
       (ge, ":hours_at_current_state", 18), #Must have at least 18 hours to reset
              
       (store_current_hours, ":hours"),       
       (faction_set_slot, ":faction_no", slot_faction_ai_last_rest_time, ":hours"),		
    (try_end),     
  ]),
  
 ####################################

             
 	(
	"npc_decision_checklist_faction_ai_alt_dk2", #This is called from within decide_faction_ai, or from 
	[
		(store_script_param, ":troop_no", 1),
		
		(store_faction_of_troop, ":faction_no", ":troop_no"),
		
		(str_store_troop_name, s4, ":troop_no"),
		(str_store_faction_name, s33, ":faction_no"),
		(try_begin),
			(eq, "$cheat_mode", 1),
		    (display_message, "@{!}DEBUG -- {s4} produces a faction strategy for {s33}"),
		(try_end),
		  		  
		#INFORMATIONS COLLECTING STEP 0: Here we obtain general information about current faction like how much parties that faction has, which lord is the marshall, current ai state and current ai target object
		#(faction_get_slot, ":faction_strength", ":faction_no", slot_faction_number_of_parties),
		(faction_get_slot, ":faction_marshal", ":faction_no", slot_faction_marshall),
		(faction_get_slot, ":current_ai_state", ":faction_no", slot_faction_ai_state),
		(faction_get_slot, ":current_ai_object", ":faction_no", slot_faction_ai_object),
		
		(assign, ":marshal_party", -1),
		(assign, ":marshal_party_strength", 0),
		  
		(try_begin),
		  (gt, ":faction_marshal", 0),
		  (troop_get_slot, ":marshal_party", ":faction_marshal", slot_troop_leaded_party),
		  (party_is_active, ":marshal_party"),
		  (party_get_slot, ":marshal_party_itself_strength", ":marshal_party", slot_party_cached_strength),
		  (party_get_slot, ":marshal_party_follower_strength", ":marshal_party", slot_party_follower_strength),
		  (store_add, ":marshal_party_strength", ":marshal_party_itself_strength", ":marshal_party_follower_strength"),
	    (try_end),
					
	    #INFORMATIONS COLLECTING STEP 1: Here we are learning how much hours past from last offensive situation/feast concluded/current state started
	    (store_current_hours, ":hours_since_last_offensive"),
	    (faction_get_slot, ":last_offensive_time", ":faction_no", slot_faction_last_offensive_concluded),
	    (val_sub, ":hours_since_last_offensive", ":last_offensive_time"),
	      
	    (store_current_hours, ":hours_since_last_feast_start"),
	    (faction_get_slot, ":last_feast_time", ":faction_no", slot_faction_last_feast_start_time),
	    (val_sub, ":hours_since_last_feast_start", ":last_feast_time"),
	      
	    (store_current_hours, ":hours_at_current_state"),
	    (faction_get_slot, ":current_state_started", ":faction_no", slot_faction_ai_current_state_started),
	    (val_sub, ":hours_at_current_state", ":current_state_started"),
	      
	    (store_current_hours, ":hours_since_last_faction_rest"),
	    (faction_get_slot, ":last_rest_time", ":faction_no", slot_faction_ai_last_rest_time),
	    (val_sub, ":hours_since_last_faction_rest", ":last_rest_time"),
			  
	    (try_begin), #calculating ":last_offensive_time_score", this will be used in #11 and #12
	        (ge, ":hours_since_last_offensive", 1080), #more than 45 days (100p)
	        (assign, ":last_offensive_time_score", 100),
	    (else_try),
	        (ge, ":hours_since_last_offensive", 480), #more than 20 days (65p..99p)
	        (store_sub, ":last_offensive_time_score", ":hours_since_last_offensive", 480),
	        (val_div, ":last_offensive_time_score", 20), 
	        (val_add, ":last_offensive_time_score", 64),
	    (else_try),
	        (ge, ":hours_since_last_offensive", 240), #more than 10 days (41p..64p)
	        (store_sub, ":last_offensive_time_score", ":hours_since_last_offensive", 240),
	        (val_div, ":last_offensive_time_score", 10), 
	        (val_add, ":last_offensive_time_score", 40),
	    (else_try), #less than 10 days (0p..40p)
	        (store_div, ":last_offensive_time_score", ":hours_since_last_offensive", 6), #0..40
	    (try_end),
									
	    #INFORMATION COLLECTING STEP 3: Here we are finding the most threatened center
	    (call_script, "script_find_center_to_defend", ":troop_no"),
	    (assign, ":most_threatened_center", reg0),
	    (assign, ":threat_danger_level", reg1),
	    (assign, ":enemy_strength_near_most_threatened_center", reg2), #NOTE! This will be off by as much as 50%
		  		 	      		
	    #INFORMATION COLLECTING STEP 4: Here we are finding number of vassals who are already following the marshal, and the assigned vassal ratio of current faction.
	    (assign, ":vassals_already_assembled", 0),
	    (assign, ":total_vassals", 0),	
	    (try_for_range, ":lord", active_npcs_begin, active_npcs_end),
	        (store_faction_of_troop, ":lord_faction", ":lord"),
	        (eq, ":lord_faction", ":faction_no"),
	        (troop_get_slot, ":led_party", ":lord", slot_troop_leaded_party),
	        (party_is_active, ":led_party"),
	        (val_add, ":total_vassals", 1),
			
	        (party_slot_eq, ":led_party", slot_party_ai_state, spai_accompanying_army),
	        (party_slot_eq, ":led_party", slot_party_ai_object, ":marshal_party"),
			
	        (party_is_active, ":marshal_party"),
	        (store_distance_to_party_from_party, ":distance_to_marshal", ":led_party", ":marshal_party"),
	        (lt, ":distance_to_marshal", 15),
	        (val_add, ":vassals_already_assembled", 1),
	    (try_end),
	    (assign, ":ratio_of_vassals_assembled", -1),
	    (try_begin),
	        (gt, ":total_vassals", 0),
	        (store_mul, ":ratio_of_vassals_assembled", ":vassals_already_assembled", 100),
	        (val_div, ":ratio_of_vassals_assembled", ":total_vassals"),
	    (try_end),
		
	    #50% of vassals means that the campaign hour limit is ten days
	    (store_mul, ":campaign_hour_limit", ":ratio_of_vassals_assembled", 3),
	    (val_add, ":campaign_hour_limit", 90), 
	    
	    #To Steve - I understand your concern about some marshals will gather army and some will not be able to find any valueable center to attack after gathering,
	    #and these marshals will be questioned by other marshals ext. This is ok but if we search for a target without adding all other vassals what if 
	    #AI cannot find any target for long time because of its low power ratio if enemy cities are equal defended? Do not forget if we do not count other vassals in 
	    #faction while making target search we can only add marshal army's power and vassals around him. And if there is any threat in our centers even it is smaller, 
	    #its threat_danger_level will be more than target_value_level if marshal new started gathering for ofensive. Because we only assume marshal and around vassals 
	    #will join attack. And in our scenarios currently there are less vassals are around him. So power ratio will be low and any small threat will be enought to stop 
	    #an offensive. Then when players finds out this they periodically will take under siege to enemy's any center and they will be saved from any kind of newly started 
	    #offensive they will be faced. So we have to calculate both attack levels and select highest one to compare with threat level. Please do not change this part.
		
		(try_begin),
	 
		  (ge, ":faction_marshal", 0),
		  (ge, ":marshal_party", 0),
		  (party_is_active, ":marshal_party"),

		  (call_script, "script_party_count_fit_for_battle", ":marshal_party"),
		  (assign, ":number_of_fit_soldiers_in_marshal_party", reg0),
		  (ge, ":number_of_fit_soldiers_in_marshal_party", 40),
		  
		  (call_script, "script_find_center_to_attack_alt_dk2", ":troop_no", 1, 0),
		  (assign, ":center_to_attack_all_vassals_included", reg0),
		  (assign, ":target_value_level_all_vassals_included", reg1),
		  
		  (call_script, "script_find_center_to_attack_alt_dk2", ":troop_no", 1, 1),
		  (assign, ":center_to_attack_only_marshal_and_followers", reg0),
		  (assign, ":target_value_level_only_marshal_and_followers", reg1),
		(else_try),  
		  (assign, ":target_value_level_all_vassals_included", 0),
		  (assign, ":target_value_level_only_marshal_and_followers", 0),
		  (assign, ":center_to_attack_all_vassals_included", -1),
		  (assign, ":center_to_attack_only_marshal_and_followers", -1),
		(try_end),
		
		(try_begin),
		  (ge, ":target_value_level_all_vassals_included", ":center_to_attack_only_marshal_and_followers"),
		  (assign, ":center_to_attack", ":center_to_attack_all_vassals_included"),
		  (assign, ":target_value_level", ":target_value_level_all_vassals_included"),
		(else_try),  
		  (assign, ":center_to_attack", ":center_to_attack_only_marshal_and_followers"),
		  (assign, ":target_value_level", ":target_value_level_only_marshal_and_followers"),
		(try_end),
		  		  
		(try_begin),
		  (eq, ":current_ai_state", sfai_attacking_center),
		  (val_mul, ":target_value_level", 3),
		  (val_div, ":target_value_level", 2),
		(try_end),

		(try_begin), #NE
		  (eq, "$cheat_mode", 1),
		  (try_begin),
		    (is_between, ":center_to_attack", centers_begin, centers_end),
		    (str_store_party_name, s4, ":center_to_attack"),
		    (display_message, "@{!}Best offensive target {s4} has value level of {reg1}"),
		  (else_try),
		    (display_message, "@{!}No center found to attack"),
		  (try_end),	
		
		  (try_begin),
		    (is_between, ":most_threatened_center", centers_begin, centers_end),
		    (str_store_party_name, s4, ":most_threatened_center"),
		    (assign, reg1, ":threat_danger_level"),
		    (display_message, "@{!}Best threat of {s4} has value level of {reg1}"),
		  (else_try),
		    (display_message, "@{!}No center found to defend"),
		  (try_end),  
		(try_end),
		
		(try_begin),
		  (eq, "$cheat_mode", 1),
		  
		  (try_begin),
  		    (is_between, ":most_threatened_center", centers_begin, centers_end),
 		    (str_store_party_name, s4, ":most_threatened_center"),
		    (assign, reg1, ":threat_danger_level"),
		    (display_message, "@Best threat of {s4} has value level of {reg1}"),
		  (else_try),
		    (display_message, "@No center found to defend"),
		  (try_end),  
		(try_end),  
				
	    (assign, "$g_target_after_gathering", -1),
	    
	    (store_current_hours, ":hours"),	      
	    (try_begin),
	      (ge, ":target_value_level", ":threat_danger_level"),
	      (faction_set_slot, ":faction_no", slot_faction_last_safe_hours, ":hours"),	  
	    (try_end),  
	    (faction_get_slot, ":last_safe_hours", ":faction_no", slot_faction_last_safe_hours),
	    (try_begin),
	      (eq, ":last_safe_hours", 0),
	      (faction_set_slot, ":faction_no", slot_faction_last_safe_hours, ":hours"),	  
	    (try_end),
	    (faction_get_slot, ":last_safe_hours", ":faction_no", slot_faction_last_safe_hours),
	    (store_sub, ":hours_since_days_defensive_started", ":hours", ":last_safe_hours"),
	    (str_store_faction_name, s7, ":faction_no"),

		(assign, ":at_peace_with_everyone", 1),
		(try_for_range, ":faction_at_war", kingdoms_begin, kingdoms_end),
			(store_relation, ":relation", ":faction_no", ":faction_at_war"),
			(lt, ":relation", 0),
			(assign, ":at_peace_with_everyone", 0),
		(try_end),

	    
	    #INFORMATIONS ARE COLLECTED, NOW CHECK ALL POSSIBLE ACTIONS AND DECIDE WHAT TO DO	NEXT
		#Player marshal
		(try_begin), # a special case to end long-running feasts
			(eq, ":troop_no", "trp_player"),
				
			(eq, ":current_ai_state", sfai_feast),
			(ge, ":hours_at_current_state", 72),
		
			(assign, ":action", sfai_default),
			(assign, ":object", -1),
			
			#Normally you are not supposed to set permanent values in this state, but this is a special case to end player-called feasts
			(assign, "$player_marshal_ai_state", sfai_default),
			(assign, "$player_marshal_ai_object", -1),
		(else_try), #another special state, to make player-called feasts last for a while when the player is the leader of the faction, but not the marshal
			(eq, "$players_kingdom", "fac_player_supporters_faction"),
			(faction_slot_eq, "$players_kingdom", slot_faction_leader, "trp_player"),
			(neq, ":troop_no", "trp_player"),
			
			(eq, ":current_ai_state", sfai_feast),
			(le, ":hours_at_current_state", 48),
			
			(party_slot_eq, ":current_ai_object", slot_town_lord, "trp_player"),
			(store_faction_of_party, ":current_ai_object_faction", ":current_ai_object"),
			(eq, ":current_ai_object_faction", "$players_kingdom"),
			
			(assign, ":action", sfai_feast),
			(assign, ":object", ":current_ai_object"),

			
		(else_try), #this is the main player marshal state
			(eq, ":troop_no", "trp_player"),
			
			(str_clear, s14),
			(assign, ":action", "$player_marshal_ai_state"),
			(assign, ":object", "$player_marshal_ai_object"),
			
	    #1-RESTING IF NEEDED 
	    #If not currently attacking a besieging a center and vassals did not rest for long time, let them rest.
	    #If we do not take this part to toppest level, tired vassals already did not accept any order, so that 
	    #faction cannot do anything already. So first let vassals rest if they need. Thats why it should be toppest.
		(else_try),
			(neq, ":current_ai_state", sfai_default),
			(neq, ":current_ai_state", sfai_feast),
			(party_is_active, ":marshal_party"),
		
			(party_slot_eq, ":marshal_party", slot_party_ai_state, spai_retreating_to_center),
			
			(assign, ":action", sfai_default),
			(assign, ":object", -1),
			(str_store_string, s14, "str_the_enemy_temporarily_has_the_field"),
				
		(else_try), 
		    (neq, ":current_ai_state", sfai_feast),
		    
		    (assign, ":currently_besieging", 0),
		    (try_begin),
			    (eq, ":current_ai_state", sfai_attacking_center),
			    (is_between, ":current_ai_object", walled_centers_begin, walled_centers_end),
			    (party_get_slot, ":besieger_party", ":current_ai_object", slot_center_is_besieged_by),
			    (party_is_active, ":besieger_party"),
			    (store_faction_of_party, ":besieger_faction", ":besieger_party"),
			    (eq, ":besieger_faction", ":faction_no"),
			    (assign, ":currently_besieging", 1),
		    (try_end),
		    
		    (assign, ":currently_defending_center", 0),
	        (try_begin),
		        (eq, ":current_ai_state", sfai_attacking_enemies_around_center),
		        (gt, ":marshal_party", 0),
		        (party_is_active, ":marshal_party"),

				(assign, ":besieged_center", -1),          
				(try_begin),
					(party_slot_eq, ":marshal_party", slot_party_ai_state, spai_holding_center), #if commander is holding a center
					(party_get_slot, ":marshal_object", ":marshal_party", slot_party_ai_object), #get commander's ai object (center they are holding)
					(party_get_battle_opponent, ":besieger_enemy", ":marshal_object"), #get this object's battle opponent
					(ge, ":besieger_enemy", 0),
					(assign, ":besieged_center", ":marshal_object"),
				(else_try),
					(party_slot_eq, ":marshal_party", slot_party_ai_state, spai_engaging_army), #if commander is engaging an army
					(party_get_slot, ":marshal_object", ":marshal_party", slot_party_ai_object), #get commander's ai object (army which they engaded)
					(ge, ":marshal_object", 0), #if commander has an object
					(neg|is_between, ":marshal_object", centers_begin, centers_end), #if this object is not a center, so it is a party
					(party_is_active, ":marshal_object"),
					(party_get_battle_opponent, ":besieged_center", ":marshal_object"), #get this object's battle opponent
				(try_end),
	          
				(eq, ":besieged_center", ":current_ai_object"),
				(assign, ":currently_defending_center", 1),
	        (try_end),

		    (eq, ":currently_besieging", 0),	    
		    (eq, ":currently_defending_center", 0),
		    (ge, ":hours_since_last_faction_rest", 1240),

			(assign, ":action", sfai_default),
			(assign, ":object", -1),
			(str_store_string, s14, "str_the_vassals_are_tired_we_let_them_rest_for_some_time"),	    
		
	  #2-DEFENSIVE ACTIONS : GATHERING ARMY FOR DEFENDING
          (else_try),
            (party_is_active, ":marshal_party"),
			(eq, ":at_peace_with_everyone", 0),
            
            (is_between, ":most_threatened_center", centers_begin, centers_end),
            (gt, ":threat_danger_level", ":target_value_level"),
                        
            (assign, ":continue_gathering", 0),
            (assign, ":start_gathering", 0),
            
            (try_begin),
              (is_between, ":most_threatened_center", villages_begin, villages_end),

              (assign, ":continue_gathering", 0),
            (else_try),
              (try_begin),
                (lt, ":hours_since_days_defensive_started", 3),
                (assign, ":multiplier", 150),
              (else_try),
                (lt, ":hours_since_days_defensive_started", 6),
                (assign, ":multiplier", 140),
              (else_try),
                (lt, ":hours_since_days_defensive_started", 9),
                (assign, ":multiplier", 132),
              (else_try),
                (lt, ":hours_since_days_defensive_started", 12),
                (assign, ":multiplier", 124),
              (else_try),
                (lt, ":hours_since_days_defensive_started", 15),
                (assign, ":multiplier", 118),
              (else_try),
                (lt, ":hours_since_days_defensive_started", 18),
                (assign, ":multiplier", 114),
              (else_try),
                (lt, ":hours_since_days_defensive_started", 21),
                (assign, ":multiplier", 110),
              (else_try),
                (lt, ":hours_since_days_defensive_started", 24),
                (assign, ":multiplier", 106),
              (else_try),
                (lt, ":hours_since_days_defensive_started", 27),
                (assign, ":multiplier", 102),
              (else_try),
                (lt, ":hours_since_days_defensive_started", 31), 
                (assign, ":multiplier", 98),
              (else_try),
                (lt, ":hours_since_days_defensive_started", 34),
                (assign, ":multiplier", 94),
              (else_try),
                (lt, ":hours_since_days_defensive_started", 37),
                (assign, ":multiplier", 90),
              (else_try),
                (lt, ":hours_since_days_defensive_started", 40),
                (assign, ":multiplier", 86),
              (else_try),
                (lt, ":hours_since_days_defensive_started", 43),
                (assign, ":multiplier", 82),
              (else_try),
                (lt, ":hours_since_days_defensive_started", 46),
                (assign, ":multiplier", 79),
              (else_try),
                (lt, ":hours_since_days_defensive_started", 49),
                (assign, ":multiplier", 76),
              (else_try),
                (lt, ":hours_since_days_defensive_started", 52),
                (assign, ":multiplier", 73),
              (else_try),
                (lt, ":hours_since_days_defensive_started", 56),
                (assign, ":multiplier", 70),
              (else_try),
                (lt, ":hours_since_days_defensive_started", 60),
                (assign, ":multiplier", 68),
              (else_try),
                (lt, ":hours_since_days_defensive_started", 66),
                (assign, ":multiplier", 66),
              (else_try),
                (lt, ":hours_since_days_defensive_started", 72),
                (assign, ":multiplier", 64),
              (else_try),
                (lt, ":hours_since_days_defensive_started", 80),
                (assign, ":multiplier", 62),
              (else_try),
                (lt, ":hours_since_days_defensive_started", 90),
                (assign, ":multiplier", 60),
              (else_try),
                (lt, ":hours_since_days_defensive_started", 100),
                (assign, ":multiplier", 58),
              (else_try),
                (assign, ":multiplier", 56),
              (try_end),
		  
              (store_mul, ":enemy_strength_multiplied", ":enemy_strength_near_most_threatened_center", ":multiplier"),
              (val_div, ":enemy_strength_multiplied", 100),
		  
              (try_begin),		  
                (lt, ":marshal_party_strength", ":enemy_strength_multiplied"),
                (assign, ":continue_gathering", 1),
              (try_end),
            (else_try),  
              (eq, ":current_ai_state", sfai_attacking_enemies_around_center),
              (neq, ":most_threatened_center", ":current_ai_object"),
		  
              (assign, ":marshal_is_already_defending_a_center", 0),
              (try_begin),
                (gt, ":marshal_party", 0),
                (party_is_active, ":marshal_party"),
       
                (assign, ":besieged_center", -1),          
                (try_begin),
                  (party_slot_eq, ":marshal_party", slot_party_ai_state, spai_holding_center), #if commander is holding a center
                  (party_get_slot, ":marshal_object", ":marshal_party", slot_party_ai_object), #get commander's ai object (center they are holding)
                  (party_get_battle_opponent, ":besieger_enemy", ":marshal_object"), #get this object's battle opponent
                  (ge, ":besieger_enemy", 0),
                  (assign, ":besieged_center", ":marshal_object"),
                (else_try),              
                  (party_slot_eq, ":marshal_party", slot_party_ai_state, spai_engaging_army), #if commander is engaging an army
                  (party_get_slot, ":marshal_object", ":marshal_party", slot_party_ai_object), #get commander's ai object (army which they engaded)
                  (ge, ":marshal_object", 0), #if commander has an object
                  (neg|is_between, ":marshal_object", centers_begin, centers_end), #if this object is not a center, so it is a party
				  (party_is_active, ":marshal_object"),
                  (party_get_battle_opponent, ":besieged_center", ":marshal_object"), #get this object's battle opponent
                (try_end),

                (eq, ":besieged_center", ":current_ai_object"),
            
                (assign, ":marshal_is_already_defending_a_center", 1),
              (try_end),
                    
              (eq, ":marshal_is_already_defending_a_center", 0),
		  
              (store_mul, ":enemy_strength_multiplied", ":enemy_strength_near_most_threatened_center", 80),
              (val_div, ":enemy_strength_multiplied", 100),
              (lt, ":marshal_party_strength", ":enemy_strength_multiplied"),
              
              (this_or_next|is_between, ":most_threatened_center", walled_centers_begin, walled_centers_end),
              (neq, ":faction_no", "$players_kingdom"),              
              
              (assign, ":start_gathering", 1),
            (try_end),
		
            (this_or_next|eq, ":continue_gathering", 1),
            (eq, ":start_gathering", 1),
		
            (assign, ":action", sfai_gathering_army),
            (assign, ":object", -1),		
            (str_store_party_name, s21, ":most_threatened_center"),
            (str_store_string, s14, "str_we_should_prepare_to_defend_s21_but_we_should_gather_our_forces_until_we_are_strong_enough_to_engage_them"),
            
            (try_begin),
              (eq, ":faction_no", "$players_kingdom"),
              (assign, "$g_gathering_reason", ":most_threatened_center"),
            (try_end),
			
	    #3-DEFENSIVE ACTIONS : RIDE TO BREAK ENEMY SIEGE / DEFEAT ENEMIES NEAR OUR CENTER
		(else_try),
			(party_is_active, ":marshal_party"),
			(is_between, ":most_threatened_center", walled_centers_begin, walled_centers_end),
			(ge, ":threat_danger_level", ":target_value_level"),
			(party_slot_ge, ":most_threatened_center", slot_center_is_besieged_by, 0),

			(assign, ":action", sfai_attacking_enemies_around_center),
			(assign, ":object", ":most_threatened_center"),
						
			(str_store_party_name, s21, ":most_threatened_center"),
			(str_store_string, s14, "str_we_should_ride_to_break_the_siege_of_s21"),
			
		#3b - DEFEAT ENEMIES NEAR CENTER - similar to above, but a different string
		(else_try),
			(party_is_active, ":marshal_party"),
			(ge, ":threat_danger_level", ":target_value_level"),
			(is_between, ":most_threatened_center", villages_begin, villages_end),
		
			(assign, ":action", sfai_attacking_enemies_around_center),
			(assign, ":object", ":most_threatened_center"),
			(str_store_party_name, s21, ":most_threatened_center"),
			(str_store_string, s14, "str_we_should_ride_to_defeat_the_enemy_gathered_near_s21"),
				
		#4-DEMOBILIZATION
		#Let vassals attend their own business
		(else_try),
			(this_or_next|eq, ":current_ai_state", sfai_gathering_army), 				
			(this_or_next|eq, ":current_ai_state", sfai_attacking_center),
			(eq, ":current_ai_state", sfai_raiding_village),

			(ge, ":hours_since_last_faction_rest", ":campaign_hour_limit"), #Effected by ratio of vassals
			(ge, ":hours_at_current_state", 24),
			
			#Ozan : I am adding some codes here because sometimes armies demobilize during last seconds of an important event like taking a castle, ext.
			(assign, ":there_is_an_important_situation", 0),
			(try_begin), #do not demobilize during taking a castle/town (fighting in the castle)
				(is_between, ":current_ai_object", walled_centers_begin, walled_centers_end),
				(party_get_battle_opponent, ":besieger_party", ":current_ai_object"),
				(party_is_active, ":besieger_party"),
				(store_faction_of_party, ":besieger_faction", ":besieger_party"),
				(this_or_next|eq, ":besieger_faction", ":faction_no"),
				(eq, ":besieger_faction", "fac_player_faction"),
				(assign, ":there_is_an_important_situation", 1),
			(else_try), #do not demobilize during besieging a siege (holding around castle)
				(is_between, ":current_ai_object", walled_centers_begin, walled_centers_end),
				(party_get_slot, ":besieger_party", ":current_ai_object", slot_center_is_besieged_by),
				(party_is_active, ":besieger_party"),
				(store_faction_of_party, ":besieger_faction", ":besieger_party"),
				(this_or_next|eq, ":besieger_faction", ":faction_no"),
				(eq, ":besieger_faction", "fac_player_faction"),		  
				(assign, ":there_is_an_important_situation", 1),
			(else_try), #do not demobilize during raiding a village (holding around village)
				(is_between, ":current_ai_object", centers_begin, centers_end),
				(neg|is_between, ":current_ai_object", walled_centers_begin, walled_centers_end),		  
				(party_slot_eq, ":current_ai_object", slot_village_state, svs_being_raided),
				(assign, ":there_is_an_important_situation", 1),
			(try_end),
			
			(eq, ":there_is_an_important_situation", 0),
			#end addition ozan
						
			(assign, reg7, ":hours_since_last_faction_rest"),
			(assign, reg8, ":campaign_hour_limit"),
		
			(str_store_string, s14, "str_this_offensive_needs_to_wind_down_soon_so_the_vassals_can_attend_to_their_own_business"),		
			(assign, ":action", sfai_default),
			(assign, ":object", -1),
			
		#6-GATHERING BECAUSE OF NO REASON
		#Start to gather the army
		(else_try),
			(party_is_active, ":marshal_party"),
			(eq, ":at_peace_with_everyone", 0),
			
			
			(eq, ":current_ai_state", sfai_default),
			(ge, ":hours_since_last_offensive", 60),
			(lt, ":hours_since_last_faction_rest", 120),
			
			#There should not be a center as a precondition for attack	
			#Otherwise, we are unlikely to have a situation in which the army gathers, but does nothing -- which is important to have for role-playing purposes
			
			(assign, ":action", sfai_gathering_army),
			(assign, ":object", -1),	
			(str_store_string, s14, "str_it_is_time_to_go_on_the_offensive_and_we_must_first_assemble_the_army"),
		
            (try_begin),
              (eq, ":faction_no", "$players_kingdom"),
              (assign, "$g_gathering_reason", -1),
            (try_end),

		#7-OFFENSIVE ACTIONS : CONTINUE GATHERING
		(else_try),		
			(party_is_active, ":marshal_party"),
			(eq, ":current_ai_state", sfai_gathering_army),
			(eq, ":at_peace_with_everyone", 0),

			(lt, ":hours_at_current_state", 24), #gather army for 54 hours   #NE 24 hours
			
			(lt, ":ratio_of_vassals_assembled", 12),

			(str_store_string, s14, "str_we_must_continue_to_gather_the_army_before_we_ride_forth_on_an_offensive_operation"),
			(assign, ":action", sfai_gathering_army),
			(assign, ":object", -1),

		#7-OFFENSIVE ACTIONS PART 2 : CONTINUE GATHERING
		(else_try),
		    (assign, ":minimum_possible_attackable_target_value_level", 50),
			(eq, ":at_peace_with_everyone", 0),

            (try_begin), #agressive marshal            
			  (troop_get_slot, ":reputation", ":troop_no", slot_lord_reputation_type),
			  (this_or_next|eq, ":reputation", lrep_martial),
			  (this_or_next|eq, ":reputation", lrep_quarrelsome),
			  (eq, ":reputation", lrep_selfrighteous),
			  (val_mul, ":minimum_possible_attackable_target_value_level", 9),
			  (val_div, ":minimum_possible_attackable_target_value_level", 10),
            (try_end),		              

			(party_is_active, ":marshal_party"),
			(eq, ":current_ai_state", sfai_gathering_army),
								
			(try_begin),
				(lt, ":hours_at_current_state", 6),
				(assign, ":minimum_needed_target_value_level", 1500),
			(else_try),
				(lt, ":hours_at_current_state", 10),
				(assign, ":minimum_needed_target_value_level", 1000),
			(else_try),  
		        (lt, ":hours_at_current_state", 14),
		        (assign, ":minimum_needed_target_value_level", 720),
			(else_try),  
				(lt, ":hours_at_current_state", 18),
				(assign, ":minimum_needed_target_value_level", 480),
			(else_try),  
				(lt, ":hours_at_current_state", 22),
				(assign, ":minimum_needed_target_value_level", 360),
			(else_try),  
				(lt, ":hours_at_current_state", 26),
				(assign, ":minimum_needed_target_value_level", 240),
			(else_try),  
				(lt, ":hours_at_current_state", 30),
				(assign, ":minimum_needed_target_value_level", 180),
			(else_try),  
				(lt, ":hours_at_current_state", 34),
				(assign, ":minimum_needed_target_value_level", 120),
			(else_try),  
				(lt, ":hours_at_current_state", 38),
				(assign, ":minimum_needed_target_value_level", 100),
			(else_try),  
				(lt, ":hours_at_current_state", 42),
				(assign, ":minimum_needed_target_value_level", 80),
			(else_try),  
				(lt, ":hours_at_current_state", 46),
				(assign, ":minimum_needed_target_value_level", 65),
			(else_try),  
				(lt, ":hours_at_current_state", 50),
				(assign, ":minimum_needed_target_value_level", 55),
			(else_try),	
				(assign, ":minimum_needed_target_value_level", ":minimum_possible_attackable_target_value_level"),
			(try_end),  

            (try_begin), #agressive marshal            
			  (troop_get_slot, ":reputation", ":troop_no", slot_lord_reputation_type),
			  (this_or_next|eq, ":reputation", lrep_martial),
			  (this_or_next|eq, ":reputation", lrep_quarrelsome),
			  (eq, ":reputation", lrep_selfrighteous),
			  (val_mul, ":minimum_needed_target_value_level", 9),
			  (val_div, ":minimum_needed_target_value_level", 10),
            (try_end),		  
						
			(le, ":target_value_level", ":minimum_needed_target_value_level"),
			(le, ":hours_at_current_state", 24),  #NE 24
		
			(str_store_string, s14, "str_we_have_assembled_some_vassals"),
			(assign, ":action", sfai_gathering_army),
			(assign, ":object", -1),
				
		#8-ATTACK AN ENEMY CENTER case 1, reconnaissance against walled center
		#(else_try),
			#(party_is_active, ":marshal_party"),
			#(neq, ":current_ai_state", sfai_default),
			#(neq, ":current_ai_state", sfai_feast),
			#(is_between, ":center_to_attack", walled_centers_begin, walled_centers_end),

			#(store_sub, ":faction_recce_slot", ":faction_no", kingdoms_begin),
			#(val_add, ":faction_recce_slot", slot_center_last_reconnoitered_by_faction_time),
			#(store_current_hours, ":hours_since_last_recon"),			
			#(party_get_slot, ":last_recon_time", ":center_to_attack", ":faction_recce_slot"), 
			#(val_sub, ":hours_since_last_recon", ":last_recon_time"),
			#(this_or_next|eq, ":last_recon_time", 0),
			#(gt, ":hours_since_last_recon", 96),
						
		    #(assign, ":action", sfai_attacking_center),
			#(assign, ":object", ":center_to_attack"),
			#(str_store_string, s14, "str_we_are_conducting_recce"),
			
		#8-ATTACK AN ENEMY CENTER case 2, reconnaissance against village
		#(else_try),  
			#(party_is_active, ":marshal_party"),
			#(neq, ":current_ai_state", sfai_default),
			#(neq, ":current_ai_state", sfai_feast),
			#(is_between, ":center_to_attack", villages_begin, villages_end),

			#(store_sub, ":faction_recce_slot", ":faction_no", kingdoms_begin),
			#(val_add, ":faction_recce_slot", slot_center_last_reconnoitered_by_faction_time),
			#(store_current_hours, ":hours_since_last_recon"),
			#(party_get_slot, ":last_recon_time", ":center_to_attack", ":faction_recce_slot"), 
			#(val_sub, ":hours_since_last_recon", ":last_recon_time"),
			#(this_or_next|eq, ":last_recon_time", 0),
			#(gt, ":hours_since_last_recon", 96),

			
			#(assign, ":action", sfai_raiding_village),
			#(assign, ":object", ":center_to_attack"),
			#(str_store_string, s14, "str_we_are_conducting_recce"),
		(else_try),
			(party_is_active, ":marshal_party"),
			(neq, ":current_ai_state", sfai_default),
			(neq, ":current_ai_state", sfai_feast),
			
			(assign, ":center_to_attack", ":center_to_attack_only_marshal_and_followers"),
			
			(is_between, ":center_to_attack", walled_centers_begin, walled_centers_end),
			
			(ge, ":target_value_level", ":minimum_possible_attackable_target_value_level"),
						
		    (assign, ":action", sfai_attacking_center),
			(assign, ":object", ":center_to_attack"),
			(str_store_string, s14, "str_we_believe_the_fortress_will_be_worth_the_effort_to_take_it"),
		# (else_try), #NE
			# (party_is_active, ":marshal_party"),
			# (neq, ":current_ai_state", sfai_default),
			# (neq, ":current_ai_state", sfai_feast),
			
			# (assign, ":center_to_attack", ":center_to_attack_only_marshal_and_followers"),
			
			# (is_between, ":center_to_attack", villages_begin, villages_end),
			
			# (ge, ":target_value_level", ":minimum_possible_attackable_target_value_level"),
		
			# (assign, ":action", sfai_raiding_village),
			# (assign, ":object", ":center_to_attack"),
			# (str_store_string, s14, "str_we_shall_leave_a_fiery_trail_through_the_heart_of_the_enemys_lands_targeting_the_wealthy_settlements_if_we_can"),
		
		#9 -- DISBAND THE ARMY
		(else_try),
			(eq, ":current_ai_state", sfai_gathering_army),			

			(str_store_string, s14, "str_the_army_will_be_disbanded_because_we_have_been_waiting_too_long_without_a_target"),

			(assign, ":action", sfai_default),
			(assign, ":object", -1),
		#OFFENSIVE OPERATIONS END

		#FEAST-RELATED OPERATIONS BEGIN
		#10-CONCLUDE CURRENT FEAST
		(else_try),
			(eq, ":current_ai_state", sfai_feast),
			(gt, ":hours_at_current_state", 72),
		
			(assign, ":action", sfai_default),
			(assign, ":object", -1),		
			(str_store_string, s14, "str_it_is_time_for_the_feast_to_conclude"),

		#11-CONTINE FEAST UNLESS THERE IS AN EMERGENCY
		(else_try),
			(eq, ":current_ai_state", sfai_feast),
			(le, ":hours_at_current_state", 72),
			
			(assign, ":action", sfai_feast),
			(assign, ":object", ":current_ai_object"),		
			(str_store_string, s14, "str_we_should_continue_the_feast_unless_there_is_an_emergency"),
		
		#12-HOLD A FEAST BECAUSE THE PLAYER WANTS TO ORGANIZE ONE
		(else_try),
			(check_quest_active, "qst_organize_feast"),
			(eq, "$players_kingdom", ":faction_no"),
		
			(quest_get_slot, ":target_center", "qst_organize_feast", slot_quest_target_center),
			
			(assign, ":action", sfai_feast),
			(assign, ":object", ":target_center"),		
			(str_store_string, s14, "str_you_had_wished_to_hold_a_feast"),
		
		#13-HOLD A FEAST BECAUSE FEMALE PLAYER SCHEDULED TO GET MARRIED
		(else_try),
			(check_quest_active, "qst_wed_betrothed_female"),
				 
			(quest_get_slot, ":groom", "qst_wed_betrothed_female", slot_quest_giver_troop),
			(troop_slot_eq, ":groom", slot_troop_prisoner_of_party, -1),
		
			(store_faction_of_troop, ":groom_faction", ":groom"),
			(eq, ":groom_faction", ":faction_no"),
				 
			(faction_get_slot, ":faction_leader", ":groom_faction", slot_faction_leader),
				 
			(assign, ":location_feast", -1),
			(try_for_range, ":possible_location", walled_centers_begin, walled_centers_end),
			   (eq, ":location_feast", -1),
			    (party_slot_eq, ":possible_location", slot_town_lord, ":groom"),
			    (party_slot_ge, ":possible_location", slot_center_is_besieged_by, 0),
			    (assign, ":location_feast", ":possible_location"),
			(try_end),
			
			(try_for_range, ":possible_location", walled_centers_begin, walled_centers_end),
				(eq, ":location_feast", -1),
				(party_slot_eq, ":possible_location", slot_town_lord, ":faction_leader"),
				(party_slot_ge, ":possible_location", slot_center_is_besieged_by, 0),
				(assign, ":location_feast", ":possible_location"),
			(try_end),
		 
			(is_between, ":location_feast", walled_centers_begin, walled_centers_end),

			(assign, ":action", sfai_feast),
			(assign, ":object", ":location_feast"),		
			(str_store_string, s14, "str_your_wedding_day_approaches_my_lady"),
		
		#14-HOLD A FEAST BECAUSE A MALE CHARACTER WANTS TO GET MARRIED
		(else_try),
			(check_quest_active, "qst_wed_betrothed"),
			(neg|quest_slot_ge, "qst_wed_betrothed", slot_quest_expiration_days, 362),
		
			(quest_get_slot, ":bride", "qst_wed_betrothed", slot_quest_target_troop),
			(call_script, "script_get_kingdom_lady_social_determinants", ":bride"),
			(assign, ":feast_host", reg0),
			(store_faction_of_troop, ":feast_host_faction", ":feast_host"),
			(eq, ":feast_host_faction", ":faction_no"),
		
			(troop_slot_eq, ":feast_host", slot_troop_prisoner_of_party, -1),
			(assign, ":wedding_venue", reg1),
		
			(is_between, ":wedding_venue", centers_begin, centers_end),
			(party_slot_eq, ":wedding_venue", slot_center_is_besieged_by, -1),
		
			(assign, ":action", sfai_feast),
			(assign, ":object", ":wedding_venue"),		
			(str_store_string, s14, "str_your_wedding_day_approaches"),
		
		#15-HOLD A FEAST BECAUSE AN NPC WANTS TO GET MARRIED
		(else_try),	
            (ge, ":hours_since_last_feast_start", 192), #If at least eight days past last feast start time
		
			(assign, ":location_feast", -1),
		
			(try_for_range, ":kingdom_lady", kingdom_ladies_begin, kingdom_ladies_end),
				(troop_get_slot, ":groom", ":kingdom_lady", slot_troop_betrothed),
				(gt, ":groom", 0), #not the player

				(store_faction_of_troop, ":lady_faction", ":kingdom_lady"),
				(store_faction_of_troop, ":groom_faction", ":groom"),
				
				(try_begin), #The groom checks if he wants to continue or break off relations. This causes actions, rather than just returns a value, so it probably should be moved elsewhere
					(troop_slot_ge, ":groom", slot_troop_prisoner_of_party, 0),		
				(else_try),
					(neq, ":groom_faction", ":lady_faction"),
					(neq, ":groom_faction", "fac_player_faction"),
					(call_script, "script_courtship_event_lady_break_relation_with_suitor", ":kingdom_lady", ":groom"),
				(else_try),
		            (eq, ":lady_faction", ":faction_no"),
		            (store_current_hours, ":hours_since_betrothal"),
		            (troop_get_slot, ":betrothal_time", ":kingdom_lady", slot_troop_betrothal_time),
		            (val_sub, ":hours_since_betrothal", ":betrothal_time"),
		            (ge, ":hours_since_betrothal", 719), #30 days
							
					(call_script, "script_get_kingdom_lady_social_determinants", ":kingdom_lady"), 
					(assign, ":wedding_venue", reg1),
				
		            (assign, ":location_feast", ":wedding_venue"),
		            (assign, ":final_bride", ":kingdom_lady"),
		            (assign, ":final_groom", ":groom"),
				(try_end),	
			(try_end),
		
			(ge, ":location_feast", centers_begin),
				 
			(assign, ":action", sfai_feast),
			(assign, ":object", ":location_feast"),
				
			(str_store_troop_name, s22, ":final_bride"),
			(str_store_troop_name, s23, ":final_groom"),		
			(str_store_string, s14, "str_s22_and_s23_wish_to_marry"),

		#16-HOLD A FEAST ANYWAY
		(else_try),
			(eq, ":current_ai_state", sfai_default),
            (gt, ":hours_since_last_feast_start", 740), #If at least 10 days past after last feast. (added by ozan)  #NE used to be 240

			(assign, ":location_high_score", 0),
			(assign, ":location_feast", -1),
        
			(try_for_range, ":location", walled_centers_begin, walled_centers_end),
				(store_faction_of_party, ":location_faction", ":location"),
				(eq, ":location_faction", ":faction_no"),

				(try_begin),
			        (neg|party_slot_eq, ":location", slot_village_state, svs_under_siege),
		            (party_get_slot, ":location_lord", ":location", slot_town_lord),
		            (is_between, ":location_lord", active_npcs_begin, active_npcs_end),
		            (troop_get_slot, ":location_score", ":location_lord", slot_troop_renown),
		            (store_random_in_range, ":random", 0, 1000), #will probably be king or senior lord
		            (val_add, ":location_score", ":random"),
		            (gt, ":location_score", ":location_high_score"),
		            (assign, ":location_high_score", ":location_score"),
		            (assign, ":location_feast", ":location"),				
				(else_try), #do not start new feasts if any place is under siege or being raided
		            (this_or_next|party_slot_eq, ":location", slot_village_state, svs_under_siege),
						(party_slot_eq, ":location", slot_village_state, svs_being_raided),
		            (assign, ":location_high_score", 9999),
		            (assign, ":location_feast", -1),
				(try_end),
			(try_end),

			(is_between, ":location_feast", walled_centers_begin, walled_centers_end),
			(party_get_slot, ":feast_host", ":location_feast", slot_town_lord),
			(troop_slot_eq, ":feast_host", slot_troop_prisoner_of_party, -1),
		
			(assign, ":action", sfai_feast),
			(assign, ":object", ":location_feast"),		
			(str_store_string, s14, "str_it_has_been_a_long_time_since_the_lords_of_the_realm_gathered_for_a_feast"),	
		
		#17-DO NOTHING #NE
		# (else_try),
			# (neq, ":current_ai_state", sfai_default),
		
			# (assign, ":action", sfai_default),
			# (assign, ":object", -1),		
			# (str_store_string, s14, "str_the_circumstances_which_led_to_this_decision_no_longer_apply_so_we_should_stop_and_reconsider_shortly"),	
	
		#18-DO NOTHING
		(else_try),
			(eq, ":current_ai_state", sfai_default),

			(eq, ":at_peace_with_everyone", 1),
				
		    (assign, ":action", sfai_default),
		    (assign, ":object", -1),		
			(str_store_string, s14, "str_we_are_currently_at_peace"),		
		(else_try),
			(eq, ":current_ai_state", sfai_default),
			(faction_slot_eq, ":faction_no", slot_faction_marshall, -1),				
		    (assign, ":action", sfai_default),
		    (assign, ":object", -1),		
			(str_store_string, s14, "str_we_are_waiting_for_selection_of_marshal"),		
		
		(else_try),
			(eq, ":current_ai_state", sfai_default),
								
		    (assign, ":action", sfai_default),
		    (assign, ":object", -1),		
			(str_store_string, s14, "str_the_vassals_still_need_time_to_attend_to_their_own_business"),		
		(try_end),
				
		(assign, reg0, ":action"),
		(assign, reg1, ":object"),		
	]),

####################################	
	    ("find_center_to_attack_alt_dk2",
    [
      (store_script_param, ":troop_no", 1),
      (store_script_param, ":attack_by_faction", 2),
      (store_script_param, ":all_vassals_included", 3),
      
      (assign, ":result", -1),
      (assign, ":score_to_beat", 0),
      
      (try_for_range, ":center_no", walled_centers_begin, walled_centers_end),            #NE changed to Walled
        (call_script, "script_npc_decision_checklist_evaluate_enemy_center_for_attack_dk2",	":troop_no", ":center_no", ":attack_by_faction", ":all_vassals_included"),
        (assign, ":score", reg0),
		
	    # (assign, reg1,  ":score"),
		# (str_store_party_name, s8, ":center_no"),       
          # (display_message, "@FUCK : attack of {s8} score to beat:{reg1}"),
                
        (gt, ":score", ":score_to_beat"),
        
        (assign, ":result", ":center_no"),
        (assign, ":score_to_beat", ":score"),
		

		  
      (try_end),
      

      (assign, reg0, ":result"),
      (assign, reg1, ":score_to_beat"),      
	  

		  
		  
	]),
	
	#####################################
	
		
  ("npc_decision_checklist_evaluate_enemy_center_for_attack_dk2",
    [
      #NOTES -- LAST OFFENSIVE TIME SCORE IS NOT USED
      
      (store_script_param, ":troop_no", 1),
      (store_script_param, ":potential_target", 2),
      (store_script_param, ":attack_by_faction", 3),
      (store_script_param, ":all_vassals_included", 4),
      
      (assign, ":result", -1),
      (assign, ":explainer_string", -1),
      #(assign, ":reason_is_obvious", 0),
      (assign, ":power_ratio", 0),
      #(assign, ":hours_since_last_recce", -1),
      
      #(assign, ":value_of_target", 0),
      #(assign, ":difficulty_of_capture", 0),
      (store_faction_of_troop, ":faction_no", ":troop_no"),
      
      (try_begin),
        (eq, ":attack_by_faction", 1),
        (faction_get_slot, ":faction_marshal", ":faction_no", slot_faction_marshall),
        (ge, ":faction_marshal", 0), #STEVE ADDITION TO AVOID MESSAGE SPAM
        (troop_get_slot, ":party_no", ":faction_marshal", slot_troop_leaded_party),
      (else_try),
        (troop_get_slot, ":party_no", ":troop_no", slot_troop_leaded_party),
      (try_end),
      
      (assign, "$g_use_current_ai_object_as_s8", 0),
            
      #THE FIRST BATCH OF DISQUALIFYING CONDITIONS DO NOT REQUIRE THE ATTACKING PARTY TO HAVE CURRENT INTELLIGENCE ON THE TARGET
      (try_begin),
        (neg|party_is_active, ":party_no"),
        
        (assign, ":result", -1),
        (assign, ":explainer_string", "str_center_party_not_active"),
        #(assign, ":reason_is_obvious", 1),
      (else_try), 
        (store_faction_of_party, ":potential_target_faction", ":potential_target"),
        (store_relation, ":relation", ":potential_target_faction", ":faction_no"),
        (ge, ":relation", 0),
        
        (assign, ":result", -1),
        (assign, ":explainer_string", "str_center_is_friendly"),
        #(assign, ":reason_is_obvious", 1),
      (else_try),
        (is_between, ":potential_target", walled_centers_begin, walled_centers_end),
        (assign, ":faction_of_besieger_party", -1),
        (try_begin),
          (neg|party_slot_eq, ":potential_target", slot_center_is_besieged_by, -1), 
          (party_get_slot, ":besieger_party", ":potential_target", slot_center_is_besieged_by),
          (party_is_active, ":besieger_party"),
          (store_faction_of_party, ":faction_of_besieger_party", ":besieger_party"),
        (try_end),
        
        (neq, ":faction_of_besieger_party", -1),
        (neq, ":faction_of_besieger_party", ":faction_no"),	
        
        (assign, ":result", -1),
        (assign, ":explainer_string", "str_center_is_already_besieged"),
        #(assign, ":reason_is_obvious", 1),
      (else_try),
        (is_between, ":potential_target", villages_begin, villages_end),
        (assign, ":village_is_looted_or_raided_already", 0),
        (try_begin),
          (party_slot_eq, ":potential_target", slot_village_state, svs_being_raided),
          (party_get_slot, ":raider_party", ":potential_target", slot_village_raided_by),
		  (party_is_active, ":raider_party"),
          (store_faction_of_party, ":raider_faction", ":raider_party"),
          (neq, ":raider_faction", ":faction_no"),
          (assign, ":raiding_by_one_other_faction", 1),
        (else_try),
          (assign, ":raiding_by_one_other_faction", 0),
        (try_end),
        
        (try_begin),
          (this_or_next|party_slot_eq, ":potential_target", slot_village_state, svs_looted),
          (eq, ":raiding_by_one_other_faction", 1),
          (assign, ":village_is_looted_or_raided_already", 1),
        (try_end),
        
        (eq, ":village_is_looted_or_raided_already", 1),
        
        (assign, ":result", -1),
        (assign, ":explainer_string", "str_center_is_looted_or_raided_already"),
        #(assign, ":reason_is_obvious", 1),
      (else_try),
        # (this_or_next|troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_upstanding), #NE
        # (troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_goodnatured),
        
        (is_between, ":potential_target", villages_begin, villages_end),	
        (assign, ":result", -1),
        (assign, ":explainer_string", "str_center_marshal_does_not_want_to_attack_innocents"),
      #(else_try),
        # (assign, ":distance_from_our_closest_walled_center", 1000),
        # (try_for_range, ":cur_center", walled_centers_begin, walled_centers_end),
           # (store_faction_of_party, ":cur_center_faction", ":cur_center"),
           # (eq, ":cur_center_faction", ":faction_no"),
           # (store_distance_to_party_from_party, ":distance_from_cur_center", ":cur_center", ":potential_target"),
           # (lt, ":distance_from_cur_center", ":distance_from_our_closest_walled_center"),
           # (assign, ":distance_from_our_closest_walled_center", ":distance_from_cur_center"),
        # (try_end),
                                                
        # (gt, ":distance_from_our_closest_walled_center", 75),
        # (this_or_next|troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_upstanding),
        # (this_or_next|troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_debauched),
        # (this_or_next|troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_goodnatured),
        # (troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_cunning),
        
        # (assign, ":result", -1),
        # (assign, ":explainer_string", "str_center_far_away_our_cautious_marshal_does_not_wish_to_reconnoiter"),	

        #NE - DKs won't have a base at start so take that into account
		
       # (assign, ":distance_from_our_closest_walled_center", 1000),
		# (assign, ":have_center", 0), 
        # (try_for_range, ":cur_center", walled_centers_begin, walled_centers_end),
           # (store_faction_of_party, ":cur_center_faction", ":cur_center"),
		   # (try_begin), 
           # (eq, ":cur_center_faction", "fac_dark_knights"),
		   # (assign, ":have_center", 1), 
		   # (try_end), 
        # (try_end), 		

		# (try_begin),
		# (eq, ":have_center", 1), 
        #######(assign, ":distance_from_our_closest_walled_center", 1000),
          # (try_for_range, ":cur_center", walled_centers_begin, walled_centers_end),
           # (store_faction_of_party, ":cur_center_faction", ":cur_center"),
           # (eq, ":cur_center_faction", ":faction_no"),
           # (store_distance_to_party_from_party, ":distance_from_cur_center", ":cur_center", ":potential_target"),
           # (lt, ":distance_from_cur_center", ":distance_from_our_closest_walled_center"),
           # (assign, ":distance_from_our_closest_walled_center", ":distance_from_cur_center"),
          # (try_end),	
		
		# (else_try), 
		   # (assign, ":distance_from_cur_center", 10),		   
           # (lt, ":distance_from_cur_center", ":distance_from_our_closest_walled_center"),
           # (assign, ":distance_from_our_closest_walled_center", ":distance_from_cur_center"),
		# (try_end), 
                                             
		
        # (gt, ":distance_from_our_closest_walled_center", 75),
        # (assign, ":result", -1),
        # (assign, ":explainer_string", "str_center_far_away_our_cautious_marshal_does_not_wish_to_reconnoiter"),				
  	  
		
      #RECONNOITERING BEGINS HERE - VALUE WILL BE TEN OR LESS
      # (else_try),
        # (gt, ":distance_from_our_closest_walled_center", 90),
        
        # (assign, ":result", -1),
        # (assign, ":explainer_string", "str_center_far_away_even_for_our_aggressive_marshal_to_reconnoiter"),
        ####(assign, ":reason_is_obvious", 1),	
      # (else_try),
        # (is_between, ":potential_target", walled_centers_begin, walled_centers_end),
        ###(neg|troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_martial),
        ###(neg|troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_quarrelsome),
        ###(neg|troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_selfrighteous),
        #NE
		# (assign, ":have_center", 0), 
        # (try_for_range, ":cur_center", walled_centers_begin, walled_centers_end),
           # (store_faction_of_party, ":cur_center_faction", ":cur_center"),
		   # (try_begin), 
           # (eq, ":cur_center_faction", "fac_dark_knights"),
		   # (assign, ":have_center", 1), 
		   # (try_end), 
        # (try_end), 	
		
		# (try_begin), 
		# (eq, ":have_center", 1), #NE
        # (assign, ":close_center_found", 0),
        # (try_for_range, ":friendly_walled_center", walled_centers_begin, walled_centers_end),
          # (eq, ":close_center_found", 0),
          # (store_faction_of_party, ":friendly_walled_center_faction", ":friendly_walled_center"),
          # (eq, ":friendly_walled_center_faction", ":faction_no"),
          # (store_distance_to_party_from_party, ":distance_from_walled_center", ":potential_target", ":friendly_walled_center"),
          # (lt, ":distance_from_walled_center", 60),
          # (assign, ":close_center_found", 1),
		  
		
		
        # (try_end),
        # (eq, ":close_center_found", 0),
        
        # (assign, ":result", -1),
        # (assign, ":explainer_string", "str_center_is_indefensible"),	
		# (else_try), 
		
		
		# (try_end), #NE
      #(else_try),
        #For now it is removed as Armagan's decision, we can add this option in later patchs. I and Armagan accept it has good potential. But this system needs also
        #scouting quests and scouting AI added together. If we only add this then we limit AI very much, it can attack only very few of centers, this damages 
        #variability of game and surprise attacks of AI. Player can predict where AI will attack and he can full garnisons of only this center. 
        #We can add asking travellers about how good defended center X by paying 100 denars for example to equalize situations of AI and human player.
        #But these needs much work and detailed AI tests so Armagan decided to skip this for now.
        
        #(store_sub, ":faction_recce_slot", ":faction_no", kingdoms_begin),
        #(val_add, ":faction_recce_slot", slot_center_last_reconnoitered_by_faction_time),
        #(party_get_slot, ":last_recce_time", ":potential_target", ":faction_recce_slot"),
        #(store_current_hours, ":hours_since_last_recce"),
        #(val_sub, ":hours_since_last_recce", ":last_recce_time"),
        
        #(this_or_next|eq, ":last_recce_time", 0),
        #(gt, ":hours_since_last_recce", 96), #Information is presumed to be accurate for four days
        
        #(store_sub, ":150_minus_distance_div_by_10", 150, ":distance_from_party"),
        #(val_div, ":150_minus_distance_div_by_10", 10),
        
        #(assign, ":result", ":150_minus_distance_div_by_10"),
        #(assign, ":explainer_string", "str_center_has_not_been_scouted"),
      #DECISIONS BASED ON ENEMY STRENGTH BEGIN HERE
	  #NE
      # (else_try),
        # (party_get_slot, ":party_strength", ":party_no", slot_party_cached_strength),
        # (party_get_slot, ":follower_strength", ":party_no", slot_party_follower_strength),
        # (party_get_slot, ":strength_of_nearby_friend", ":party_no", slot_party_nearby_friend_strength),                
        
        # (store_add, ":total_strength", ":party_strength", ":follower_strength"),
        # (val_add, ":total_strength", ":strength_of_nearby_friend"),
        
       ## (party_get_slot, ":potential_target_nearby_enemy_exact_strength", ":potential_target", slot_party_nearby_friend_strength),
        #(assign, ":potential_target_nearby_enemy_strength", ":potential_target_nearby_enemy_exact_strength"),                
        # (try_begin),
          # (is_between, ":potential_target", villages_begin, villages_end),
          # (assign, ":enemy_strength", 10),
        # (else_try),
          # (party_get_slot, ":enemy_strength", ":potential_target", slot_party_cached_strength),
          # (party_get_slot, ":enemy_strength_nearby", ":potential_target", slot_party_nearby_friend_strength),
          # (val_add, ":enemy_strength", ":enemy_strength_nearby"),
        # (try_end),
        # (val_max, ":enemy_strength", 1),                

        # (this_or_next|troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_martial),
        # (this_or_next|troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_quarrelsome),
        # (troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_selfrighteous),
        
        # (store_mul, ":power_ratio", ":total_strength", 100),
        # (val_div, ":power_ratio", ":enemy_strength"),
        # (lt, ":power_ratio", 150), 
        
        # (assign, ":result", -1),
        # (assign, ":explainer_string", "str_center_protected_by_enemy_army_aggressive"),
      # (else_try),
        # (ge, ":enemy_strength", ":total_strength"), #if enemy is powerful
        
        # (assign, ":result", -1),
        # (assign, ":explainer_string", "str_center_protected_by_enemy_army_cautious"),
      # (else_try),               
        # (store_mul, ":power_ratio", ":total_strength", 100),
        # (val_div, ":power_ratio", ":enemy_strength"),
        # (lt, ":power_ratio", 185), 
        
        # (this_or_next|troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_upstanding),
        # (this_or_next|troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_debauched),
        # (this_or_next|troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_goodnatured),
        # (troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_cunning),
        
       ## equations here
        # (assign, ":result", -1),
        # (assign, ":explainer_string", "str_center_cautious_marshal_believes_center_too_difficult_to_capture"),
      # (else_try),
        # (lt, ":power_ratio", 140), #it was 140
        
        # (assign, ":result", -1),
        # (assign, ":explainer_string", "str_center_even_aggressive_marshal_believes_center_too_difficult_to_capture"),
      ##To Steve - I moved below two if statement here from upper places, to enable in answering different different answers even 
      ##if we are close to an unlooted enemy village. For example now it can say "center X" is too far too while our army is 
      ##looting a village because of its closeness.
      (else_try),
        #if the party has already started the siege
        (faction_slot_eq, ":faction_no", slot_faction_ai_state, sfai_raiding_village),
        (faction_get_slot, ":current_object", ":faction_no", slot_faction_ai_object),
        (is_between, ":current_object", villages_begin, villages_end),
        (neq, ":potential_target", ":current_object"),
        (party_slot_eq, ":current_object", slot_village_state, svs_under_siege),
        
        (store_current_hours, ":hours_since_siege_began"),
        (party_get_slot, ":hour_that_siege_began", ":current_object", slot_center_siege_begin_hours),
        (val_sub, ":hours_since_siege_began", ":hour_that_siege_began"),
        (gt, ":hours_since_siege_began", 4),
        
        (call_script, "script_npc_decision_checklist_evaluate_enemy_center_for_attack_dk2", ":troop_no", ":current_object", ":attack_by_faction", 0),
        (gt, reg0, -1),
        
        (assign, ":result", -1),
        (assign, ":explainer_string", "str_center_we_have_already_committed_too_much_time_to_our_present_siege_to_move_elsewhere"),
		###NE
      #(else_try),
        #If the party is close to an unlooted village
        # (faction_slot_eq, ":faction_no", slot_faction_ai_state, sfai_raiding_village),
        # (faction_get_slot, ":current_object", ":faction_no", slot_faction_ai_object),       
        # (neq, ":potential_target", ":current_object"),
        # (is_between, ":current_object", villages_begin, villages_end),
        # (store_distance_to_party_from_party, ":distance_to_cur_object", ":party_no", ":current_object"),
        # (lt, ":distance_to_cur_object", 10),
        
        # (call_script, "script_npc_decision_checklist_evaluate_enemy_center_for_attack", ":troop_no", ":current_object", ":attack_by_faction", 0),
        # (gt, reg0, -1),
        
        # (assign, "$g_use_current_ai_object_as_s8", 1),
                
        # (assign, ":result", -1),
        # (assign, ":explainer_string", "str_center_we_are_already_here_we_should_at_least_loot_the_village"),
      #DECISION TO ATTACK IS HERE
      #(else_try),
        #To Steve - I removed below lines, as here decided. We will use pre-function to evaluate assailability scores for centers rather than below lines to make AI 
        #selecting better targets. If you want to make some marshals to select not-best options I can add that option into script_calculate_center_assailability_score, 
        #for that we can need seed values for each center and for each lord, so we can add these seed values to create variability, clever marshals have seeds with less 
        #standard deviation and less values and less-clever marshals have bigger seeds. Then probability of some lords to disagree marshal increases because their seed 
        #values will be different from marshal's. If Steve wants it from me to implement I can add this.
      
        #(try_begin),
        #  (is_between, ":potential_target", villages_begin, villages_end),
        #  (party_get_slot, ":score", ":potential_target", slot_town_prosperity),
        #  (val_add, ":score", 50), #average 100
        #(else_try),
        #  (is_between, ":potential_target", castles_begin, castles_end),
        #  (assign, ":score", ":power_ratio"), #ie, at least 140
        #(else_try),	
        #  (party_get_slot, ":score", ":potential_target", slot_town_prosperity),
        #  (val_add, ":score", 75),
        #  (val_mul, ":score", ":power_ratio"),
        #  (val_div, ":score", 100), #ie, at least about 200
        #(try_end),
        # 
        #(val_sub, ":score", ":distance_from_party"),
        #(lt, ":score", -1),
      
        #(assign, ":result", -1),
        #(assign, ":explainer_string", "str_center_value_outweighed_by_difficulty_of_capture"),
     (else_try),
        (try_begin),
          (eq, "$cheat_mode", 1),
          (eq, ":faction_no", "fac_kingdom_3"),
          (store_faction_of_party, ":potential_target_faction", ":potential_target"),
          (store_relation, ":relation", ":potential_target_faction", ":faction_no"),
          (lt, ":relation", 0),
        (try_end),  
         # (display_message, "@ Calculating assailability"),
        (call_script, "script_calculate_center_assailability_score_dk2", ":troop_no", ":potential_target", ":all_vassals_included"),
        (assign, ":score", reg0),
        (assign, ":power_ratio", reg1),
        #(assign, ":distance_score", reg2),
      
        (assign, ":result", ":score"),
		
		#####NE
		# (str_store_party_name, s11, ":potential_target"),
		####HERE HERE 
	    # (display_message, "@ Target: {s11}, Score: {reg0}, power ratio {reg1}"),
		# (val_add, ":power_ratio", 200),
      
        (try_begin),
          (le, ":power_ratio", 100),
          (try_begin),
            (this_or_next|troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_upstanding),
            (this_or_next|troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_debauched),
            (this_or_next|troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_goodnatured),
            (troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_cunning),	      	      
            (assign, ":explainer_string", "str_center_cautious_marshal_believes_center_too_difficult_to_capture"),
          (else_try),
            (assign, ":explainer_string", "str_center_even_aggressive_marshal_believes_center_too_difficult_to_capture"),
          (try_end),
        (else_try),
          (le, ":power_ratio", 150),
        
          (try_begin),
	        (this_or_next|troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_upstanding),
	        (this_or_next|troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_debauched),
	        (this_or_next|troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_goodnatured),
	        (troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_cunning),	      	      
	        (assign, ":explainer_string", "str_center_protected_by_enemy_army_cautious"),
	      (else_try),
	        (assign, ":explainer_string", "str_center_protected_by_enemy_army_aggressive"),
	      (try_end),
	    (else_try),
	      (try_begin),
	        (le, ":score", "$g_faction_object_score"),
	        (assign, ":explainer_string", "str_center_value_outweighed_by_difficulty_of_capture"),
	      (else_try),
	        #To Steve, does not this sentence needs to explain why we are not attacking that city? 
	        #This sentence says it justifies, so why we are not attacking?
	        (assign, ":explainer_string", "str_center_value_justifies_the_difficulty_of_capture"),
	      (try_end),
	    (try_end),
	  (try_end),
	  	  
		  
		 ##### # NE 
     # (str_store_string, s7, ":explainer_string"),
	 # (str_store_party_name, s8, ":potential_target"),
      
     # (display_message, "@DEBUG : attack of {s8} is {s7}"),
	
	  (assign, reg0, ":result"),
	  (assign, reg1, ":explainer_string"),
	  (assign, reg2, ":power_ratio"),	  	

     ]),
              
			  
			  ################################
    #script_calculate_center_assailability_score
    # INPUT: faction_no
    # param1: faction_no 
    # param2: all_vassals_included, (becomes 1 if we want to find attackable center if we collected 20% of vassals during gathering army phase)
    # OUTPUT: 
    # reg0 = center_to_attack (-1 if none is logical)
    # reg1 = maximum_attack_score
    (
    "calculate_center_assailability_score_dk2", 
    [		
      (store_script_param, ":troop_no", 1),
      (store_script_param, ":potential_target", 2),
      (store_script_param, ":all_vassals_included", 3),
      
      (assign, ":target_score", -1),
      
      (store_faction_of_troop, ":faction_no", ":troop_no"),
  
      (store_current_hours, ":hours_since_last_offensive"),
      (faction_get_slot, ":last_offensive_time", ":faction_no", slot_faction_last_offensive_concluded),
      (val_sub, ":hours_since_last_offensive", ":last_offensive_time"),
      
      (store_div, ":last_offensive_time_score", ":hours_since_last_offensive", 12), #30..50
      (val_add, ":last_offensive_time_score", 30),
      (val_min, ":last_offensive_time_score", 100),

      (faction_get_slot, ":faction_marshal", ":faction_no", slot_faction_marshall),
    
      (assign, ":marshal_party", -1),
      (assign, ":marshal_strength", 0),
      #(assign, ":strength_of_nearby_friend", 0),
      
      (try_begin),
        (gt, ":faction_marshal", 0),
        (troop_get_slot, ":marshal_party", ":faction_marshal", slot_troop_leaded_party),
        (party_is_active, ":marshal_party"),
        (party_get_slot, ":marshal_strength", ":marshal_party", slot_party_cached_strength),
        #(eq, ":all_vassals_included", 0),
        (party_get_slot, ":strength_of_current_followers", ":marshal_party", slot_party_follower_strength),
        #(party_get_slot, ":strength_of_nearby_friend", ":marshal_party", slot_party_nearby_friend_strength),
      (try_end),
  
      #(try_begin),
      #  (eq, ":all_vassals_included", 0),
      #    
      #  (try_begin),
      #    (gt, ":faction_marshal", 0),
      #    (troop_get_slot, ":marshal_party", ":faction_marshal", slot_troop_leaded_party),
      #    (party_is_active, ":marshal_party"),
      #    (party_get_slot, ":strength_of_potential_followers", ":marshal_party", slot_party_follower_strength),
      #  (try_end),                
      #(else_try),
      #  (eq, ":all_vassals_included", 1),
      #      
      #  (assign, ":strength_of_potential_followers", 0),
      #          
      #  (try_for_parties, ":party_no"),
      #    (store_faction_of_party, ":party_faction", ":party_no"),
      #    (eq, ":party_faction", ":faction_no"),
      #    (neq, ":party_no", ":marshal_party"),          
      #    (party_slot_eq, ":party_no", slot_party_type, spt_kingdom_hero_party),
      #    (call_script, "script_party_calculate_strength", ":party_no", 0),
      #    (val_add, ":strength_of_potential_followers", reg0),
      #  (try_end),    
      #  
      #  (val_div, ":strength_of_potential_followers", 2), #Ozan - Think about this, will you divide strength_of_potential_followers to 3 or 2.5 or 2
      #(else_try),
      #  (assign, ":strength_of_potential_followers", 0),      
      #(try_end),
      
      (faction_get_slot, ":last_attacked_center", ":faction_no", slot_faction_last_attacked_center),
      (faction_get_slot, ":last_attacked_hours", ":faction_no", slot_faction_last_attacked_hours),
            
      (try_begin),
        (store_current_hours, ":hours"),
        (store_add, ":last_attacked_hours_plus_24", ":last_attacked_hours", 24),
        (gt, ":hours", ":last_attacked_hours_plus_24"),
        (faction_set_slot, ":faction_no", slot_faction_last_attacked_center, 0),
        (assign, ":last_attacked_center", 0),
      (try_end),
                
      (try_begin),        
        (this_or_next|eq, ":last_attacked_center", 0),
        (this_or_next|eq, ":last_attacked_center", ":potential_target"),
        (this_or_next|eq, "$g_do_not_skip_other_than_current_ai_object", 1),
        (neg|faction_slot_eq, ":faction_no", slot_faction_marshall, ":troop_no"),
        
        (party_is_active, ":potential_target"),
        (store_faction_of_party, ":potential_target_faction", ":potential_target"),
          
        (store_relation, ":relation", ":potential_target_faction", ":faction_no"),	      
        (lt, ":relation", 0),
        
        #attack if and only if we are already besieging that center or anybody do not making besiege.
        (assign, ":faction_of_besieger_party", -1),
        (try_begin),        
          (is_between, ":potential_target", walled_centers_begin, walled_centers_end),      
          (neg|party_slot_eq, ":potential_target", slot_center_is_besieged_by, -1), 
          (party_get_slot, ":besieger_party", ":potential_target", slot_center_is_besieged_by),
          (party_is_active, ":besieger_party"),
          (store_faction_of_party, ":faction_of_besieger_party", ":besieger_party"),
        (try_end),	
        			     
        (this_or_next|eq, ":faction_of_besieger_party", -1), 
        (eq, ":faction_of_besieger_party", ":faction_no"),
        
        #attack if and only if this center is not a village or if it is village it should not be raided or looted
        (assign, ":village_is_looted_or_raided_already", 0),
        (try_begin),
          (is_between, ":potential_target", villages_begin, villages_end),
          (try_begin),
            (party_slot_eq, ":potential_target", slot_village_state, svs_being_raided),
            (party_get_slot, ":raider_party", ":potential_target", slot_village_raided_by),
			(party_is_active, ":raider_party"),
			
            (store_faction_of_party, ":raider_faction", ":raider_party"),
            (neq, ":raider_faction", ":faction_no"),
            (assign, ":raiding_by_one_other_faction", 1),
          (else_try),
            (assign, ":raiding_by_one_other_faction", 0),
          (try_end),  
          (this_or_next|party_slot_eq, ":potential_target", slot_village_state, svs_looted),
          (eq, ":raiding_by_one_other_faction", 1),
          (assign, ":village_is_looted_or_raided_already", 1),
        (try_end),        
        (eq, ":village_is_looted_or_raided_already", 0),

        #if ":potential_target" is faction object of some other faction which is enemy to owner of 
        #":potential_target" then this target cannot be new target we are looking for.
        (assign, ":this_potantial_target_is_target_of_some_other_faction", 0),
        (try_for_range, ":cur_faction", kingdoms_begin, kingdoms_end),
          (is_between, ":cur_faction", "fac_kingdom_1", kingdoms_end), #Excluding player kingdom
          (neq, ":cur_faction", ":faction_no"),
          (faction_get_slot, ":faction_object", ":cur_faction", slot_faction_ai_object),
          (eq, ":faction_object", ":potential_target"),
          (store_relation, ":rel", ":potential_target_faction", ":cur_faction"),
          (lt, ":rel", 0),
          (assign, ":this_potantial_target_is_target_of_some_other_faction", 1),          
        (try_end),      
        (eq, ":this_potantial_target_is_target_of_some_other_faction", 0),                                            
    		  				
        (try_begin),
          (is_between, ":potential_target", walled_centers_begin, walled_centers_end),      
          (party_get_slot, ":potential_target_inside_strength", ":potential_target", slot_party_cached_strength),
          (party_get_slot, ":potential_target_nearby_enemy_strength", ":potential_target", slot_party_nearby_friend_strength),    
          (val_div, ":potential_target_nearby_enemy_strength", 2),        
          (store_add, ":potential_target_strength", ":potential_target_inside_strength", ":potential_target_nearby_enemy_strength"),

          #(try_begin),
            #(eq, ":faction_no", "fac_kingdom_4"),
            #(assign, reg0, ":potential_target_inside_strength"),
            #(assign, reg1, ":potential_target_nearby_enemy_strength"),
            #(assign, reg2, ":marshal_strength"),
            #(assign, reg3, ":strength_of_potential_followers"),
            #(assign, reg4, ":strength_of_nearby_friend"),
            #(assign, reg6, ":marshal_party"),
            #(str_store_party_name, s8, ":potential_target"),
            #(eq, ":all_vassals_included", 0),
            #(display_message, "@DEBUG : {s8}:{reg0}, neare {reg1}, our {reg2}, follow {reg3}, nearf {reg4}"),
          #(try_end),
                    
          (val_mul, ":potential_target_strength", 4), #in walled centers defenders have advantage.
          (val_div, ":potential_target_strength", 3),
                              
          #(store_add, ":army_strength", ":marshal_strength", ":strength_of_potential_followers"),
          (assign, ":army_strength", ":marshal_strength"),
          (val_add, ":army_strength", ":strength_of_current_followers"),
          (store_mul, ":power_ratio", ":army_strength", 100),
          
          #this ratio ":power_ratio" shows (our total army power) / (their total army power)
          (try_begin),
            (gt, ":potential_target_strength", 0),
            (val_div, ":power_ratio", ":potential_target_strength"),
          (else_try),
            (assign, ":power_ratio", 1000),
          (try_end),  
        (else_try),        
          (party_get_slot, ":potential_target_nearby_enemy_strength", ":potential_target", slot_party_nearby_friend_strength),                      
          (assign, ":potential_target_strength", 1000),
                    
          #(store_add, ":army_strength", ":marshal_strength", ":strength_of_potential_followers"),
          (assign, ":army_strength", ":marshal_strength"),
          (val_add, ":army_strength", ":strength_of_current_followers"),
          (store_mul, ":power_ratio", ":army_strength", 100),
                                                            
          (try_begin),
            (gt, ":potential_target_strength", 0),
            (val_div, ":power_ratio", ":potential_target_strength"),
          (else_try),
            (assign, ":power_ratio", 1000),
          (try_end),            
        (try_end),
                            
        (ge, ":power_ratio", 60), #attack if and only if our army is at least 1.2 times powerfull		#NE half this to 60		
        (store_sub, ":power_ratio_sub_120", ":power_ratio", 60),
        
        (try_begin),
          (lt, ":power_ratio_sub_120", 100), #changes between 20..120
          (store_add, ":power_ratio_score", ":power_ratio_sub_120", 20),
        (else_try),
          (lt, ":power_ratio_sub_120", 200), #changes between 120..170
          (store_sub, ":power_ratio_score", ":power_ratio_sub_120", 100),
          (val_div, ":power_ratio_score", 2),
          (val_add, ":power_ratio_score", 120),
        (else_try),
          (lt, ":power_ratio_sub_120", 400), #changes between 170..210
          (store_sub, ":power_ratio_score", ":power_ratio_sub_120", 200),
          (val_div, ":power_ratio_score", 5),
          (val_add, ":power_ratio_score", 170),
        (else_try),
          (lt, ":power_ratio_sub_120", 800), #changes between 210..250
          (store_sub, ":power_ratio_score", ":power_ratio_sub_120", 400),
          (val_div, ":power_ratio_score", 10),
          (val_add, ":power_ratio_score", 210),
        (else_try),
          (assign, ":power_ratio_score", 250),
        (try_end),
          
        (assign, ":number_of_walled_centers", 0),
        (assign, ":total_distance", 0),
        (try_for_range, ":walled_center", walled_centers_begin, walled_centers_end),
          (store_faction_of_party, ":walled_center_faction", ":walled_center"),
          (eq, ":walled_center_faction", ":faction_no"),
                
          (store_distance_to_party_from_party, ":dist", ":walled_center", ":potential_target"),            
          (val_add, ":total_distance", ":dist"),
                
          (val_add, ":number_of_walled_centers", 1),
        (try_end),
                
        (try_begin),
          (gt, ":number_of_walled_centers", 0),
          (store_div, ":average_distance", ":total_distance", ":number_of_walled_centers"),
          #(assign, reg0, ":average_distance"),                    
          #(str_store_faction_name, s7, ":faction_no"),
          #(str_store_party_name, s8, ":potential_target"),
          #(display_message, "@average distance for {s7} for {s8} is {reg0}"),
          
          (try_begin),
            (ge, ":marshal_party", 0),
            (party_is_active, ":marshal_party"),
            (store_distance_to_party_from_party, ":marshal_dist_to_potential_target", ":marshal_party", ":potential_target"),
          (else_try),
            (assign, ":marshal_dist_to_potential_target", 100),
          (try_end),
                      
          (try_begin),  
            #if currently our target is attacking to an enemy center and that center is besieged/raided by one of our parties then 
            #divide marshal_distance for other center's to "2" instead of "3" and add some small more distance to avoid easily 
            #changing mind during siege because of small score differences.
              
            (faction_get_slot, ":current_ai_state", ":faction_no", slot_faction_ai_state),
            (eq, ":current_ai_state", sfai_attacking_center),
            (faction_get_slot, ":current_ai_object", ":faction_no", slot_faction_ai_object),
            
            (ge, ":current_ai_object", 0),
            (neq, ":current_ai_object", ":potential_target"),
              
            (try_begin),
              (ge, ":power_ratio_score", 300), #200 max
              (assign, ":power_ratio_score", 200),
            (else_try),
              (ge, ":power_ratio_score", 100), #100..200
              (val_sub, ":power_ratio_score", 100),
              (val_div, ":power_ratio_score", 2),
              (val_add, ":power_ratio_score", 100),
            (try_end),  
            
            (try_begin),
              (faction_slot_eq, ":faction_no", slot_faction_marshall, ":troop_no"),
              (eq, "$g_do_not_skip_other_than_current_ai_object", 0),
              (assign, ":power_ratio_score", 0), #lets completely forget all other choices if we are already besieging one center.
            (try_end),  
            
            (faction_set_slot, ":faction_no", slot_faction_last_attacked_center, ":current_ai_object"),
            (store_current_hours, ":hours"),
            (faction_set_slot, ":faction_no", slot_faction_last_attacked_hours, ":hours"),

            (eq, ":all_vassals_included", 0),

            (store_div, ":marshal_dist_to_potential_target_div_x", ":marshal_dist_to_potential_target", 2),
            (assign, ":marshal_dist_to_potential_target_div_x", ":marshal_dist_to_potential_target"),
          (else_try),
            (store_div, ":marshal_dist_to_potential_target_div_x", ":marshal_dist_to_potential_target", 3),
          (try_end),
            
          (store_add, ":total_distance", ":average_distance", ":marshal_dist_to_potential_target_div_x"), #in average ":total_distance" is about 150, min : 0, max : 1000
        (else_try),
          (assign, ":total_distance", 100),
        (try_end),                

        (try_begin),
          #according to cautious troop distance is more important

	      (this_or_next|troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_upstanding),
	      (this_or_next|troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_debauched),
	      (this_or_next|troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_goodnatured),
	      (troop_slot_eq, ":troop_no", slot_lord_reputation_type, lrep_cunning),	      	      

          (try_begin),
            (lt, ":total_distance", 30), #very close (100p)
            (assign, ":distance_score", 100),
          (else_try),
            (lt, ":total_distance", 80), #close (50p-100p)
            (store_sub, ":distance_score", ":total_distance", 30),
            (val_div, ":distance_score", 1),
            (store_sub, ":distance_score", 100, ":distance_score"),
          (else_try),  
            (lt, ":total_distance", 160), #far (10p-50p)
            (store_sub, ":distance_score", ":total_distance", 80),
            (val_div, ":distance_score", 2),
            (store_sub, ":distance_score", 50, ":distance_score"),
          (else_try),
            (assign, ":distance_score", 10), #very far
          (try_end),
        (else_try),  
          #according to agressive troop distance is less important
          
          (try_begin),
            (lt, ":total_distance", 40), #very close (100p)
            (assign, ":distance_score", 100),
          (else_try),
            (lt, ":total_distance", 140), #close (50p-100p)
            (store_sub, ":distance_score", ":total_distance", 40),
            (val_div, ":distance_score", 2),
            (store_sub, ":distance_score", 100, ":distance_score"),
          (else_try),  
            (lt, ":total_distance", 300), #far (10p-50p)
            (store_sub, ":distance_score", ":total_distance", 140),
            (val_div, ":distance_score", 4),
            (store_sub, ":distance_score", 50, ":distance_score"),
          (else_try),
            (assign, ":distance_score", 10), #very far
          (try_end),
        (try_end),
                                                                                           
        (store_mul, ":target_score", ":distance_score", ":power_ratio_score"),
        (val_mul, ":target_score", ":last_offensive_time_score"),
        (val_div, ":target_score", 100), #target score is between 0..10000 generally here

        (call_script, "script_find_total_prosperity_score", ":potential_target"),                
        (assign, ":total_prosperity_score", reg0),
            
        #(try_begin), #new for increase attackability of villages by ai
          #(is_between, ":potential_target", villages_begin, villages_end), 
          (val_mul, ":total_prosperity_score", 3),
          (val_div, ":total_prosperity_score", 2),
        #(try_end),

        (val_mul, ":target_score", ":total_prosperity_score"),
          
        (try_begin), #if both that center was our (original center) and (ex center) than bonus is 1.2x
          (party_slot_eq, ":potential_target", slot_center_ex_faction, ":faction_no"),
          (party_slot_eq, ":potential_target", slot_center_original_faction, ":faction_no"),
          (val_mul, ":target_score", 12),
          (val_div, ":target_score", 10),
        (else_try), #if either that center was our (original center) or (ex center) than bonus is 1.1x
          (this_or_next|party_slot_eq, ":potential_target", slot_center_ex_faction, ":faction_no"),
          (party_slot_eq, ":potential_target", slot_center_original_faction, ":faction_no"),
          (val_mul, ":target_score", 11),
          (val_div, ":target_score", 10),
        (try_end),
            
        (val_div, ":target_score", 1000), #target score is between 0..1000 generally here
        
        (try_begin),
          (eq, ":potential_target_faction", "fac_player_supporters_faction"),
          (game_get_reduce_campaign_ai, ":reduce_campaign_ai"),
          
          (assign, ":number_of_walled_centers_player_have", 0),
          (try_for_range, ":center_no", walled_centers_begin, walled_centers_end),
            (store_faction_of_party, ":center_faction", ":center_no"),
            (eq, ":center_faction", "fac_player_supporters_faction"),
            (val_add, ":number_of_walled_centers_player_have", 1),
          (try_end),
          
          (try_begin),
            (eq, ":reduce_campaign_ai", 2), #easy
            
            (try_begin),
              (le, ":number_of_walled_centers_player_have", 2),
              (assign, ":hardness_score", 0),              
            (else_try),
              (eq, ":number_of_walled_centers_player_have", 3),
              (assign, ":hardness_score", 20),
            (else_try),
              (eq, ":number_of_walled_centers_player_have", 4),
              (assign, ":hardness_score", 40),
            (else_try),
              (eq, ":number_of_walled_centers_player_have", 5),
              (eq, ":number_of_walled_centers_player_have", 6),
              (assign, ":hardness_score", 55),
            (else_try),
              (eq, ":number_of_walled_centers_player_have", 7),
              (eq, ":number_of_walled_centers_player_have", 8),
              (eq, ":number_of_walled_centers_player_have", 9),
              (assign, ":hardness_score", 70),
            (else_try),
              (assign, ":hardness_score", 85),
            (try_end),
          (else_try),  
            (eq, ":reduce_campaign_ai", 1), #medium

            (try_begin),
              (le, ":number_of_walled_centers_player_have", 1),
              (assign, ":hardness_score", 25),
            (else_try),
              (eq, ":number_of_walled_centers_player_have", 2),
              (assign, ":hardness_score", 45),
            (else_try),
              (eq, ":number_of_walled_centers_player_have", 3),
              (assign, ":hardness_score", 60),
            (else_try),
              (eq, ":number_of_walled_centers_player_have", 4),
              (eq, ":number_of_walled_centers_player_have", 5),
              (assign, ":hardness_score", 75),
            (else_try),
              (eq, ":number_of_walled_centers_player_have", 6),
              (eq, ":number_of_walled_centers_player_have", 7),
              (eq, ":number_of_walled_centers_player_have", 8),
              (assign, ":hardness_score", 85),
            (else_try),
              (assign, ":hardness_score", 92),
            (try_end),
          (else_try), #hard
            (assign, ":hardness_score", 100), 
          (try_end),
          
          (val_mul, ":target_score", ":hardness_score"),
          (val_div, ":target_score", 100),
        (try_end),

        (try_begin), #NE
          (ge, "$cheat_mode", 1),
          (eq, ":faction_no", "fac_kingdom_4"),
          (ge, ":target_score", -1),
          (assign, reg0, ":target_score"),
          (assign, reg7, ":total_prosperity_score"),
          (assign, reg8, ":power_ratio_score"),
          (assign, reg9, ":distance_score"),
          (assign, reg10, ":last_offensive_time_score"),
          (str_store_party_name, s8, ":potential_target"),
          (eq, ":all_vassals_included", 0),
          (assign, reg11, ":all_vassals_included"),          
          (display_message, "@DEBUG : attack of {s8} is {reg0}({reg11}), prs:{reg7}, pow:{reg8}, dis:{reg9}, lst:{reg10}"),
        (try_end),  
      (try_end),
                                                     
      (assign, reg0, ":target_score"),
      (assign, reg1, ":power_ratio"),
      (assign, reg2, ":distance_score"),
      (assign, reg3, ":total_prosperity_score"),
    ]),

####################################################################################################################################
# NE Custom Scripts Start - Starting with .608b all NE written scripts go here
####################################################################################################################################


  # script_enable_militia_on_village
  # Input: arg1 = party_no
  # This script will set the global variable needed to determine if a particular village has a militia or not
  # This is called when a player successfully completes a train militia quest, or hopefully later, also
  # when a player gives militia to a village.
  # Output: none
  
  ("ne_enable_militia_on_village",
    [
      
      (store_script_param, ":center_no", 1),
      (party_set_slot, ":center_no", slot_militia_quest_completed, 1),
      
  ]),
  
  ("ne_disable_militia_on_village",
    [
      
      (store_script_param, ":center_no", 1),
      (party_set_slot, ":center_no", slot_militia_quest_completed, 0),
      
  ]),

  # Debug script to see militia status
     ("ne_see_militia_status",
    [

      (store_script_param, ":center_no", 1),
      (party_get_slot, ":militia_completed", ":center_no", slot_militia_quest_completed),
      (try_begin),
        (gt, ":militia_completed", 0),
        (display_message, "@This village has a militia."),
      (else_try),
        (display_message, "@This village does not have a militia."),
      (try_end),

  ]),

####################################################################################################################################
# NE Custom Scripts End
####################################################################################################################################
	
####################################################################################################################################
# LAV MODIFICATIONS START (COMPANIONS OVERSEER MOD)
####################################################################################################################################

    ("lco_item_name_to_s41",
        [
            (assign, ":ex_reg60", reg60),
            (assign, ":ex_reg61", reg61),
            (store_script_param, ":item_id", 1),
            (store_script_param, ":modifier", 2),
            (store_script_param, reg60, 3),
            (store_script_param, reg61, 4),
            (str_store_item_name, s41, ":item_id"),
            (try_begin),
                (gt, ":modifier", 0),
                (store_add, ":str_offset", "str_item_imod_name_0", ":modifier"),
                (str_store_string, s42, ":str_offset"),
                (str_store_string, s41, "str_lco_s42_s41"),
            (try_end),
            (try_begin),
                (gt, reg61, 1),
                (try_begin),
                    (item_get_type, ":item_type", ":item_id"),
                    (eq, ":item_type", itp_type_goods),
                    (str_store_string, s41, "str_lco_s41_reg60_reg61"),
                (else_try),
                    (str_store_string, s41, "str_lco_s41_reg60"),
                (try_end),
            (try_end),
            (assign, reg60, ":ex_reg60"),
            (assign, reg61, ":ex_reg61"),
        ]
    ),

    ("lco_fill_hero_panels",
        [
            (try_begin),
                (eq, "$g_lco_heroes", 0),
                (call_script, "script_lco_clear_all_items", lco_storage),
                (assign, ":troop_id", lco_storage),
            (else_try),
                (store_add, ":offset", "$g_lco_heroes", "$g_lco_active_hero"), # Slot ID where hero reference is stored
                (troop_get_slot, ":troop_id", lco_storage, ":offset"), # We got hero troop ID, now checking equipment
            (try_end),
            (store_mul, ":offset", "$g_lco_heroes", 2),
            (val_add, ":offset", 11), # Offset now points to first text overlay of hero equipment
            (str_clear, s40),
            (try_for_range, ":index", 0, 9),
                (store_add, ":overlay_offset", ":offset", ":index"),
                (troop_get_slot, ":overlay_id", lco_storage, ":overlay_offset"),
                (troop_get_inventory_slot, ":item_id", ":troop_id", ":index"),
                (try_begin),
                    (lt, ":item_id", 0),
                    (store_add, ":string_id", "str_lco_slot_name_0", ":index"),
                    (overlay_set_text, ":overlay_id", ":string_id"),
                    (overlay_set_color, ":overlay_id", 0x808080),
                (else_try),
                    (troop_get_inventory_slot_modifier, ":modifier", ":troop_id", ":index"),
                    (troop_inventory_slot_get_item_amount, ":qty", ":troop_id", ":index"),
                    (troop_inventory_slot_get_item_max_amount, ":qty_max", ":troop_id", ":index"),
                    (call_script, "script_lco_item_name_to_s41", ":item_id", ":modifier", ":qty", ":qty_max"),
                    (overlay_set_text, ":overlay_id", s41),
                    (overlay_set_color, ":overlay_id", 0x000000),
                (try_end),
            (try_end),
            # Update V1.1. Disable book slots configuration variable
            (try_begin),
                (eq, "$g_lco_suppress_books", 0),
                # Searching for books...
                (val_add, ":overlay_offset", 1),
                (assign, ":books_found", 0),
                (troop_get_inventory_capacity, ":capacity", ":troop_id"),
                (try_for_range, ":index", num_equipment_kinds, ":capacity"),
                    (troop_get_inventory_slot, ":item_id", ":troop_id", ":index"),
                    (ge, ":item_id", 0),
                    (item_get_type, ":item_type", ":item_id"),
                    (eq, ":item_type", itp_type_book),
                    (troop_get_inventory_slot_modifier, ":modifier", ":troop_id", ":index"),
                    (troop_inventory_slot_get_item_amount, ":qty", ":troop_id", ":index"),
                    (troop_inventory_slot_get_item_max_amount, ":qty_max", ":troop_id", ":index"),
                    (call_script, "script_lco_item_name_to_s41", ":item_id", ":modifier", ":qty", ":qty_max"),
                    (troop_get_slot, ":overlay_id", lco_storage, ":overlay_offset"),
                    (overlay_set_text, ":overlay_id", s41),
                    (overlay_set_color, ":overlay_id", 0x000000),
                    (val_add, ":overlay_offset", 1),
                    (val_add, ":books_found", 1),
                    (try_begin),
                        (gt, ":books_found", 1), # Found two books, so stopping
                        (assign, ":capacity", 0),
                    (try_end),
                (try_end),
                (try_for_range, ":index", ":books_found", 2),
                    (troop_get_slot, ":overlay_id", lco_storage, ":overlay_offset"),
                    (overlay_set_text, ":overlay_id", "str_lco_slot_name_9"),
                    (overlay_set_color, ":overlay_id", 0x808080),
                    (val_add, ":overlay_offset", 1),
                (try_end),
            (try_end),
        ]
    ),

    ("lco_fill_player_panels",
        [
            (store_mul, ":offset", "$g_lco_heroes", 2),
            (val_add, ":offset", 31), # Offset now points to first text overlay of player equipment
            (str_clear, s40),
            (try_for_range, ":index", 0, 9),
                (store_add, ":overlay_offset", ":offset", ":index"),
                (troop_get_slot, ":overlay_id", lco_storage, ":overlay_offset"),
                (troop_get_inventory_slot, ":item_id", "trp_player", ":index"),
                (try_begin),
                    (lt, ":item_id", 0),
                    (store_add, ":string_id", "str_lco_slot_name_0", ":index"),
                    (overlay_set_text, ":overlay_id", ":string_id"),
                    (overlay_set_color, ":overlay_id", 0x808080),
                (else_try),
                    (troop_get_inventory_slot_modifier, ":modifier", "trp_player", ":index"),
                    (troop_inventory_slot_get_item_amount, ":qty", "trp_player", ":index"),
                    (troop_inventory_slot_get_item_max_amount, ":qty_max", "trp_player", ":index"),
                    (call_script, "script_lco_item_name_to_s41", ":item_id", ":modifier", ":qty", ":qty_max"),
                    (overlay_set_text, ":overlay_id", s41),
                    (overlay_set_color, ":overlay_id", 0x000000),
                (try_end),
            (try_end),
            # Displaying inventory
            (store_mul, ":offset", "$g_lco_heroes", 2),
            (val_add, ":offset", 40),
            (val_add, ":offset", "$g_lco_inv_slots"),
            (try_for_range, ":index", 0, "$g_lco_inv_slots"),
                (store_add, ":inventory_offset", ":index", num_equipment_kinds), # Actual inventory slot for player
                (store_add, ":overlay_offset", ":offset", ":index"),
                (troop_get_slot, ":overlay_id", lco_storage, ":overlay_offset"), # Text overlay for slot
                # Update V1.1. Checking slot frozen status and updating text color as necessary
                (try_begin),
                    (call_script, "script_cf_lco_slot_is_frozen", ":inventory_offset"),
                    (overlay_set_color, ":overlay_id", 0x000000FF),
                (else_try),
                    (overlay_set_color, ":overlay_id", 0x00000000),
                (try_end),
                (troop_get_inventory_slot, ":item_id", "trp_player", ":inventory_offset"),
                (try_begin),
                    (lt, ":item_id", 0),
                    (try_begin),
                        (call_script, "script_cf_lco_slot_is_frozen", ":inventory_offset"),
                        (overlay_set_color, ":overlay_id", 0x006060FF),
                        (overlay_set_text, ":overlay_id", "str_lco_slot_frozen"),
                    (else_try),
                        (overlay_set_text, ":overlay_id", s40),
                    (try_end),
                (else_try),
                    (troop_get_inventory_slot_modifier, ":modifier", "trp_player", ":inventory_offset"),
                    (troop_inventory_slot_get_item_amount, ":qty", "trp_player", ":inventory_offset"),
                    (troop_inventory_slot_get_item_max_amount, ":qty_max", "trp_player", ":inventory_offset"),
                    (call_script, "script_lco_item_name_to_s41", ":item_id", ":modifier", ":qty", ":qty_max"),
                    (overlay_set_text, ":overlay_id", s41),
                (try_end),
            (try_end),
            # Displaying garbage/loot
            (val_add, ":offset", "$g_lco_inv_slots"),
            (val_add, ":offset", "$g_lco_garb_slots"),
            (try_for_range, ":index", 0, "$g_lco_garb_slots"),
                (store_add, ":overlay_offset", ":offset", ":index"),
                (troop_get_slot, ":overlay_id", lco_storage, ":overlay_offset"),
                (store_add, ":inventory_offset", ":index", num_equipment_kinds),
                (troop_get_inventory_slot, ":item_id", "$g_lco_garbage_troop", ":inventory_offset"),
                (try_begin),
                    (lt, ":item_id", 0),
                    (overlay_set_text, ":overlay_id", s40),
                (else_try),
                    (troop_get_inventory_slot_modifier, ":modifier", "$g_lco_garbage_troop", ":inventory_offset"),
                    (troop_inventory_slot_get_item_amount, ":qty", "$g_lco_garbage_troop", ":inventory_offset"),
                    (troop_inventory_slot_get_item_max_amount, ":qty_max", "$g_lco_garbage_troop", ":inventory_offset"),
                    (call_script, "script_lco_item_name_to_s41", ":item_id", ":modifier", ":qty", ":qty_max"),
                    (overlay_set_text, ":overlay_id", s41),
                (try_end),
            (try_end),
        ]
    ),

    ("cf_lco_is_active_panel",
        [
            (store_script_param_1, ":overlay"),
            (assign, ":found", 0),
            (store_mul, ":range1", "$g_lco_heroes", 2),
            (store_add, ":range2", ":range1", 11),
            # Checking hero equipment panels
            (try_for_range, ":index", ":range1", ":range2"),
                (troop_slot_eq, lco_storage, ":index", ":overlay"),
                (assign, ":found", 1),
            (try_end),
            # Checking player equipment panels
            (try_begin),
                (eq, ":found", 0),
                (val_add, ":range1", 22),
                (store_add, ":range2", ":range1", 9),
                (try_for_range, ":index", ":range1", ":range2"),
                    (troop_slot_eq, lco_storage, ":index", ":overlay"),
                    (assign, ":found", 1),
                (try_end),
            (try_end),
            # Checking player inventory panels
            (try_begin),
                (eq, ":found", 0),
                (val_add, ":range1", 18),
                (store_add, ":range2", ":range1", "$g_lco_inv_slots"),
                (try_for_range, ":index", ":range1", ":range2"),
                    (troop_slot_eq, lco_storage, ":index", ":overlay"),
                    (assign, ":found", 1),
                (try_end),
            (try_end),
            # Checking garbage/loot inventory panels
            (try_begin),
                (eq, ":found", 0),
                (val_add, ":range1", "$g_lco_inv_slots"), # Skipping player inventory panels
                (val_add, ":range1", "$g_lco_inv_slots"), # Skipping player inventory text labels
                (store_add, ":range2", ":range1", "$g_lco_garb_slots"),
                (try_for_range, ":index", ":range1", ":range2"),
                    (troop_slot_eq, lco_storage, ":index", ":overlay"),
                    (assign, ":found", 1),
                (try_end),
            (try_end),
            (eq, ":found", 1),
        ]
    ),

    ("lco_get_slot_details_for_panel",
        [
            (store_script_param_1, ":overlay"),
            (assign, reg0, -1),
            (assign, reg1, -1),
            (assign, reg2, -1),
            (assign, reg3, 0),
            (assign, reg4, 0),
            (assign, reg5, 0),
            (assign, ":found", 0),
            # Looking for hero equipment slots
            (store_mul, ":range1", "$g_lco_heroes", 2),
            (store_add, ":range2", ":range1", 11),
            (try_for_range, ":index", ":range1", ":range2"),
                (troop_slot_eq, lco_storage, ":index", ":overlay"),
                (store_add, ":hero_offset", "$g_lco_heroes", "$g_lco_active_hero"),
                (troop_get_slot, ":troop_id", lco_storage, ":hero_offset"),
                (store_sub, ":n_index", ":index", ":range1"),
                (try_begin),
                    (lt, ":n_index", 9),
                    (assign, reg0, ":troop_id"),
                    (assign, reg1, ":n_index"),
                (else_try),
                    (call_script, "script_lco_allocate_slots_for_books", ":troop_id"), # reg0 and reg1 now contain slot ids for first two books in inventory, or for empty slots
                    (try_begin),
                        (eq, ":n_index", 9),
                        (assign, reg1, reg0),
                    (try_end),
                    (assign, reg0, ":troop_id"),
                (try_end),
                (assign, ":found", 1),
            (try_end),
            # Looking for player equipment slots
            (try_begin),
                (eq, ":found", 0),
                (val_add, ":range1", 22),
                (store_add, ":range2", ":range1", 9),
                (try_for_range, ":index", ":range1", ":range2"),
                    (troop_slot_eq, lco_storage, ":index", ":overlay"),
                    (assign, reg0, "trp_player"),
                    (store_sub, reg1, ":index", ":range1"),
                    (assign, ":found", 1),
                (try_end),
            (try_end),
            # Looking for player inventory slots
            (try_begin),
                (eq, ":found", 0),
                (val_add, ":range1", 18),
                (store_add, ":range2", ":range1", "$g_lco_inv_slots"),
                (try_for_range, ":index", ":range1", ":range2"),
                    (troop_slot_eq, lco_storage, ":index", ":overlay"),
                    (assign, reg0, "trp_player"),
                    (store_sub, reg1, ":index", ":range1"),
                    (val_add, reg1, num_equipment_kinds),
                    (assign, ":found", 1),
                (try_end),
            (try_end),
            # Looking for garbage/loot inventory slots
            (try_begin),
                (eq, ":found", 0),
                (val_add, ":range1", "$g_lco_inv_slots"), # Skipping player inventory panels
                (val_add, ":range1", "$g_lco_inv_slots"), # Skipping player inventory text labels
                (store_add, ":range2", ":range1", "$g_lco_garb_slots"),
                (try_for_range, ":index", ":range1", ":range2"),
                    (troop_slot_eq, lco_storage, ":index", ":overlay"),
                    (assign, reg0, "$g_lco_garbage_troop"),
                    (store_sub, reg1, ":index", ":range1"),
                    (val_add, reg1, num_equipment_kinds),
                    (assign, ":found", 1),
                (try_end),
            (try_end),
            # Finally if found, filling item details
            (try_begin),
                (eq, ":found", 1),
                (troop_get_inventory_slot, reg2, reg0, reg1),
                (try_begin),
                    (ge, reg2, 0),
                    (troop_get_inventory_slot_modifier, reg3, reg0, reg1),
                    (troop_inventory_slot_get_item_amount, reg4, reg0, reg1),
                    (troop_inventory_slot_get_item_max_amount, reg5, reg0, reg1),
                (try_end),
            (try_end),
        ]
    ),

    # INPUT: arg1 = <troop_id>, arg2 = <slot_id>
    # OUTPUT: none, script modifies some $g_lco_* variables which are tracked by ti_on_presentation_run trigger in prsnt_overview_equipment
    ("lco_drag_item",
        [
            (store_script_param_1, ":troop_id"),
            (store_script_param_2, ":slot_id"),
            (try_begin),
                (call_script, "script_cf_lco_controllable", ":troop_id"),
                (troop_get_inventory_slot, ":item_id", ":troop_id", ":slot_id"),
                (try_begin),
                    (ge, ":item_id", 0),
                    (assign, "$g_lco_drag_item", ":item_id"),
                    (troop_get_inventory_slot_modifier, "$g_lco_drag_modifier", ":troop_id", ":slot_id"),
                    (troop_inventory_slot_get_item_amount, "$g_lco_drag_quantity", ":troop_id", ":slot_id"),
                    (troop_inventory_slot_get_item_max_amount, "$g_lco_drag_quantity_max", ":troop_id", ":slot_id"),
                    (assign, "$g_lco_dragging_from", ":troop_id"),
                    (assign, "$g_lco_dragging_from_slot", ":slot_id"),
                    # Displaying overlay
                    (call_script, "script_lco_item_name_to_s41", ":item_id", "$g_lco_drag_modifier", "$g_lco_drag_quantity", "$g_lco_drag_quantity_max"),
                    (overlay_set_text, "$g_lco_dragging_text", s41),
                    (overlay_set_display, "$g_lco_dragging_panel", 1),
                    (assign, "$g_lco_dragging", 1),
                    (troop_set_inventory_slot, ":troop_id", ":slot_id", -1),
                    (try_begin),
                        (eq, ":troop_id", "$g_lco_garbage_troop"),
                        (troop_sort_inventory, "$g_lco_garbage_troop"),
                    (try_end),
                (try_end),
            (else_try),
                (display_message, "str_lco_drop_error_control", 0xFF4040),
            (try_end),
        ]
    ),

    ("lco_cancel_drag_item",
        [
            (try_begin),
                (eq, "$g_lco_dragging", 1), # Safety check
                (try_begin),
                    # Trying to deposit the item where it originally belongs
                    (troop_get_inventory_slot, ":stored_id", "$g_lco_dragging_from", "$g_lco_dragging_from_slot"),
                    (lt, ":stored_id", 0),
                    (troop_set_inventory_slot, "$g_lco_dragging_from", "$g_lco_dragging_from_slot", "$g_lco_drag_item"),
                    (troop_set_inventory_slot_modifier, "$g_lco_dragging_from", "$g_lco_dragging_from_slot", "$g_lco_drag_modifier"),
                    (try_begin),
                        (gt, "$g_lco_drag_quantity", 0),
                        (troop_inventory_slot_set_item_amount, "$g_lco_dragging_from", "$g_lco_dragging_from_slot", "$g_lco_drag_quantity"),
                    (try_end),
                    (assign, "$g_lco_dragging", 0),
                (else_try),
                    # Original slot is occupied, so trying to drop the dragged item to player's inventory
                    (troop_get_inventory_capacity, ":capacity", "trp_player"),
                    (try_for_range, ":slot_id", num_equipment_kinds, ":capacity"),
                        (troop_get_inventory_slot, ":stored_id", "trp_player", ":slot_id"),
                        (lt, ":stored_id", 0),
                        (troop_set_inventory_slot, "trp_player", ":slot_id", "$g_lco_drag_item"),
                        (troop_set_inventory_slot_modifier, "trp_player", ":slot_id", "$g_lco_drag_modifier"),
                        (try_begin),
                            (gt, "$g_lco_drag_quantity", 0),
                            (troop_inventory_slot_set_item_amount, "trp_player", ":slot_id", "$g_lco_drag_quantity"),
                        (try_end),
                        (assign, "$g_lco_dragging", 0),
                        (assign, ":capacity", 0), # Break cycle
                    (try_end),
                    (eq, "$g_lco_dragging", 0), # Check for success
                (else_try),
                    # Player inventory is full, trying to deposit item to garbage
                    (troop_get_inventory_capacity, ":capacity", "$g_lco_garbage_troop"),
                    (try_for_range, ":slot_id", num_equipment_kinds, ":capacity"),
                        (troop_get_inventory_slot, ":stored_id", "$g_lco_garbage_troop", ":slot_id"),
                        (lt, ":stored_id", 0),
                        (troop_set_inventory_slot, "$g_lco_garbage_troop", ":slot_id", "$g_lco_drag_item"),
                        (troop_set_inventory_slot_modifier, "$g_lco_garbage_troop", ":slot_id", "$g_lco_drag_modifier"),
                        (try_begin),
                            (gt, "$g_lco_drag_quantity", 0),
                            (troop_inventory_slot_set_item_amount, "$g_lco_garbage_troop", ":slot_id", "$g_lco_drag_quantity"),
                        (try_end),
                        (assign, "$g_lco_dragging", 0),
                        (assign, ":capacity", 0), # Break cycle
                        (troop_sort_inventory, "$g_lco_garbage_troop"),
                    (try_end),
                (try_end),
                # If no longer dragging, we need to make proper modifications
                (try_begin),
                    (eq, "$g_lco_dragging", 0),
                    (assign, "$g_lco_dragging_from", 0),      # Troop ID of dragged item current owner
                    (assign, "$g_lco_dragging_from_slot", 0), # Slot ID of dragged item current owner
                    (assign, "$g_lco_drag_item", -1),         # Item type currently being dragged
                    (assign, "$g_lco_drag_modifier", 0),      # Modifier of item currently being dragged
                    (assign, "$g_lco_drag_quantity", 0),      # Quantity of item currently being dragged (for foods)
                    (assign, "$g_lco_drag_quantity_max", 0),  # Max quantity of item currently being dragged (for foods)
                    (overlay_set_display, "$g_lco_dragging_panel", 0),
                (try_end),
            (try_end),
        ]
    ),

    ("lco_drop_item",
        [
            (store_script_param_1, ":troop_id"),
            (store_script_param_2, ":slot_id"),
            (try_begin),
                # If user is dropping item to garbage, then we override normal procedure and just drop the item, even if player is clicking on a filled panel
                (eq, ":troop_id", "$g_lco_garbage_troop"),
                (call_script, "script_lco_discard_item", "$g_lco_drag_item", "$g_lco_drag_modifier", "$g_lco_drag_quantity"),
                (assign, "$g_lco_dragging_from", 0),      # Troop ID of dragged item current owner
                (assign, "$g_lco_dragging_from_slot", 0), # Slot ID of dragged item current owner
                (assign, "$g_lco_drag_item", -1),         # Item type currently being dragged
                (assign, "$g_lco_drag_modifier", 0),      # Modifier of item currently being dragged
                (assign, "$g_lco_drag_quantity", 0),      # Quantity of item currently being dragged (for foods)
                (assign, "$g_lco_drag_quantity_max", 0),  # Max quantity of item currently being dragged (for foods)
                (assign, "$g_lco_dragging", 0),
                (overlay_set_display, "$g_lco_dragging_panel", 0),
            (else_try),
                (call_script, "script_cf_lco_controllable", ":troop_id"),
                (troop_get_inventory_slot, ":ex_item_id", ":troop_id", ":slot_id"),
                (troop_get_inventory_slot_modifier, ":ex_modifier", ":troop_id", ":slot_id"),
                (troop_inventory_slot_get_item_amount, ":ex_quantity", ":troop_id", ":slot_id"),
                (troop_inventory_slot_get_item_max_amount, ":ex_quantity_max", ":troop_id", ":slot_id"),
                (troop_set_inventory_slot, ":troop_id", ":slot_id", "$g_lco_drag_item"),
                (troop_set_inventory_slot_modifier, ":troop_id", ":slot_id", "$g_lco_drag_modifier"),
                (try_begin),
                    (gt, "$g_lco_drag_quantity", 0),
                    (troop_inventory_slot_set_item_amount, ":troop_id", ":slot_id", "$g_lco_drag_quantity"),
                (try_end),
                (try_begin),
                    (ge, ":ex_item_id", 0),
                    (assign, "$g_lco_drag_item", ":ex_item_id"),
                    (assign, "$g_lco_drag_modifier", ":ex_modifier"),
                    (assign, "$g_lco_drag_quantity", ":ex_quantity"),
                    (assign, "$g_lco_drag_quantity_max", ":ex_quantity_max"),
                    (assign, "$g_lco_dragging_from", ":troop_id"),
                    (assign, "$g_lco_dragging_from_slot", ":slot_id"),
                    # Displaying overlay
                    (call_script, "script_lco_item_name_to_s41", "$g_lco_drag_item", "$g_lco_drag_modifier", "$g_lco_drag_quantity", "$g_lco_drag_quantity_max"),
                    (overlay_set_text, "$g_lco_dragging_text", s41),
                    (overlay_set_display, "$g_lco_dragging_panel", 1), # Not necessary but just in case
                    (assign, "$g_lco_dragging", 1), # Not necessary but just in case
                (else_try),
                    (assign, "$g_lco_dragging_from", 0),      # Troop ID of dragged item current owner
                    (assign, "$g_lco_dragging_from_slot", 0), # Slot ID of dragged item current owner
                    (assign, "$g_lco_drag_item", -1),         # Item type currently being dragged
                    (assign, "$g_lco_drag_modifier", 0),      # Modifier of item currently being dragged
                    (assign, "$g_lco_drag_quantity", 0),      # Quantity of item currently being dragged (for foods)
                    (assign, "$g_lco_drag_quantity_max", 0),  # Max quantity of item currently being dragged (for foods)
                    (assign, "$g_lco_dragging", 0),
                    (overlay_set_display, "$g_lco_dragging_panel", 0),
                (try_end),
            (else_try),
                (display_message, "str_lco_drop_error_control", 0xFF4040),
            (try_end),

        ]
    ),

    # OUTPUT: reg0 = error string if cannot drop
    ("cf_lco_can_drop_item",
        [
            (store_script_param, ":troop_id", 1),
            (store_script_param, ":slot_id", 2),
            (store_script_param, ":item_id", 3),
            (store_script_param, ":modifier", 4),

            (assign, reg0, "str_lco_drop_error_control"),
            (call_script, "script_cf_lco_controllable", ":troop_id"),

            (assign, ":can_drop", 0),
            (assign, ":result", "str_lco_drop_error_type"),
            (try_begin),
                (ge, ":slot_id", num_equipment_kinds),
                (try_begin),
                    (this_or_next|eq, ":troop_id", "trp_player"),
                    (eq, ":troop_id", "$g_lco_garbage_troop"),
                    (assign, ":can_drop", 1), # We can drop anything into player's inventory slots or to the garbage
                (else_try),
                    (item_get_type, ":type", ":item_id"),
                    (eq, ":type", itp_type_book), # We can only drop books into other companions inventory slots
                    # Update V1.1. Disable book slots configuration variable
                    (eq, "$g_lco_suppress_books", 0),
                    (assign, ":can_drop", 1),
                (try_end),
            (else_try),
                (item_get_type, ":type", ":item_id"),
                (try_begin),
                    (lt, ":slot_id", 4), # Weapon slot
                    (this_or_next|eq, ":type", itp_type_one_handed_wpn),
                    (this_or_next|eq, ":type", itp_type_two_handed_wpn),
                    (this_or_next|eq, ":type", itp_type_polearm),
                    (this_or_next|eq, ":type", itp_type_arrows),
                    (this_or_next|eq, ":type", itp_type_bolts),
                    (this_or_next|eq, ":type", itp_type_shield),
                    (this_or_next|eq, ":type", itp_type_bow),
                    (this_or_next|eq, ":type", itp_type_crossbow),
                    (this_or_next|eq, ":type", itp_type_thrown),
                    (this_or_next|eq, ":type", itp_type_pistol),
                    (this_or_next|eq, ":type", itp_type_musket),
                    (eq, ":type", itp_type_bullets),
                    (assign, ":can_drop", 1),
                (else_try),
                    (eq, ":slot_id", 4), # Head armor
                    (eq, ":type", itp_type_head_armor),
                    (assign, ":can_drop", 1),
                (else_try),
                    (eq, ":slot_id", 5), # Body armor
                    (eq, ":type", itp_type_body_armor),
                    (assign, ":can_drop", 1),
                (else_try),
                    (eq, ":slot_id", 6), # Leg armor
                    (eq, ":type", itp_type_foot_armor),
                    (assign, ":can_drop", 1),
                (else_try),
                    (eq, ":slot_id", 7), # Hand armor
                    (eq, ":type", itp_type_hand_armor),
                    (assign, ":can_drop", 1),
                (else_try),
                    (eq, ":slot_id", 8), # Horse
                    (eq, ":type", itp_type_horse),
                    (assign, ":can_drop", 1),
                (try_end),
                (try_begin),
                    (eq, ":can_drop", 1), # Item and slot match by type, but can the character actually equip this item?
                    (neq, ":type", itp_type_arrows),  # Do not check for ammo
                    (neq, ":type", itp_type_bolts),   # Do not check for ammo
                    (neq, ":type", itp_type_bullets), # Do not check for ammo
                    # BugFix V1.1. Shields are no longer exempt from prerequisite checks.
                    #(neq, ":type", itp_type_shield), # Do not check for shields
                    (assign, ":result", "str_lco_drop_error_reqs"),
                    (call_script, "script_lco_replicate_attributes", ":troop_id"),
                    (call_script, "script_lco_clear_all_items", lco_storage),
                    (troop_set_auto_equip, lco_storage, 0),
                    (troop_set_inventory_slot, lco_storage, num_equipment_kinds, ":item_id"),
                    (troop_set_inventory_slot_modifier, lco_storage, num_equipment_kinds, ":modifier"),
                    # BugFix V1.1. Shields require some additional care
                    (try_begin),
                        (eq, ":type", itp_type_shield),
                        (troop_add_item, lco_storage, "itm_tutorial_club", imod_plain), # So the testing troop has both weapon and shield and auto-equip will work properly.
                    (try_end),
                    (troop_equip_items, lco_storage),
                    (troop_get_inventory_slot, ":copy_item_id", lco_storage, num_equipment_kinds),
                    (call_script, "script_lco_clear_all_items", lco_storage),
                    (ge, ":copy_item_id", 0), # He did not equip it!
                    (assign, ":can_drop", 0), # Hence original troop cannot equip it either!
                (try_end),
            (try_end),
            (assign, reg0, ":result"),
            (eq, ":can_drop", 1),
        ]
    ),

    ("lco_set_active_hero",
        [
            (store_script_param_1, ":index"),
            (assign, "$g_lco_active_hero", ":index"),
            (position_set_x, pos60, 25),
            (store_mul, ":base_y", "$g_lco_heroes", 25),
            (val_sub, ":base_y", 25),
            (val_max, ":base_y", 500),
            (store_mul, ":y", "$g_lco_active_hero", 25),
            (store_sub, ":y", ":base_y", ":y"),
            (position_set_y, pos60, ":y"),
            (overlay_set_position, "$g_lco_active_panel", pos60),
            (call_script, "script_lco_fill_hero_panels"),
        ]
    ),

    # This script will scan hero inventory and will return his "book" slots.
    # Slot numbers of first two books found in character inventory are used as the book slots.
    # If less than two books are found, remaining ones are picked from free slots in character inventory.
    ("lco_allocate_slots_for_books",
        [
            (store_script_param_1, ":troop_id"),
            (troop_sort_inventory, ":troop_id"),
            (troop_get_inventory_capacity, ":capacity", ":troop_id"),
            (assign, reg0, -1),
            (assign, reg1, -1),
            (try_for_range, ":slot_id", num_equipment_kinds, ":capacity"),
                (troop_get_inventory_slot, ":item_id", ":troop_id", ":slot_id"),
                (try_begin),
                    (ge, ":item_id", 0),
                    (item_get_type, ":type", ":item_id"),
                    (eq, ":type", itp_type_book),
                    (try_begin),
                        (eq, reg0, -1),
                        (assign, reg0, ":slot_id"),
                    (else_try),
                        (eq, reg1, -1),
                        (assign, reg1, ":slot_id"),
                    (try_end),
                (try_end),
            (try_end),
            (try_for_range, ":slot_id", num_equipment_kinds, ":capacity"),
                (troop_get_inventory_slot, ":item_id", ":troop_id", ":slot_id"),
                (try_begin),
                    (lt, ":item_id", 0),
                    (try_begin),
                        (eq, reg0, -1),
                        (assign, reg0, ":slot_id"),
                    (else_try),
                        (eq, reg1, -1),
                        (assign, reg1, ":slot_id"),
                    (try_end),
                (try_end),
            (try_end),
        ]
    ),

    ("cf_lco_auto_offer_item",
        [
            (store_script_param, ":troop_id", 1),
            (store_script_param, ":item_id", 2),
            (store_script_param, ":modifier", 3),
            (store_script_param, ":quantity", 4),
            (item_get_type, ":type", ":item_id"),
            (assign, ":out_item_id", -1),
            (assign, ":out_modifier", 0),
            (assign, ":out_quantity", 0),
            (assign, ":out_quantity_max", 0),
            (assign, ":is_equipped", 0),

            (call_script, "script_cf_lco_controllable", ":troop_id"), # Automatic failure

            # First option: if item is a weapon, troop has a free slot and can equip the item, we equip it by default
            (try_begin),
                (this_or_next|is_between, ":type", itp_type_one_handed_wpn, itp_type_goods),
                (is_between, ":type", itp_type_pistol, itp_type_animal),
                (try_for_range, ":slot_id", 0, 4),
                    (eq, ":is_equipped", 0),
                    (troop_get_inventory_slot, ":eq_item_id", ":troop_id", ":slot_id"),
                    (lt, ":eq_item_id", 0),
                    (call_script, "script_cf_lco_can_drop_item", ":troop_id", ":slot_id", ":item_id", ":modifier"),
                    (troop_set_inventory_slot, ":troop_id", ":slot_id", ":item_id"),
                    (troop_set_inventory_slot_modifier, ":troop_id", ":slot_id", ":modifier"),
                    (try_begin),
                        (gt, ":quantity", 0),
                        (troop_inventory_slot_set_item_amount, ":troop_id", ":slot_id", ":quantity"),
                    (try_end),
                    (assign, ":is_equipped", 1),
                (try_end),
            (try_end),

            # Second option: if item is a book, we automatically give it to troop, sort the inventory and look for books.
            # If we find more than two, we'll return the third.
            # TODO: When companion book reading is implemented, need to make proper checks here.
            # Companion should not automatically give away a book he's currently reading.
            (try_begin),
                (eq, ":is_equipped", 0),
                (eq, ":type", itp_type_book),
                # Update V1.1. Disable book slots configuration variable
                (eq, "$g_lco_suppress_books", 0),
                (troop_add_item, ":troop_id", ":item_id", ":modifier"),
                (assign, ":is_equipped", 1),
                (troop_sort_inventory, ":troop_id"),
                (troop_get_inventory_capacity, ":capacity", ":troop_id"),
                (assign, ":books_found", 0),
                (try_for_range, ":slot_id", num_equipment_kinds, ":capacity"),
                    (troop_get_inventory_slot, ":cur_item_id", ":troop_id", ":slot_id"),
                    (ge, ":cur_item_id", 0),
                    (item_get_type, ":cur_type", ":cur_item_id"),
                    (eq, ":cur_type", itp_type_book),
                    (try_begin),
                        (lt, ":books_found", 2),
                        (val_add, ":books_found", 1),
                    (else_try),
                        (assign, ":out_item_id", ":cur_item_id"),
                        (troop_set_inventory_slot, ":troop_id", ":slot_id", -1), # Delete book from inventory
                        (assign, ":capacity", 0), # Break cycle
                    (try_end),
                (try_end),
            (try_end),

            # Third option: we create a duplicate, give him an item and check if he will equip it.
            # If he will not equip it, it's a failure
            # If he will equip it, there may be zero, one or more items lying in inventory.
            # If it's zero, fine.
            # If it's one, also fine, we return it as a compensation item
            # If it's more than one, then we sort inventory and add ammo/shield items to free slots while there are free slots
            # Then we sort again and retrieve the first item in inventory as compensation
            (try_begin),
                (eq, ":is_equipped", 0),
                (neq, ":type", itp_type_goods),
                (neq, ":type", itp_type_animal),
                (neq, ":type", itp_type_book),
                (call_script, "script_lco_clear_all_items", lco_storage),
                (call_script, "script_lco_replicate_attributes", ":troop_id"),
                (call_script, "script_lco_replicate_equipment", ":troop_id"),
                (troop_add_item, lco_storage, ":item_id", ":modifier"),
                (troop_equip_items, lco_storage),
                (troop_sort_inventory, lco_storage),
                # Checking if our item is lying in inventory
                (assign, ":is_equipped", 1),
                (troop_get_inventory_capacity, ":capacity", ":troop_id"),
                (try_for_range, ":slot_id", num_equipment_kinds, ":capacity"),
                    (troop_get_inventory_slot, ":inv_item_id", lco_storage, ":slot_id"),
                    (troop_get_inventory_slot_modifier, ":inv_modifier", lco_storage, ":slot_id"),
                    (eq, ":item_id", ":inv_item_id"),
                    (eq, ":modifier", ":inv_modifier"),
                    (assign, ":is_equipped", 0), # Troop refused to equip our item, so no sense checking further
                    (assign, ":capacity", 0), # Break cycle
                (try_end),
                # Since it's not, we are now looking for a slot to put the item in.
                (try_begin),
                    (eq, ":is_equipped", 1),
                    (assign, ":swap_slot", -1),
                    (try_begin),
                        (eq, ":type", itp_type_horse),
                        (assign, ":swap_slot", 8),
                    (else_try),
                        (is_between, ":type", itp_type_head_armor, itp_type_pistol),
                        (store_sub, ":swap_slot", ":type", 8),
                    (else_try),
                        # Our item is a weapon or ammo.
                        # This means we have at least one item in inventory (if there was an empty weapon slot it would be filled on first option).
                        # Now we look for the first item that is not ammo. If we find it, this is the swapped item.
                        (assign, ":swap_item_id", -1),
                        (assign, ":swap_item_mod", 0),
                        (try_for_range, ":slot_id", num_equipment_kinds, num_equipment_kinds+5), # Because there cannot be more items by code design
                            (eq, ":swap_item_id", -1), # Not yet found
                            (troop_get_inventory_slot, ":cur_item_id", lco_storage, ":slot_id"),
                            (ge, ":cur_item_id", 0), # Slot is not empty
                            (item_get_type, ":cur_type", ":cur_item_id"),
                            (this_or_next|is_between, ":cur_type", itp_type_one_handed_wpn, itp_type_arrows),
                            (this_or_next|is_between, ":cur_type", itp_type_bow, itp_type_goods),
                            (is_between, ":cur_type", itp_type_pistol, itp_type_bullets),
                            (assign, ":swap_item_id", ":cur_item_id"),
                            (troop_get_inventory_slot_modifier, ":swap_item_mod", lco_storage, ":slot_id"),
                        (try_end),
                        # If we didn't find a weapon, then we look for ammo and choose the last in the list (least expensive)
                        (try_for_range_backwards, ":slot_id", num_equipment_kinds, num_equipment_kinds+5), # Because there cannot be more items by code design
                            (eq, ":swap_item_id", -1), # Not yet found
                            (troop_get_inventory_slot, ":cur_item_id", lco_storage, ":slot_id"),
                            (ge, ":cur_item_id", 0), # Slot is not empty
                            (item_get_type, ":cur_type", ":cur_item_id"),
                            (this_or_next|eq, ":cur_type", itp_type_bullets),
                            (is_between, ":cur_type", itp_type_arrows, itp_type_shield),
                            (assign, ":swap_item_id", ":cur_item_id"),
                            (troop_get_inventory_slot_modifier, ":swap_item_mod", lco_storage, ":slot_id"),
                        (try_end),
                        # If we didn't find anything, that's an error and we report it. Otherwise, we are looking for swap_item slot in the original troop equipment
                        (try_begin),
                            (eq, ":swap_item_id", -1),
                            (display_message, "str_lco_impossible_error"),
                        (else_try),
                            (try_for_range, ":slot_id", 0, num_equipment_kinds),
                                (troop_get_inventory_slot, ":cur_item_id", ":troop_id", ":slot_id"),
                                (troop_get_inventory_slot_modifier, ":cur_item_mod", ":troop_id", ":slot_id"),
                                (eq, ":cur_item_id", ":swap_item_id"),
                                (eq, ":cur_item_mod", ":swap_item_mod"),
                                (assign, ":swap_slot", ":slot_id"),
                            (try_end),
                        (try_end),
                    (try_end),

                    # Now we have ":swap_slot" keeping the slot id in the original troop equipment that we are putting offered item to.
                    (try_begin),
                        (eq, ":swap_slot", -1),
                        (assign, ":is_equipped", 0),
                    (else_try),
                        (troop_get_inventory_slot, ":out_item_id", ":troop_id", ":swap_slot"),
                        (troop_get_inventory_slot_modifier, ":out_modifier", ":troop_id", ":swap_slot"),
                        (troop_inventory_slot_get_item_amount, ":out_quantity", ":troop_id", ":swap_slot"),
                        (troop_inventory_slot_get_item_max_amount, ":out_quantity", ":troop_id", ":swap_slot"),
                        (troop_set_inventory_slot, ":troop_id", ":swap_slot", ":item_id"),
                        (troop_set_inventory_slot_modifier, ":troop_id", ":swap_slot", ":modifier"),
                        (assign, ":is_equipped", 1),
                    (try_end),
                (try_end),
            (try_end),

            (eq, ":is_equipped", 1),
            (assign, reg0, ":out_item_id"),
            (assign, reg1, ":out_modifier"),
            (assign, reg2, ":out_quantity"),
            (assign, reg3, ":out_quantity_max"),
        ]
    ),

    ("lco_backup_inventory",
        [
            (store_script_param_1, ":troop_id"),
            (call_script, "script_lco_clear_all_items", lco_storage),
            (troop_set_auto_equip, lco_storage, 0),
            (troop_get_inventory_capacity, ":capacity", ":troop_id"),
            (assign, ":target_id", num_equipment_kinds),
            (try_for_range, ":source_id", num_equipment_kinds, ":capacity"),
                (troop_get_inventory_slot, ":item_id", ":troop_id", ":source_id"),
                (ge, ":item_id", 0),
                (troop_get_inventory_slot_modifier, ":modifier", ":troop_id", ":source_id"),
                (troop_inventory_slot_get_item_amount, ":qty", ":troop_id", ":source_id"),
                (troop_set_inventory_slot, lco_storage, ":target_id", ":item_id"),
                (troop_set_inventory_slot_modifier, lco_storage, ":target_id", ":modifier"),
                (try_begin),
                    (gt, ":qty", 0),
                    (troop_inventory_slot_set_item_amount, lco_storage, ":target_id", ":qty"),
                (try_end),
                (troop_set_inventory_slot, ":troop_id", ":source_id", -1),
                (val_add, ":target_id", 1),
            (try_end),
        ]
    ),

    ("lco_retrieve_inventory",
        [
            (store_script_param_1, ":troop_id"),
            (troop_sort_inventory, lco_storage),
            (troop_get_inventory_capacity, ":capacity", ":troop_id"),
            (assign, ":source_id", num_equipment_kinds),
            (try_for_range, ":target_id", num_equipment_kinds, ":capacity"),
                (troop_get_inventory_slot, ":cur_item_id", ":troop_id", ":target_id"),
                (lt, ":cur_item_id", 0), # Current slot empty?
                (troop_get_inventory_slot, ":item_id", lco_storage, ":source_id"),
                (ge, ":item_id", 0), # There is still an item in the storage?
                (troop_get_inventory_slot_modifier, ":modifier", lco_storage, ":source_id"),
                (troop_inventory_slot_get_item_amount, ":qty", lco_storage, ":source_id"),
                (troop_set_inventory_slot, ":troop_id", ":target_id", ":item_id"),
                (troop_set_inventory_slot_modifier, ":troop_id", ":target_id", ":modifier"),
                (try_begin),
                    (gt, ":qty", 0),
                    (troop_inventory_slot_set_item_amount, ":troop_id", ":target_id", ":qty"),
                (try_end),
                (val_add, ":source_id", 1),
            (try_end),
            (call_script, "script_lco_clear_all_items", lco_storage),
        ]
    ),

    ("lco_clear_all_items",
        [
            (store_script_param_1, ":troop_id"),
            (troop_clear_inventory, ":troop_id"),
            (try_for_range, ":index", 0, 9),
                (troop_set_inventory_slot, ":troop_id", ":index", -1), # Cleaning equipment
            (try_end),
        ]
    ),

    ("lco_replicate_attributes",
        [
            # BugFix V1.1. Added shield skill to the list of monitored skills and attributes.
            (store_script_param_1, ":troop_id"),
            (store_attribute_level, ":str", ":troop_id", ca_strength),
            (store_skill_level, ":pdraw", "skl_power_draw", ":troop_id"),
            (store_skill_level, ":pthrow", "skl_power_throw", ":troop_id"),
            (store_skill_level, ":riding", "skl_riding", ":troop_id"),
            (store_skill_level, ":shield", "skl_shield", ":troop_id"),
            (store_attribute_level, ":ex_str", lco_storage, ca_strength),
            (store_skill_level, ":ex_pdraw", "skl_power_draw", lco_storage),
            (store_skill_level, ":ex_pthrow", "skl_power_throw", lco_storage),
            (store_skill_level, ":ex_riding", "skl_riding", lco_storage),
            (store_skill_level, ":ex_shield", "skl_shield", lco_storage),
            (val_sub, ":str", ":ex_str"),
            (val_sub, ":pdraw", ":ex_pdraw"),
            (val_sub, ":pthrow", ":ex_pthrow"),
            (val_sub, ":riding", ":ex_riding"),
            (val_sub, ":shield", ":ex_shield"),
            (troop_raise_attribute, lco_storage, ca_strength, ":str"),
            (troop_raise_skill, lco_storage, "skl_power_draw", ":pdraw"),
            (troop_raise_skill, lco_storage, "skl_power_throw", ":pthrow"),
            (troop_raise_skill, lco_storage, "skl_riding", ":riding"),
            (troop_raise_skill, lco_storage, "skl_shield", ":shield"),
        ]
    ),

    ("lco_replicate_equipment",
        [
            (store_script_param_1, ":troop_id"),
            (try_for_range, ":index", 0, num_equipment_kinds),
                (troop_get_inventory_slot, ":item_id", ":troop_id", ":index"),
                (troop_get_inventory_slot_modifier, ":modifier", ":troop_id", ":index"),
                (troop_set_inventory_slot, lco_storage, ":index", ":item_id"),
                (troop_set_inventory_slot_modifier, lco_storage, ":index", ":modifier"),
            (try_end),
        ]
    ),

    ("lco_hero_grab_equipment",
        [
            (store_script_param, ":troop_id", 1),
            (assign, ":hero_offset", num_equipment_kinds),
            (troop_get_inventory_capacity, ":capacity", "trp_player"),
            (troop_get_inventory_capacity, ":hero_capacity", ":troop_id"),
            (try_for_range, ":slot_id", num_equipment_kinds, ":capacity"),
                (try_begin),
                    (call_script, "script_cf_lco_slot_is_frozen", ":slot_id"), # If current slot is frozen, we skip it in either case
                (else_try),
                    (troop_get_inventory_slot, ":item_id", "trp_player", ":slot_id"),
                    (ge, ":item_id", 0),
                    (assign, ":grab", 0),
                    (item_get_type, ":type", ":item_id"),
                    # Will companion grab this item?
                    (try_begin),
                        (eq, "$g_lco_auto_horses", 1),
                        (eq, ":type", itp_type_horse),
                        (assign, ":grab", 1),
                    (else_try),
                        (eq, "$g_lco_auto_armors", 1),
                        (this_or_next|eq, ":type", itp_type_head_armor),
                        (this_or_next|eq, ":type", itp_type_body_armor),
                        (this_or_next|eq, ":type", itp_type_foot_armor),
                        (eq, ":type", itp_type_hand_armor),
                        (assign, ":grab", 1),
                    (else_try),
                        (eq, "$g_lco_auto_shields", 1),
                        (eq, ":type", itp_type_shield),
                        (assign, ":grab", 1),
                    (try_end),
                    (this_or_next|eq, ":troop_id", lco_storage), # When this operation is used on lco_storage, this means we are sorting player's inventory, so just take everything
                    (eq, ":grab", 1),
                    (troop_get_inventory_slot_modifier, ":modifier", "trp_player", ":slot_id"),
                    (troop_set_inventory_slot, ":troop_id", ":hero_offset", ":item_id"),
                    (troop_set_inventory_slot_modifier, ":troop_id", ":hero_offset", ":modifier"),
                    (troop_set_inventory_slot, "trp_player", ":slot_id", -1), # Remove item
                    (val_add, ":hero_offset", 1),
                    (ge, ":hero_offset", ":hero_capacity"),
                    (assign, ":capacity", 0), # Break cycle because companion has no space in inventory for more items
                (try_end),
            (try_end),
        ]
    ),

    ("lco_hero_return_equipment",
        [
            (store_script_param, ":troop_id", 1),
            (troop_sort_inventory, ":troop_id"),
            (troop_get_inventory_capacity, ":hero_capacity", ":troop_id"),
            # Companion is returning items to player
            (troop_get_inventory_capacity, ":capacity", "trp_player"),
            (assign, ":hero_offset", num_equipment_kinds),
            (try_for_range, ":slot_id", num_equipment_kinds, ":capacity"),
                (try_begin),
                    (call_script, "script_cf_lco_slot_is_frozen", ":slot_id"), # If current slot is frozen, we skip it
                (else_try),
                    (troop_get_inventory_slot, ":item_id", "trp_player", ":slot_id"),
                    (lt, ":item_id", 0), # Slot is empty, can get item back
                    (troop_get_inventory_slot, ":item_id", ":troop_id", ":hero_offset"),
                    (troop_get_inventory_slot_modifier, ":modifier", ":troop_id", ":hero_offset"),
                    (troop_set_inventory_slot, "trp_player", ":slot_id", ":item_id"),
                    (troop_set_inventory_slot_modifier, "trp_player", ":slot_id", ":modifier"),
                    (troop_set_inventory_slot, ":troop_id", ":hero_offset", -1), # Remove item
                    (val_add, ":hero_offset", 1),
                    (ge, ":hero_offset", ":hero_capacity"),
                    (assign, ":capacity", 0), # Break cycle because we reached the end of companion's inventory
                (try_end),
            (try_end),
            # If player's inventory is full and companion still has items in inventory, he will drop them to garbage
            (troop_get_inventory_capacity, ":capacity", "$g_lco_garbage_troop"),
            (assign, ":hero_offset", num_equipment_kinds),
            (try_for_range, ":slot_id", num_equipment_kinds, ":capacity"),
                (troop_get_inventory_slot, ":item_id", "$g_lco_garbage_troop", ":slot_id"),
                (lt, ":item_id", 0), # Slot is empty, can get item back
                (troop_get_inventory_slot, ":item_id", ":troop_id", ":hero_offset"),
                (troop_get_inventory_slot_modifier, ":modifier", ":troop_id", ":hero_offset"),
                (troop_set_inventory_slot, "$g_lco_garbage_troop", ":slot_id", ":item_id"),
                (troop_set_inventory_slot_modifier, "$g_lco_garbage_troop", ":slot_id", ":modifier"),
                (troop_set_inventory_slot, ":troop_id", ":hero_offset", -1), # Remove item
                (val_add, ":hero_offset", 1),
                (ge, ":hero_offset", ":hero_capacity"),
                (assign, ":capacity", 0), # Break cycle because we reached the end of companion's inventory
            (try_end),
            (troop_sort_inventory, "$g_lco_garbage_troop"),
        ]
    ),

    ("lco_text_label",
        [
            (store_script_param, ":string", 1),
            (store_script_param, ":x", 2),
            (store_script_param, ":y", 3),
            (val_sub, ":x", 1), # Compensation for bad looks
            (set_fixed_point_multiplier, 1000),
            (init_position, pos60),
            (init_position, pos62),
            (position_set_x, pos60, ":x"),
            (position_set_y, pos60, ":y"),
            (position_set_x, pos62, 750),
            (position_set_y, pos62, 750),
            (create_text_overlay, ":label", ":string", tf_center_justify),
            (overlay_set_position, ":label", pos60),
            (overlay_set_size, ":label", pos62),
            (assign, reg0, ":label"),
        ]
    ),

    ("lco_text_caption",
        [
            (store_script_param, ":string", 1),
            (store_script_param, ":x", 2),
            (store_script_param, ":y", 3),
            (val_sub, ":x", 1), # Compensation for bad looks
            (val_sub, ":y", 105),
            (set_fixed_point_multiplier, 1000),
            (init_position, pos60),
            (init_position, pos62),
            (position_set_x, pos60, ":x"),
            (position_set_y, pos60, ":y"),
            (position_rotate_z, pos60, 45),
            (position_set_x, pos62, 750),
            (position_set_y, pos62, 750),
            (create_text_overlay, ":label", ":string"),
            (overlay_set_size, ":label", pos62),
            (overlay_set_position, ":label", pos60),
            (overlay_set_mesh_rotation, ":label", pos60),
            (create_text_overlay, ":label", ":string"),
            (overlay_set_size, ":label", pos62),
            (overlay_set_position, ":label", pos60),
            (overlay_set_mesh_rotation, ":label", pos60),
            (assign, reg0, ":label"),
        ]
    ),

    ("lco_initialize_presentation",
        [

            (presentation_set_duration, 999999),
            (try_begin),
                (eq, "$g_lco_initialized", 0),
                (assign, "$g_lco_activate_troop", 0), # By default, we do not make a particular troop active
                (assign, "$g_lco_active_hero", 0),    # We show the first hero by default
                (assign, "$g_lco_page", 0),           # We show the first page by default
                (assign, "$g_lco_operation", 0),      # No special action by default
                (assign, "$g_lco_target", 0),         # No action target by default
                (assign, "$g_lco_auto_horses", 1),    # Horses are auto-equipped by default
                (assign, "$g_lco_auto_armors", 1),    # Same
                (assign, "$g_lco_auto_shields", 1),   # Same
                (assign, "$g_lco_include_companions", 1),
                (assign, "$g_lco_include_lords", 0),
                (assign, "$g_lco_include_regulars", 0),
                # BugFix V1.1. Do not overwrite $g_lco_garbage_troop on first run if it's already initialized.
                (try_begin),
                    (lt, "$g_lco_garbage_troop", 3),
                    (assign, "$g_lco_garbage_troop", lco_garbage), # This troop will be used for discarding items or looting, and it's inventory will be purged on exit
                (try_end),
                (assign, "$g_lco_initialized", 1),
                # BugFix V1.2. Hardcoded xp-to-level conversion table has been removed
            (try_end),

            # GLOBAL VARIABLES INITIALIZATION

            (assign, "$g_lco_heroes", 0),             # Total number of heroes in the party, excluding player
            (assign, "$g_lco_inv_slots", 0),          # Total number of slots in the player's inventory
            (assign, "$g_lco_dragging", 0),           # Currently not dragging anything
            (assign, "$g_lco_dragging_from", 0),      # Troop ID of dragged item current owner
            (assign, "$g_lco_dragging_from_slot", 0), # Slot ID of dragged item current owner
            (assign, "$g_lco_drag_item", -1),         # Item type currently being dragged
            (assign, "$g_lco_drag_modifier", 0),      # Modifier of item currently being dragged
            (assign, "$g_lco_drag_quantity", 0),      # Quantity of item currently being dragged (for foods)
            (assign, "$g_lco_drag_quantity_max", 0),  # Max quantity of item currently being dragged (for foods)
            (assign, "$g_lco_popup_active", 0),       # Whether or not there's an active popup with item details
            (assign, "$g_lco_popup_overlay", 0),      # Overlay ID that caused the popup to appear (to prevent popup from disappearing when mouseout happens on another overlay)
            (assign, "$g_lco_popup_item", 0),         # ID of the item to show in popup
            (assign, "$g_lco_popup_modifier", 0),     # ID of the modifier to show in popup
            (assign, "$g_lco_panel_found", 0),        # Variable is used to prevent a single click from affecting two panels simultaneously in equipment_overview

            (val_clamp, "$g_lco_auto_horses", 0, 2),
            (val_clamp, "$g_lco_auto_armors", 0, 2),
            (val_clamp, "$g_lco_auto_shields", 0, 2),
            (val_clamp, "$g_lco_include_companions", 0, 2),
            (val_clamp, "$g_lco_include_lords", 0, 2),
            (val_clamp, "$g_lco_include_regulars", 0, 2),
            (try_begin),
                (is_presentation_active, "prsnt_companions_overview"),
                (val_clamp, "$g_lco_page", 0, 2),   # Current page to display
            (try_end),

            # TROOP HANDLING

            (call_script, "script_lco_prepare_heroes"),
            (try_begin),
                # We are requested to make a particular troop active
                (gt, "$g_lco_activate_troop", 0),
                (try_for_range, reg0, 0, "$g_lco_heroes"),
                    (store_add, ":offset", reg0, "$g_lco_heroes"),
                    (troop_slot_eq, lco_storage, ":offset", "$g_lco_activate_troop"),
                    (assign, "$g_lco_active_hero", ":offset"),
                (try_end),
                (assign, "$g_lco_activate_troop", 0),
            (try_end),
            (val_clamp, "$g_lco_active_hero", 0, "$g_lco_heroes"), # Index of currently selected hero
            (troop_get_inventory_capacity, "$g_lco_inv_slots", "trp_player"),
            (val_sub, "$g_lco_inv_slots", num_equipment_kinds),
            (troop_get_inventory_capacity, "$g_lco_garb_slots", "$g_lco_garbage_troop"),
            (val_sub, "$g_lco_garb_slots", num_equipment_kinds),
            (troop_set_auto_equip, lco_storage, 0),
            (call_script, "script_lco_clear_all_items", lco_storage),
            (troop_set_auto_equip, "$g_lco_garbage_troop", 0),
            # We do not clear garbage troop because it may be used for looting

            # PRESENTATION SHARED BUTTONS AND INCLUSION FORM

            (call_script, "script_lco_create_button", "str_lco_i_return", 855, 25, 190, 42),
            (assign, "$g_lco_return", reg0),
            (call_script, "script_lco_create_checkbox", "str_lco_i_list_companions",  25, 75, "$g_lco_include_companions"),
            (assign, "$g_lco_inc_0", reg0),
            (call_script, "script_lco_create_checkbox", "str_lco_i_list_lords",  25, 50, "$g_lco_include_lords"),
            (assign, "$g_lco_inc_1", reg0),
            (call_script, "script_lco_create_checkbox", "str_lco_i_list_regulars",  25, 25, "$g_lco_include_regulars"),
            (assign, "$g_lco_inc_2", reg0),

            (call_script, "script_lco_create_image_button", "mesh_lco_square_button_up", "mesh_lco_square_button_down", 25, 685, 333, 400),
            (assign, "$g_lco_switch_page_0", reg0),
            (call_script, "script_lco_create_image_button", "mesh_lco_square_button_up", "mesh_lco_square_button_down", 55, 685, 333, 400),
            (assign, "$g_lco_switch_page_1", reg0),
            (call_script, "script_lco_create_image_button", "mesh_lco_square_button_up", "mesh_lco_square_button_down", 85, 685, 333, 400),
            (assign, "$g_lco_switch_page_2", reg0),
            (store_mul, ":x", "$g_lco_page", 30),
            (val_add, ":x", 25),
            (call_script, "script_lco_create_mesh", "mesh_lco_square_button_down", ":x", 685, 333, 400),
            (assign, "$g_lco_selected_page", reg0),
            (assign, reg40, 1),
            (call_script, "script_lco_create_label", "str_lco_reg40", 35, 702, 750, tf_center_justify | tf_vertical_align_center),
            (assign, reg40, 2),
            (call_script, "script_lco_create_label", "str_lco_reg40", 65, 702, 750, tf_center_justify | tf_vertical_align_center),
            (str_store_string, s40, "str_lco_i_ie_icon"),
            (call_script, "script_lco_create_label", "str_lco_s40",   95, 702, 750, tf_center_justify | tf_vertical_align_center),

            # DISPLAYING VERSION INFORMATION

            (call_script, "script_lco_create_label", "str_lco_version", 975, 5, 750, tf_right_align),

        ]
    ),

    ("lco_prepare_heroes",
        [
            (assign, "$g_lco_heroes", 0), # Total number of heroes in the party, excluding player
            # CALCULATING NUMBER OF HEROES
            (try_begin),
                (eq, "$g_lco_include_companions", 1),
                (party_get_num_companion_stacks, ":total_stacks", "p_main_party"),
                (try_for_range, reg0, 0, ":total_stacks"),
                    (party_stack_get_troop_id, ":troop_id", "p_main_party", reg0),
                    (is_between, ":troop_id", companions_begin, companions_end),
                    (troop_set_slot, lco_storage, "$g_lco_heroes", ":troop_id"),
                    (val_add, "$g_lco_heroes", 1),
                (try_end),
            (try_end),
            (try_begin),
                (eq, "$g_lco_include_lords", 1),
                (gt, "$players_kingdom", 0),
                (faction_slot_eq, "$players_kingdom", slot_faction_leader, "trp_player"),
                (try_for_range, ":troop_id", active_npcs_begin, active_npcs_end),
                    (troop_slot_eq, ":troop_id", slot_troop_occupation, slto_kingdom_hero),
                    (troop_get_slot, ":party_no", ":troop_id", slot_troop_leaded_party),
                    (gt, ":party_no", 0),
                    (party_is_active, ":party_no"),
                    (troop_set_slot, lco_storage, "$g_lco_heroes", ":troop_id"),
                    (val_add, "$g_lco_heroes", 1),
                (try_end),
            (try_end),
            (try_begin),
                (eq, "$g_lco_include_regulars", 1),
                (party_get_num_companion_stacks, ":total_stacks", "p_main_party"),
                (try_for_range, reg0, 0, ":total_stacks"),
                    (party_stack_get_troop_id, ":troop_id", "p_main_party", reg0),
                    (neg|troop_is_hero, ":troop_id"),
                    (troop_set_slot, lco_storage, "$g_lco_heroes", ":troop_id"),
                    (val_add, "$g_lco_heroes", 1),
                (try_end),
            (try_end),
        ]
    ),

    ("cf_lco_controllable",
        [
            (store_script_param_1, ":troop_id"),
            (troop_is_hero, ":troop_id"), # We never have control over regulars
            (assign, ":control", 0),
            (try_begin),
                (this_or_next|eq, ":troop_id", "trp_player"),
                (eq, ":troop_id", "$g_lco_garbage_troop"),
                (assign, ":control", 1),
            (else_try),
                (gt, "$g_lco_heroes", 0),
                (is_between, ":troop_id", companions_begin, companions_end), # We do not provide control over lords
                (troop_slot_eq, ":troop_id", slot_troop_occupation, slto_player_companion),
                (assign, ":control", 1),
            (try_end),
            (eq, ":control", 1),
        ]
    ),

    ("lco_troop_name_to_s40",
        [
            (store_script_param_1, ":troop_id"),
            (try_begin),
                (troop_is_hero, ":troop_id"),
                (str_store_troop_name, s40, ":troop_id"),
            (else_try),
                (str_store_troop_name_plural, s40, ":troop_id"),
            (try_end),
        ]
    ),

    ("lco_discard_item",
        [
            (store_script_param, ":item_id", 1),
            (store_script_param, ":modifier", 2),
            (store_script_param, ":quantity", 3),
            (troop_sort_inventory, "$g_lco_garbage_troop"),
            (troop_get_inventory_capacity, ":capacity", "$g_lco_garbage_troop"),
            (store_sub, reg0, ":capacity", num_equipment_kinds),
            (assign, ":discarded", 0),
            (try_for_range, ":index", num_equipment_kinds, ":capacity"),
                (troop_get_inventory_slot, ":cur_item_id", "$g_lco_garbage_troop", ":index"),
                (lt, ":cur_item_id", 0),
                (troop_set_inventory_slot, "$g_lco_garbage_troop", ":index", ":item_id"),
                (troop_set_inventory_slot_modifier, "$g_lco_garbage_troop", ":index", ":modifier"),
                (try_begin),
                    (ge, ":quantity", 1),
                    (troop_inventory_slot_set_item_amount, "$g_lco_garbage_troop", ":index", ":quantity"),
                (try_end),
                (store_add, reg0, ":index", 1-num_equipment_kinds), # Total number of items in garbage
                (assign, ":capacity", 0), # Break cycle
                (assign, ":discarded", 1),
            (try_end),
            (try_begin),
                # If garbage troop inventory is full, we replace the last (cheapest) item
                (eq, ":discarded", 0),
                (assign, ":index", ":capacity"),
                (val_sub, ":index", 1),
                (troop_set_inventory_slot, "$g_lco_garbage_troop", ":index", ":item_id"),
                (troop_set_inventory_slot_modifier, "$g_lco_garbage_troop", ":index", ":modifier"),
                (try_begin),
                    (ge, ":quantity", 1),
                    (troop_inventory_slot_set_item_amount, "$g_lco_garbage_troop", ":index", ":quantity"),
                (try_end),
                (store_sub, reg0, ":capacity", num_equipment_kinds),
            (try_end),
            (troop_sort_inventory, "$g_lco_garbage_troop"),
        ]
    ),

    ("lco_retrieve_discarded",
        [
            (troop_sort_inventory, "$g_lco_garbage_troop"),
            (assign, ":hero_offset", num_equipment_kinds),
            (troop_get_inventory_capacity, ":capacity", "trp_player"),
            (troop_get_inventory_capacity, ":hero_capacity", "$g_lco_garbage_troop"),
            (try_for_range, ":slot_id", num_equipment_kinds, ":capacity"),
                (try_begin),
                    (call_script, "script_cf_lco_slot_is_frozen", ":slot_id"),
                (else_try),
                    (troop_get_inventory_slot, ":item_id", "trp_player", ":slot_id"),
                    (lt, ":item_id", 0), # Slot is empty, can get item back
                    (troop_get_inventory_slot, ":item_id", "$g_lco_garbage_troop", ":hero_offset"),
                    (troop_get_inventory_slot_modifier, ":modifier", "$g_lco_garbage_troop", ":hero_offset"),
                    (troop_inventory_slot_get_item_amount, ":quantity", "$g_lco_garbage_troop", ":hero_offset"),
                    (troop_set_inventory_slot, "trp_player", ":slot_id", ":item_id"),
                    (troop_set_inventory_slot_modifier, "trp_player", ":slot_id", ":modifier"),
                    (try_begin),
                        (ge, ":quantity", 1),
                        (troop_inventory_slot_set_item_amount, "trp_player", ":slot_id", ":quantity"),
                    (try_end),
                    (troop_set_inventory_slot, "$g_lco_garbage_troop", ":hero_offset", -1), # Remove item
                    (val_add, ":hero_offset", 1),
                    (ge, ":hero_offset", ":hero_capacity"),
                    (assign, ":capacity", 0),
                (try_end),
            (try_end),
            (call_script, "script_lco_count_discarded"),
        ]
    ),

    # Added in V1.20.
    ("lco_sort_player_inventory",
        [
            (call_script, "script_lco_clear_all_items", lco_storage),
            (call_script, "script_lco_hero_grab_equipment", lco_storage),
            (troop_sort_inventory, lco_storage),
            (call_script, "script_lco_hero_return_equipment", lco_storage),
        ]
    ),

    # Added in V1.20.
    # script_get_item_price
    # This script will return the price of an item in reg0
    # INPUT: <arg1> = item_type_id, <arg2> = item_modifier_id
    # OUTPUT: reg0 = nominal item price (price modifiers are ignored)
    ("lco_get_item_price",
        [
            (store_script_param, ":item_id", 1),
            (store_script_param, ":item_modifier", 2),
            (store_script_param, ":item_amount", 3),
            (troop_clear_inventory, lco_storage),
            (troop_set_auto_equip, lco_storage, 0),
            (troop_set_inventory_slot, lco_storage, num_equipment_kinds, ":item_id"),
            (troop_set_inventory_slot_modifier, lco_storage, num_equipment_kinds, ":item_modifier"),
            (try_begin),
                (ge, ":item_amount", 1),
                (troop_inventory_slot_set_item_amount, lco_storage, num_equipment_kinds, ":item_amount"),
            (try_end),
            (troop_remove_items, lco_storage, ":item_id", 1),
        ]
    ), 

    # Added in v1.20.
    ("lco_retrieve_discarded_best",
        [
            (call_script, "script_lco_retrieve_discarded"),
            (try_begin),
                (gt, reg0, 0), # If there are still items in loot
                # Sort player inventory
                (call_script, "script_lco_sort_player_inventory"),
                # Process
                (assign, ":hero_offset", num_equipment_kinds), # Offset of item in loot that is currently processed
                (troop_get_inventory_capacity, ":capacity", "trp_player"),
                (troop_get_inventory_capacity, ":hero_capacity", "$g_lco_garbage_troop"),
                (try_for_range_backwards, ":slot_id", num_equipment_kinds, ":capacity"),
                    (try_begin),
                        (call_script, "script_cf_lco_slot_is_frozen", ":slot_id"), # Skipping over frozen slots
                    (else_try),
                        # Retrieving item from garbage troop's inventory
                        (troop_get_inventory_slot, ":loot_item_id", "$g_lco_garbage_troop", ":hero_offset"),
                        (ge, ":loot_item_id", 0), # Garbage troop has an item in currently processed slot
                        (troop_get_inventory_slot_modifier, ":loot_modifier", "$g_lco_garbage_troop", ":hero_offset"),
                        (troop_inventory_slot_get_item_amount, ":loot_quantity", "$g_lco_garbage_troop", ":hero_offset"),
                        (call_script, "script_lco_get_item_price", ":loot_item_id", ":loot_modifier", ":loot_quantity"),
                        (assign, ":loot_price", reg0),
#(assign, reg41, ":loot_item_id"),(assign, reg42, ":loot_modifier"),(assign, reg43, ":loot_quantity"),(assign, reg44, ":loot_price"),
                        # Retrieving item from player's inventory
                        (troop_get_inventory_slot, ":item_id", "trp_player", ":slot_id"),
                        (troop_get_inventory_slot_modifier, ":modifier", "trp_player", ":slot_id"),
                        (troop_inventory_slot_get_item_amount, ":quantity", "trp_player", ":slot_id"),
                        (call_script, "script_lco_get_item_price", ":item_id", ":modifier", ":quantity"),
                        (assign, ":price", reg0),
#(assign, reg45, ":item_id"),(assign, reg46, ":modifier"),(assign, reg47, ":quantity"),(assign, reg48, ":price"),
#(assign, reg50, ":hero_offset"),(assign, reg51, ":slot_id"),
#(display_message, "@plr.inv[{reg51}] = ({reg45} mod {reg46} qty {reg47} val {reg48}), trp.inv[{reg50}] = ({reg41} mod {reg42} qty {reg43} val {reg44})", 0x00FF00),
                        # If price for loot item is greater than price for player item, we swap them.
                        # If it's equal or less, since both arrays are sorted, we quit the loop (subsequent loot items will be of same or lower price).
                        (gt, ":loot_price", ":price"),
#(display_message, "@SWAPPING"),
                        # Overwriting item in player's inventory
                        (troop_set_inventory_slot, "trp_player", ":slot_id", ":loot_item_id"),
                        (troop_set_inventory_slot_modifier, "trp_player", ":slot_id", ":loot_modifier"),
                        (try_begin),
                            (ge, ":loot_quantity", 1),
                            (troop_inventory_slot_set_item_amount, "trp_player", ":slot_id", ":loot_quantity"),
                        (try_end),
                        # Overwriting item in loot inventory
                        (troop_set_inventory_slot, "$g_lco_garbage_troop", ":hero_offset", ":item_id"),
                        (troop_set_inventory_slot_modifier, "$g_lco_garbage_troop", ":hero_offset", ":modifier"),
                        (try_begin),
                            (ge, ":quantity", 1),
                            (troop_inventory_slot_set_item_amount, "$g_lco_garbage_troop", ":hero_offset", ":quantity"),
                        (try_end),
                        (val_add, ":hero_offset", 1), # Proceed to next loot item
                        # Just in case, we are also checking for exceeding the loot troop inventory size
                        (lt, ":hero_offset", ":hero_capacity"),
                    (else_try),
                        (assign, ":capacity", 0), # Terminate cycle if no more loot items, or current loot item is cheaper than current player's item, or loot inventory exhausted
                    (try_end),
                (try_end),
            (try_end),
            (call_script, "script_lco_sort_player_inventory"),
            (call_script, "script_lco_count_discarded"),
        ]
    ),

    ("lco_count_discarded",
        [
            (troop_get_inventory_capacity, ":hero_capacity", "$g_lco_garbage_troop"),
            (store_free_inventory_capacity, ":free_capacity", "$g_lco_garbage_troop"),
            (troop_sort_inventory, "$g_lco_garbage_troop"),
            (store_sub, reg0, ":hero_capacity", ":free_capacity"),
            (val_sub, reg0, num_equipment_kinds),
            #(assign, reg0, 0),
            #(try_for_range, ":slot_id", num_equipment_kinds, ":hero_capacity"),
            #    (troop_get_inventory_slot, ":item_id", "$g_lco_garbage_troop", ":slot_id"),
            #    (ge, ":item_id", 0), # Slot is not empty
            #    (val_add, reg0, 1),
            #(try_end),
        ]
    ),

    # BugFix V1.20. Replacing hardcoded xp-to-level table with a call to standard game operation
    ("lco_xp_to_next_level",
        [
            (store_script_param_1, ":troop_id"),
            (store_character_level, ":level", ":troop_id"),
            (val_add, ":level", 1),
            (troop_get_xp, ":xp", ":troop_id"),
            (get_level_boundary, ":xp_needed", ":level"),
            (store_sub, reg40, ":xp_needed", ":xp"),
        ]
    ),

    ("lco_create_mesh",
        [
            (store_script_param, ":mesh", 1),
            (store_script_param, ":x", 2),
            (store_script_param, ":y", 3),
            (store_script_param, ":x_ratio", 4),
            (store_script_param, ":y_ratio", 5),
            (set_fixed_point_multiplier, 1000),
            (create_mesh_overlay, reg0, ":mesh"),
            (position_set_x, pos60, ":x"),
            (position_set_y, pos60, ":y"),
            (overlay_set_position, reg0, pos60),
            (position_set_x, pos61, ":x_ratio"),
            (position_set_y, pos61, ":y_ratio"),
            (overlay_set_size, reg0, pos61),
        ]
    ),

    ("lco_create_button",
        [
            (store_script_param, ":caption", 1),
            (store_script_param, ":x", 2),
            (store_script_param, ":y", 3),
            (store_script_param, ":x_size", 4),
            (store_script_param, ":y_size", 5),
            (set_fixed_point_multiplier, 1000),
            (create_game_button_overlay, reg0, ":caption"),
            (position_set_x, pos60, ":x"),
            (position_set_y, pos60, ":y"),
            (overlay_set_position, reg0, pos60),
            (position_set_x, pos61, ":x_size"),
            (position_set_y, pos61, ":y_size"),
            (overlay_set_size, reg0, pos61),
        ]
    ),

    ("lco_create_image_button",
        [
            (store_script_param, ":mesh", 1),
            (store_script_param, ":mesh_down", 2),
            (store_script_param, ":x", 3),
            (store_script_param, ":y", 4),
            (store_script_param, ":x_scale", 5),
            (store_script_param, ":y_scale", 6),
            (set_fixed_point_multiplier, 1000),
            (create_image_button_overlay, reg0, ":mesh", ":mesh_down"),
            (position_set_x, pos60, ":x"),
            (position_set_y, pos60, ":y"),
            (overlay_set_position, reg0, pos60),
            (position_set_x, pos61, ":x_scale"),
            (position_set_y, pos61, ":y_scale"),
            (overlay_set_size, reg0, pos61),
        ]
    ),

    ("lco_create_label",
        [
            (store_script_param, ":caption", 1),
            (store_script_param, ":x", 2),
            (store_script_param, ":y", 3),
            (store_script_param, ":scale", 4),
            (store_script_param, ":alignment", 5),
            (set_fixed_point_multiplier, 1000),
            (create_text_overlay, reg0, ":caption", ":alignment"),
            (position_set_x, pos60, ":x"),
            (position_set_y, pos60, ":y"),
            (overlay_set_position, reg0, pos60),
            (position_set_x, pos62, ":scale"),
            (position_set_y, pos62, ":scale"),
            (overlay_set_size, reg0, pos62),
        ]
    ),

    ("lco_create_checkbox",
        [
            (store_script_param, ":caption", 1),
            (store_script_param, ":x", 2),
            (store_script_param, ":y", 3),
            (store_script_param, ":value", 4),
            (set_fixed_point_multiplier, 1000),
            (create_check_box_overlay, reg0, "mesh_checkbox_off", "mesh_checkbox_on"),
            (overlay_set_val, reg0, ":value"),
            (position_set_x, pos60, ":x"),
            (position_set_y, pos60, ":y"),
            (overlay_set_position, reg0, pos60),
            (create_text_overlay, reg1, ":caption"),
            (val_add, ":x", 25),
            (position_set_x, pos60, ":x"),
            (overlay_set_position, reg1, pos60),
            (position_set_x, pos62, 750),
            (position_set_y, pos62, 750),
            (overlay_set_size, reg1, pos62),
        ]
    ),

    ("lco_create_container",
        [
            (store_script_param, ":x", 1),
            (store_script_param, ":y", 2),
            (store_script_param, ":width", 3),
            (store_script_param, ":height", 4),
            (store_script_param, ":auto_start", 5),
            (set_fixed_point_multiplier, 1000),
            (str_clear, s40),
            (create_text_overlay, reg0, s40, tf_scrollable),
            (position_set_x, pos60, ":x"),
            (position_set_y, pos60, ":y"),
            (overlay_set_position, reg0, pos60),
            (position_set_x, pos61, ":width"),
            (position_set_y, pos61, ":height"),
            (overlay_set_area_size, reg0, pos61),
            (try_begin),
                (neq, ":auto_start", 0),
                (set_container_overlay, reg0),
            (try_end),
        ]
    ),

    ("lco_freeze_slot_toggle",
        [
            (store_script_param_1, ":slot_id"),
            #(val_add, ":slot_id", lco_frozen_slots_start), # Removed as of V1.20
            (try_begin),
                (troop_slot_eq, lco_garbage, ":slot_id", 1),
                (troop_set_slot, lco_garbage, ":slot_id", 0),
                (assign, reg0, 0),
            (else_try),
                (troop_set_slot, lco_garbage, ":slot_id", 1),
                (assign, reg0, 1),
            (try_end),
        ]
    ),

    ("cf_lco_slot_is_frozen",
        [
            (store_script_param_1, ":slot_id"),
            #(val_add, ":slot_id", lco_frozen_slots_start), # Removed as of V1.20
            (troop_slot_eq, lco_garbage, ":slot_id", 1),
        ]
    ),

    ("lco_suppress_book_slots",
        [
            (store_script_param_1, "$g_lco_suppress_books"),
        ]
    ),

  # script_get_item_prerequisites:
  #  Use this script to identify item's prerequisites (what attribute/skill and at what level character must have to equip the item).
  #  It uses "trp_merchants_end" troop by default, but can use any other if necessary, for as long as it's tf_hero and NOT tf_inactive.
  #  Input:
  #   arg1 - item_id
  #   arg2 - item_modifier
  #  Output:
  #   reg0 - prerequisite type. 0 == No Prerequisite; 1 == Attribute Prereq, 2 == Skill Prereq
  #   reg1 - prerequisite id. Contains skill ID for skill prereq and attribute ID for attr prereqs (though it's always ca_strength and thus 0).
  #   reg2 - prerequisite value. Note that zero reg2 in combination with non-zero reg0/reg1 means the script FAILED to identify prerequisite value for whatever reason.
  ("get_item_prerequisites",
    [
      (store_script_param_1, ":item_id"),
      (item_get_type, ":item_type", ":item_id"),
      (store_script_param_2, ":item_modifier_id"),
      (assign, ":preq_type", 0),
      (assign, ":preq_atsk", 0),
      (assign, ":preq_value", 0),
      # Identify prerequisite type and relevant skill
      (assign, ":max_preq", 11), # We check for skill values of up to 10. Increase this if your mod has higher prerequisites.
      (try_begin),
        (this_or_next|eq, ":item_type", itp_type_one_handed_wpn),
        (this_or_next|eq, ":item_type", itp_type_two_handed_wpn),
        (this_or_next|eq, ":item_type", itp_type_polearm),
        (this_or_next|eq, ":item_type", itp_type_crossbow),
        (this_or_next|eq, ":item_type", itp_type_head_armor),
        (this_or_next|eq, ":item_type", itp_type_body_armor),
        (this_or_next|eq, ":item_type", itp_type_foot_armor),
        (eq, ":item_type", itp_type_hand_armor),
        (assign, ":preq_type", 1),
        (assign, ":max_preq", 21), # We check for STR values of up to 20. Increase this if your mod has higher prerequisites.
      (else_try),
        (eq, ":item_type", itp_type_horse),
        (assign, ":preq_type", 2),
        (assign, ":preq_atsk", "skl_riding"),
      (else_try),
        (eq, ":item_type", itp_type_shield),
        (assign, ":preq_type", 2),
        (assign, ":preq_atsk", "skl_shield"),
      (else_try),
        (eq, ":item_type", itp_type_bow),
        (assign, ":preq_type", 2),
        (assign, ":preq_atsk", "skl_power_draw"),
      (else_try),
        (eq, ":item_type", itp_type_thrown),
        (assign, ":preq_type", 2),
        (assign, ":preq_atsk", "skl_power_throw"),
      (try_end),
      # Identify prerequisite value
      (try_begin),
        (neq, ":preq_type", 0),
        # Cleanup temp troop inventory and attr/skill
        (troop_set_auto_equip, gip_dummy, 0),
        (troop_clear_inventory, gip_dummy),
        (try_for_range, ":slot_id", 0, num_equipment_kinds),
          (troop_set_inventory_slot, gip_dummy, ":slot_id", -1),
        (try_end),
        (try_begin),
          (eq, ":preq_type", 1),
          (store_attribute_level, ":previous", gip_dummy, ca_strength),
          (val_mul, ":previous", -1),
          (troop_raise_attribute, gip_dummy, ca_strength, ":previous"),
        (else_try),
          (store_skill_level, ":previous", ":preq_atsk", gip_dummy),
          (val_mul, ":previous", -1),
          (troop_raise_skill, gip_dummy, ":preq_atsk", ":previous"),
        (try_end),
        # Give a replica of our item to test troop
        (troop_set_inventory_slot, gip_dummy, num_equipment_kinds, ":item_id"),
        (troop_set_inventory_slot_modifier, gip_dummy, num_equipment_kinds, ":item_modifier_id"),
        # If we are checking a shield, we need to provide the troop with a zero-prerequisite one-handed weapon.
        (try_begin),
          (eq, ":item_type", itp_type_shield),
          (troop_set_inventory_slot, gip_dummy, ek_item_0, "itm_club"),
        (try_end),
        # Attempt to equip while zero attr/skill
        (troop_equip_items, gip_dummy),
        (try_begin),
          (troop_get_inventory_slot, ":now", gip_dummy, num_equipment_kinds),
          (eq, ":now", ":item_id"), # If the item is still there, the troop failed to equip it, so now we need to find the prerequisite
          # Now checking
          (try_for_range, ":value", 1, ":max_preq"),
            (eq, ":preq_value", 0), # We still haven't found a valid prerequisite
            # Increase prerequisite attr/skill by 1
            (try_begin),
              (eq, ":preq_type", 1), # STR check?
              (troop_raise_attribute, gip_dummy, ca_strength, 1),
            (else_try),
              (troop_raise_skill, gip_dummy, ":preq_atsk", 1),
            (try_end),
            # Attempt to equip the item
            (troop_equip_items, gip_dummy),
            (try_begin),
              (troop_get_inventory_slot, ":now", gip_dummy, num_equipment_kinds),
              (eq, ":now", -1), # If no item is there, then troop must have equipped the item.
              (assign, ":preq_value", ":value"), # We found the prerequisite value! Store it.
              #(assign, ":value", ":max_preq"), # Try to break the cycle (not sure if it works, but won't hurt anyway).
            (try_end),
          (try_end),
        (else_try),
          # We have successfully equipped the item with zero attr/skill. So it doesn't have any prereqs after all.
          (assign, ":preq_type", 0),
          (assign, ":preq_atsk", 0),
        (try_end),
        # Cleanup temp troop inventory after we finished processing
        (troop_clear_inventory, gip_dummy),
        (try_for_range, ":slot_id", 0, num_equipment_kinds),
          (troop_set_inventory_slot, gip_dummy, ":slot_id", -1),
        (try_end),
      (try_end),
      # Return results
      (assign, reg0, ":preq_type"),
      (assign, reg1, ":preq_atsk"),
      (assign, reg2, ":preq_value"),
    ]
  ), 

####################################################################################################################################
# LAV MODIFICATIONS END (COMPANIONS OVERSEER MOD)
####################################################################################################################################

################################################################################
# FISH&CHIP MODIFICATIONS START
################################################################################

    # Shared script for all FISH&CHIP heraldic items
    ("setup_heraldry",
        [
            (store_script_param, ":heraldic_mesh", 1),
            (store_script_param, ":banner_mesh", 2),
            (store_script_param, ":offset_x", 3),
            (store_script_param, ":offset_y", 4),
            (store_script_param, ":scale_factor", 5),
            (set_fixed_point_multiplier, 100),
            (store_sub, ":background_slot", ":banner_mesh", arms_meshes_begin),
            (troop_get_slot, ":background_color", "trp_banner_background_color_array", ":background_slot"),
            (cur_tableau_set_background_color, ":background_color"),
            (init_position, pos1),
            (position_set_x, pos1, ":offset_x"),
            (position_set_y, pos1, ":offset_y"),
            (position_set_z, pos1, 30),
            (cur_tableau_add_mesh, ":banner_mesh", pos1, ":scale_factor", 0),
            (init_position, pos1),
            (position_set_z, pos1, 60),
            (cur_tableau_add_mesh, ":heraldic_mesh", pos1, 0, 0),
            (cur_tableau_set_camera_parameters, 0, 200, 200, 0, 100000),
        ]
    ),

    # Shared script for all FISH&CHIP camo items
    ("setup_camouflage",
        [
            (store_script_param, ":tableau_mesh", 1),
            (store_script_param, ":instance_id", 2),
            (set_fixed_point_multiplier, 100),
            (init_position, pos1),
            (try_begin),
                (gt, ":instance_id", 0),
                (cur_tableau_add_mesh, ":instance_id", pos1, 0, 0),
            (else_try),
                (store_sub, ":instance_id", 0, ":instance_id"),
                (val_or, ":instance_id", 0xFF000000),
                (cur_tableau_set_background_color, ":instance_id"),
            (try_end),
            (position_set_z, pos1, 30),
            (cur_tableau_add_mesh, ":tableau_mesh", pos1, 0, 0),
            (cur_tableau_set_camera_parameters, 0, 200, 200, 0, 100000),
        ]
    ),

################################################################################
# FISH&CHIP MODIFICATIONS END
################################################################################

# 0.608b5 new stuff

  # Troop trees presentation


("prsnt_culture_troop_tree",
 [(store_script_param_1, ":culture"),
  (store_sub, ":num", ":culture", fac_culture_1), (val_mod, ":num", 6),
  (store_add, ":slot",  ":num","mesh_pic_arms_swadian"),
  (create_mesh_overlay, reg0, ":slot"),
  (overlay_set_alpha, reg0, 0x7F),
  (store_add, ":slot", ":num", "mesh_pic2_swa"),
  (create_mesh_overlay, reg1, ":slot"),
  (overlay_set_alpha, reg1, 0x7F),
  (position_set_x, pos1, 180),(position_set_y, pos1, 560),
  (position_set_x, pos2, 500),(position_set_y, pos2, 25),      
  (position_set_x, pos3, 500),(position_set_y, pos3, 500),
  (overlay_set_position, reg0, pos1), (overlay_set_size, reg0, pos3),      
  (overlay_set_position, reg1, pos2), (overlay_set_size, reg1, pos3),       
  (try_for_range, ":slot", 0, 61),
     (troop_set_slot, "trp_temp_array_a", ":slot", 0),
     (troop_set_slot, "trp_temp_array_b", ":slot", 0),
     (troop_set_slot, "trp_temp_array_c", ":slot", 0),
     (store_add, ":num", ":slot", 100), #Caba - was missing ":slot"
     (troop_set_slot, "trp_temp_array_b", ":num", -1),
     (troop_set_slot, "trp_temp_array_c", ":num", -1),
  (try_end),
  #try-else block here to get 'troop-no' (or above) for non-kingdom trees
  (faction_get_slot, ":troop_no", ":culture", slot_faction_tier_1_troop),
  # lowest troop tiers initialization BEGIN 
  (troop_set_slot, "trp_temp_array_a", 0, 1),           # Number of Lowest Tier Troop
  (troop_set_slot, "trp_temp_array_a", 1, 1),           # 1 for 1st troop
  (troop_set_slot, "trp_temp_array_b", 1, ":troop_no"), # 1st troop id
  # lowest troop tiers initialization END 
  (assign, ":max_tier", 0), (assign, ":no_tier", 0),
  ## Calculates number of tiers--":max_tiers" and number of branches (more or less)
  (try_for_range, ":tier", 1, 10),                      # Asuming that you wont make troop tree more than 10 tiers
     (eq, ":no_tier", 0),
     (assign, ":no_tier", 1),
     (store_sub, ":prev_tier", ":tier", 1),
     (store_mul, ":slot_for_prev_num", ":prev_tier", 10),
     (store_mul, ":slot_for_num", ":tier", 10),
     (assign, ":num", 0),
     (troop_get_slot, ":prev_num", "trp_temp_array_a", ":slot_for_prev_num"),
     (gt, ":prev_num", 0),
     (val_add, ":prev_num", 1),
     (try_for_range, ":tree_no",  1,  ":prev_num"),     
        (store_add, ":prev_slot", ":tree_no", ":slot_for_prev_num"),
        (troop_get_slot, ":troop_no", "trp_temp_array_b", ":prev_slot"),
        (gt, ":troop_no", 0),
        #Caba - check for duplication
        (assign, ":end", ":tree_no"),
        (try_for_range, ":i", 1, ":end"), #check troops of this prev_tier previously looped over, be sure this troop hasn't been checked
            (store_add, ":other_prev_slot", ":i", ":slot_for_prev_num"),
            (neq, ":prev_slot", ":other_prev_slot"), #just to be sure
            (troop_slot_eq, "trp_temp_array_b", ":other_prev_slot", ":troop_no"),
            (assign, ":end", 0), #break loop, found in checked list
        (try_end),
        (neq, ":end", 0),
        #Caba - end
        (troop_get_upgrade_troop, ":next_troop", ":troop_no", 0),
        (gt, ":next_troop", 0),
        (assign, ":no_tier", 0), 
        (val_add, ":num", 1),
        (troop_set_slot, "trp_temp_array_a", ":slot_for_num", ":num"),
        (store_add, ":slot", ":slot_for_num", ":num"),
        (troop_set_slot, "trp_temp_array_a", ":slot", ":tree_no"),
        (troop_set_slot, "trp_temp_array_b", ":slot", ":next_troop"),
        (troop_get_upgrade_troop, ":next_troop", ":troop_no", 1),
        (gt, ":next_troop", 0),
        (val_add, ":num", 1),
        (troop_set_slot, "trp_temp_array_a", ":slot_for_num", ":num"),
        (store_add, ":slot", ":slot_for_num", ":num"),
        (troop_set_slot, "trp_temp_array_a", ":slot", ":tree_no"),
        (troop_set_slot, "trp_temp_array_b", ":slot", ":next_troop"),
     (try_end),
     (eq, ":no_tier", 0),
     (val_add, ":max_tier", 1),
  (try_end),
  (store_mul, ":max_num_tier", ":max_tier", 10), (val_add, ":max_tier", 1),
  (troop_get_slot, ":num", "trp_temp_array_a", ":max_num_tier"),
  (val_add, ":num", 1),
  #Calculate Y Position of last tier's branches? ???
  (try_for_range, ":tree_no", 1, ":num"),
     (store_add, ":slot", ":max_num_tier", ":tree_no"),
     (store_mul, ":subs", ":tree_no", troop_tree_space_y),
     (store_sub, ":pos", working_pos_y + 35, ":subs"),
     (troop_set_slot, "trp_temp_array_c", ":slot", ":pos"),
  (try_end),
  #Calculate Troop Y positions
  (try_for_range_backwards, ":tier", 1, ":max_tier"),
     (store_mul, ":slot_for_num", ":tier", 10),
     (store_sub, ":prev_tier", ":tier", 1),
     (store_mul, ":slot_for_prev_num", ":prev_tier", 10),
     (troop_get_slot, ":prev_num", "trp_temp_array_a", ":slot_for_prev_num"),
     (gt, ":prev_num", 0),
     (val_add, ":prev_num", 1),
     (try_for_range, ":tree_no", 1, ":prev_num"),
        (store_add, ":prev_slot", ":tree_no", ":slot_for_prev_num"),
        (assign, ":prev_pos", 0), (assign, ":num", 0),
        (try_for_range, ":subs", 1, 10),
           (store_add, ":slot", ":subs", ":slot_for_num"),
           (troop_slot_eq, "trp_temp_array_a", ":slot", ":tree_no"),
           #Caba - check for duplication - loop over past troops rather than using a troop slot (change?)
           (troop_get_slot, ":troop_no", "trp_temp_array_b", ":slot"),
           (assign, ":end", ":slot"),
           (try_for_range, ":i", 0, ":end"), #check troops of this prev_tier previously looped over, be sure this troop hasn't been checked
                (neq, ":i", ":slot"), #just to be sure
                (troop_slot_eq, "trp_temp_array_b", ":i", ":troop_no"),
                (assign, ":end", 0), #break loop, found in checked list
           (try_end),
           (neq, ":end", 0),
           #Caba - end
           (troop_get_slot, ":pos", "trp_temp_array_c", ":slot"),           
           (val_add, ":prev_pos", ":pos"),
           (val_add, ":num", 1),
        (try_end),
        (gt, ":num", 0),
        (val_div, ":prev_pos", ":num"),
        (troop_set_slot, "trp_temp_array_c", ":prev_slot", ":prev_pos"),
     (try_end),
     (assign, ":pos", 999),
     (try_for_range, ":tree_no", 1, ":prev_num"), 
        (store_add, ":prev_slot", ":tree_no", ":slot_for_prev_num"),
        (troop_get_slot, ":prev_pos", "trp_temp_array_c", ":prev_slot"),           
        (gt, ":prev_pos", 0),
        (lt, ":prev_pos", ":pos"),
        (assign, ":pos", ":prev_pos"),
     (try_end),        
     (try_for_range, ":tree_no", 1, ":prev_num"), 
        (store_add, ":prev_slot", ":tree_no", ":slot_for_prev_num"),
        (troop_get_slot, ":prev_pos", "trp_temp_array_c", ":prev_slot"),           
        (eq, ":prev_pos", 0),
        (store_sub, ":prev_pos", ":pos", troop_tree_space_y),
        (assign, ":pos", ":prev_pos"),
        (troop_set_slot, "trp_temp_array_c", ":prev_slot", ":prev_pos"),     
     (try_end),
  (try_end),
  (val_add, ":max_num_tier", 11), (troop_set_slot, "trp_temp_array_c", 100, 0), (assign, ":num",100),
  #Draw Troops, Titles - Calcuate X and position of Connecting Lines
  (try_for_range, ":slot", 0,  ":max_num_tier"),
     (troop_get_slot, ":troop_no", "trp_temp_array_b", ":slot"),
     (gt, ":troop_no", 0),
     #Caba - check for duplication - loop over past troops rather than using a troop slot (change?)
     (assign, ":end", ":slot"),
     (try_for_range, ":i", 0, ":end"), #check troops of this prev_tier previously looped over, be sure this troop hasn't been checked
        (neq, ":i", ":slot"), #just to be sure
        (troop_slot_eq, "trp_temp_array_b", ":i", ":troop_no"),
        (assign, ":end", 0), #break loop, found in checked list
     (try_end),
     (neq, ":end", 0),
     #Caba - end
     (store_div, ":posx", ":slot", 10),
     (val_mul, ":posx", troop_tree_space_x),
     (val_add, ":posx", troop_tree_left),
     (troop_get_slot, ":posy", "trp_temp_array_c", ":slot"),
     (val_add, ":num", 1),
     (call_script, "script_prsnt_upgrade_tree_troop_and_name", ":troop_no", ":posx", ":posy"),
     (troop_set_slot, "trp_temp_array_c", ":num", reg1),
     (troop_set_slot, "trp_temp_array_b", ":num", ":troop_no"),
     (store_mod, ":cur_slot",  ":slot", 10),
     (gt, ":cur_slot", 0),
     ## Draw lines to next troops, if found
     (store_sub, ":cur_slot1", ":slot", ":cur_slot"),
     (val_add,   ":cur_slot1", 10),     
     (store_add, ":cur_slot2", ":cur_slot1", 10),
     (try_for_range, ":slot2", ":cur_slot1", ":cur_slot2"), 
        (troop_slot_ge, "trp_temp_array_b", ":slot2", 1), 
        (troop_slot_eq, "trp_temp_array_a", ":slot2", ":cur_slot"),
        #Caba - check for duplication - loop over past troops rather than using a troop slot (change?)
        (troop_get_slot, ":troop_no", "trp_temp_array_b", ":slot2"),
        (assign, ":end", ":slot2"),
        (try_for_range, ":i", ":cur_slot1", ":end"), #check troops of this prev_tier previously looped over, be sure this troop hasn't been checked
            (neq, ":i", ":cur_slot1"), #just to be sure            
            (troop_slot_eq,  "trp_temp_array_b", ":i", ":troop_no"),
            (assign, ":posy_to_use", ":i"),
            (assign, ":end", 0), #break loop, found in checked list
        (try_end),
        (try_begin),
            (neq, ":end", 0),
            (assign, ":posy_to_use", ":slot2"),
        (try_end),
        #Caba - end
        (store_add, ":posx2", ":posx", troop_tree_space_x),
        (store_add, ":posx1", ":posx", troop_tree_space_x/2),
        (troop_get_slot, ":posy2", "trp_temp_array_c", ":posy_to_use"), #caba ":slot2"),
        (store_add, ":posy1", ":posy", troop_tree_space_y/2),
        (val_add, ":posy2", troop_tree_space_y/2),
        #Caba
        (try_begin),
            (neq, ":end", 0),
        #Caba - end
            (call_script, "script_prsnt_lines_to", ":posx", ":posy1", ":posx2", ":posy2", title_black),
            (val_sub, ":posy2", 3),
            (call_script, "script_prsnt_upgrade_tree_troop_cost", ":troop_no", ":posx1", ":posy2"),
        #Caba  
        (else_try),
            (val_sub, ":posy2", 20),
            (store_sub, ":posx3", ":posx2", 20),
            (call_script, "script_prsnt_lines_to", ":posx", ":posy1", ":posx3", ":posy2", title_black),
            (call_script, "script_prsnt_lines_to", ":posx3", ":posy2", ":posx2", ":posy2", title_black),
        (try_end),
        #Caba - end
     (try_end),     
  (try_end),
  (troop_set_slot, "trp_temp_array_c", 100, ":num"),  ]),
 
("prsnt_lines_to", # Drawing lines from (x1,y1) to (x2,y2), the line will be horizontal til half way, vertical and then horizontal again
 [(store_script_param, ":pos_x1", 1),
  (store_script_param, ":pos_y1", 2),
  (store_script_param, ":pos_x2", 3),
  (store_script_param, ":pos_y2", 4),
  (store_script_param, ":color", 5),
  (try_begin),
     (eq, ":pos_x1", ":pos_x2"),
     (store_sub, ":size", ":pos_y1", ":pos_y2"),
     (val_abs, ":size"),
     (val_min, ":pos_y1", ":pos_y2"),
     (call_script, "script_prsnt_lines", 4, ":size", ":pos_x1", ":pos_y1", ":color"),
  (else_try),
     (eq, ":pos_y1", ":pos_y2"),
     (store_sub, ":size", ":pos_x1", ":pos_x2"),
     (val_abs, ":size"),
     (val_min, ":pos_x1", ":pos_x2"),
     (call_script, "script_prsnt_lines", ":size", 5, ":pos_x1", ":pos_y1", ":color"),
  (else_try),
     (store_add, ":pos_x", ":pos_x1", ":pos_x2"), (val_div, ":pos_x", 2), (val_sub, ":pos_x", 6),
     (call_script, "script_prsnt_lines_to", ":pos_x1", ":pos_y1", ":pos_x",  ":pos_y1", ":color"),
     (call_script, "script_prsnt_lines_to", ":pos_x",  ":pos_y1", ":pos_x",  ":pos_y2", ":color"),
     (call_script, "script_prsnt_lines_to", ":pos_x",  ":pos_y2", ":pos_x2", ":pos_y2", ":color"),
  (try_end), ]),
  
# rubik's CC scripts BEGIN  
("prsnt_upgrade_tree_troop_and_name",
 [(store_script_param, ":troop_no", 1),
  (store_script_param, ":pos_x", 2),
  (store_script_param, ":pos_y", 3),

  (str_store_troop_name, s1, ":troop_no"),

  (val_add, ":pos_x", 1),(val_sub, ":pos_y", 1),
  (create_text_overlay, reg1, "@{s1}", tf_center_justify|tf_vertical_align_center),
  (position_set_x, pos1, smaller_size),
  (position_set_y, pos1, smaller_size),
  (overlay_set_size, reg1, pos1),
  (position_set_x, pos1, ":pos_x"),
  (position_set_y, pos1, ":pos_y"),
  (overlay_set_position, reg1, pos1),
  (overlay_set_color, reg1, 0xFFFFFF),

  (val_sub, ":pos_x", 1),(val_add, ":pos_y", 1),
  (create_text_overlay, reg1, "@{s1}", tf_center_justify|tf_vertical_align_center),
  (position_set_x, pos1, smaller_size),
  (position_set_y, pos1, smaller_size),
  (overlay_set_size, reg1, pos1),
  (position_set_x, pos1, ":pos_x"),
  (position_set_y, pos1, ":pos_y"),
  (overlay_set_position, reg1, pos1),
  (overlay_set_color, reg1, 0x000000),

  (val_sub, ":pos_x", 52), # adjusted from 65
  #(val_add, ":pos_y", 5), # adjusted from 10
  (store_mul, ":cur_troop", ":troop_no", 2), #with weapons
  (create_image_button_overlay_with_tableau_material, reg1, -1, "tableau_game_party_window", ":cur_troop"),
  (position_set_x, pos1, troop_tree_size_x),
  (position_set_y, pos1, troop_tree_size_y),
  (overlay_set_size, reg1, pos1),
  (position_set_x, pos1, ":pos_x"),
  (position_set_y, pos1, ":pos_y"),
  (overlay_set_position, reg1, pos1), ]),
  
("prsnt_upgrade_tree_troop_cost",
 [(store_script_param, ":troop_no", 1),
  (store_script_param, ":pos_x", 2),
  (store_script_param, ":pos_y", 3),
  (call_script, "script_game_get_upgrade_cost", ":troop_no"),
  (create_text_overlay, reg1, "@{reg0}", tf_left_align|tf_vertical_align_center),
  (position_set_x, pos1, ":pos_x"),
  (position_set_y, pos1, ":pos_y"),
  (overlay_set_position, reg1, pos1),
  (position_set_x, pos1, smaller_size),
  (position_set_y, pos1, smaller_size),
  (overlay_set_size, reg1, pos1), ]),
  
("prsnt_lines",
 [(store_script_param, ":size_x", 1),
  (store_script_param, ":size_y", 2),
  (store_script_param, ":pos_x", 3),
  (store_script_param, ":pos_y", 4),
  (store_script_param, ":color", 5),
  (create_mesh_overlay, reg1, "mesh_white_plane"),
  (val_mul, ":size_x", 50),
  (val_mul, ":size_y", 50),
  (position_set_x, pos0, ":size_x"),
  (position_set_y, pos0, ":size_y"),
  (overlay_set_size, reg1, pos0),
  (position_set_x, pos0, ":pos_x"),
  (position_set_y, pos0, ":pos_y"),
  (overlay_set_position, reg1, pos0),
  (overlay_set_color, reg1, ":color"), ]),

("get_troop_max_hp",
 [(store_script_param_1, ":troop"),
  (store_skill_level, ":skill", skl_ironflesh, ":troop"),
  (store_attribute_level, ":attrib", ":troop", ca_strength),
  (val_mul, ":skill", 2),
  (val_add, ":skill", ":attrib"),
  (val_add, ":skill", 35),
  (assign, reg0, ":skill"), ]),

("copy_inventory", 
 [(store_script_param_1, ":source"),
  (store_script_param_2, ":target"),
  (troop_clear_inventory, ":target"),
  (troop_get_inventory_capacity, ":inv_cap", ":source"),
  (try_for_range, ":i_slot", 0, ":inv_cap"),
    (troop_get_inventory_slot, ":item", ":source", ":i_slot"),
    (troop_set_inventory_slot, ":target", ":i_slot", ":item"),
    (troop_get_inventory_slot_modifier, ":imod", ":source", ":i_slot"),
    (troop_set_inventory_slot_modifier, ":target", ":i_slot", ":imod"),
    (troop_inventory_slot_get_item_amount, ":amount", ":source", ":i_slot"),
    (gt, ":amount", 0),
    (troop_inventory_slot_set_item_amount, ":target", ":i_slot", ":amount"),
  (try_end), ]),
# rubik's CC scripts END    

# 0.608b6 new stuff

    ("relation_text_to_s3", [
      (store_script_param_1, ":cur_relation"),
      (try_begin),
        (ge, ":cur_relation", 90),
        (str_store_string, s3, "@loyal to"),
      (else_try),
        (ge, ":cur_relation", 80),
        (str_store_string, s3, "@devoted to"),
      (else_try),
        (ge, ":cur_relation", 70),
        (str_store_string, s3, "@fond of"),
      (else_try),
        (ge, ":cur_relation", 60),
        (str_store_string, s3, "@gracious to"),
      (else_try),
        (ge, ":cur_relation", 50),
        (str_store_string, s3, "@friendly to"),
      (else_try),
        (ge, ":cur_relation", 40),
        (str_store_string, s3, "@supportive of"),
      (else_try),
        (ge, ":cur_relation", 30),
        (str_store_string, s3, "@favorable to"),
      (else_try),
        (ge, ":cur_relation", 20),
        (str_store_string, s3, "@cooperative with"),
      (else_try),
        (ge, ":cur_relation", 10),
        (str_store_string, s3, "@accepting of"),
      (else_try),
        (ge, ":cur_relation", 0),
        (str_store_string, s3, "@indifferent to"),
      (else_try),
        (ge, ":cur_relation", -10),
        (str_store_string, s3, "@suspicious of"),
      (else_try),
        (ge, ":cur_relation", -20),
        (str_store_string, s3, "@grumbling about"),
      (else_try),
        (ge, ":cur_relation", -30),
        (str_store_string, s3, "@hostile to"),
      (else_try),
        (ge, ":cur_relation", -40),
        (str_store_string, s3, "@resentful of"),
      (else_try),
        (ge, ":cur_relation", -50),
        (str_store_string, s3, "@angry at"),
      (else_try),
        (ge, ":cur_relation", -60),
        (str_store_string, s3, "@hateful of"),
      (else_try),
        (ge, ":cur_relation", -70),
        (str_store_string, s3, "@revengeful of"),
      (else_try),
        (str_store_string, s3, "@vengeful of"),
      (try_end),
    ]),

    # Prefix in {s2}
    ("fief_report_village_to_s1", [
      (store_script_param, ":village", 1),
      (store_script_param, ":describe_town", 2),
      (str_store_party_name_link, s2, ":village"),
      (party_get_slot, reg50, ":village", slot_center_player_relation),
      (call_script, "script_relation_text_to_s3", reg50),
      (str_clear, s4),
      (try_begin),
        (gt, reg50, 0),
        (str_store_string, s4, "@+"),
      (try_end),
      (party_get_slot, ":state", ":village", slot_village_state),
      (party_get_slot, reg51, ":village", slot_village_infested_by_bandits),
      (party_get_slot, reg52, ":village", slot_town_prosperity),
      (party_get_slot, ":product", ":village", slot_town_village_product),
      (party_get_slot, ":volunteer", ":village", slot_center_npc_volunteer_troop_type),
      (party_get_slot, reg53, ":village", slot_center_npc_volunteer_troop_amount),
      (party_get_slot, ":center", ":village", slot_village_bound_center),
      (party_get_slot, ":building", ":village", slot_center_current_improvement),
      (party_get_slot, ":building_end", ":village", slot_center_improvement_end_hour),
    ]),


    ("describe_hero_wounds_to_s9", [
        (str_clear, s9),
        (store_script_param, ":hero", 1),
        (try_begin),
            (eq, ":hero", "trp_player"),
            (str_store_string, s60, "@your"),
        (else_try),
            (str_store_troop_name, s60, ":hero"),
            (str_store_string, s60, "@{s60}'s"),
        (try_end),
        (store_current_hours, ":cur_hours"),
        (try_begin),
          (troop_get_slot, ":wound", ":hero", slot_troop_wound_str),
          (gt, ":wound", 0),
          (val_sub,":wound",":cur_hours"),
          (val_div,":wound",24),
          (assign,reg4,":wound"),
          (str_store_string,s9,"@{s9}^   The wound affecting {s60} strength will be healed in {reg4} days."),
        (try_end),
        (try_begin),
          (troop_get_slot, ":wound", ":hero", slot_troop_wound_agi),
          (gt, ":wound", 0),
          (val_sub,":wound",":cur_hours"),
          (val_div,":wound",24),
          (assign,reg4,":wound"),
          (str_store_string,s9,"@{s9}^   The wound affecting {s60} agility will be healed in {reg4} days."),
        (try_end),
        (try_begin),
          (troop_get_slot, ":wound", ":hero", slot_troop_wound_cha),
          (gt, ":wound", 0),
          (val_sub,":wound",":cur_hours"),
          (val_div,":wound",24),
          (assign,reg4,":wound"),
          (str_store_string,s9,"@{s9}^   The wound affecting {s60} charisma will be healed in {reg4} days."),
        (try_end),
        (try_begin),
          (troop_get_slot, ":wound", ":hero", slot_troop_wound_int),
          (gt, ":wound", 0),
          (val_sub,":wound",":cur_hours"),
          (val_div,":wound",24),
          (assign,reg4,":wound"),
          (str_store_string,s9,"@{s9}^   The wound affecting {s60} intelligence will be healed in {reg4} days."),
        (try_end),	
    ]),

    # Set party icon for NPC kingdoms as dictated by faction
    ("set_icon_for_lord_party", [
      (store_script_param, ":troop_no", 1),
      (store_troop_faction, ":troop_faction_no", ":troop_no"),
      (troop_get_slot, ":party_no", ":troop_no", slot_troop_leaded_party),
      (try_begin),
        (party_is_active, ":party_no"),
        (is_between, ":troop_faction_no", npc_kingdoms_begin, "fac_dark_knights"),
        (store_sub, ":icon", ":troop_faction_no", npc_kingdoms_begin),
        (val_mul, ":icon", 3),
        (val_add, ":icon", "icon_swadia_king"),
        (try_begin),
          (faction_slot_eq, ":troop_faction_no", slot_faction_marshall, ":troop_no"),
          (val_add, ":icon", 1),
        (else_try),
          (neg|faction_slot_eq, ":troop_faction_no", slot_faction_leader, ":troop_no"),
          (val_add, ":icon", 2),
        (try_end),
        (party_set_icon, ":party_no", ":icon"),
      (try_end),
    ]),
]
