#textdomain wesnoth-ei
#
# NOTE: This level is intended as a challenging final scenario.
#       Players without sufficient high-level troops to recall
#       are advised to select "The Duel" instead.
#
#   I would prefer keeping this scenario as difficult as possible, so that players feel like they have a goal to reach for
#
[scenario]
    id=17b_All-In
    name= _ "All-In"
    map_file=17b_All-In.map
    turns=unlimited
    victory_when_enemies_defeated=no
    next_scenario=18_Epilogue
    {DISABLE_GRAND_MARSHAL}

    {DEFAULT_SCHEDULE_MORNING}

    {INTRO_AND_SCENARIO_MUSIC weight_of_revenge.ogg cry_from_elensefar.ogg}
    {EXTRA_SCENARIO_MUSIC battle-epic.ogg}
    {EXTRA_SCENARIO_MUSIC heavens-remix.ogg}
    {EXTRA_SCENARIO_MUSIC the_city_falls.ogg}

    [story]
        [part]
            #po: the river has the same name as the city
            story= _ "The morning sun shone bright upon the valley of the Weldyn, glinting off swords and lances innumerable, arrayed in tight formation inside the city walls."
            music=silence.ogg
        [/part]
        [part]
            story= _ "From the ranks of Wesnoth’s finest arose a cry, soft at first but then mounting in volume, a cry of desperate hope, a cry of fiery purpose and icy will."
            music=silence.ogg
        [/part]
        [part]
            sound=horn-signals/horn-2.ogg
            story= _ "The horns sounded, the gates swung open, and from inside the city spilled forth Weldyn’s last gasp."
            music=silence.ogg
        [/part]
    [/story]

    {EI_TRACK {JOURNEY_17_NEW} }

    [side]
        id=Konrad
        type=King of Wesnoth
        save_id=Gweddry
        side=1
        {GOLD 200 175 150} # in addition, each general saved also gives a large amount of gold
        canrecruit=yes
        controller=human
        team_name=wesnothians
        user_team_name=_"Wesnothians"
        {FLAG_VARIANT loyalist}
    [/side]

#define INVADER_AI_STUFF
    color=teal
    controller=ai
    canrecruit=yes
    team_name=undead
    user_team_name=_"Undead"
    {GOLD 75 120 170} # reduced difficulty scaling, since liches won't attack properly if gold is too low. This is also supposed to be a very difficult, optional level
    {INCOME -2 0 2} # the longer you wait, the stronger the enemies get. Liches can never lose gold
    village_gold=0  # strictly limited income, since gold is recycled
    {FLAG_VARIANT undead}
#enddef
#define CHANGE_RECRUITS_IF_RICH SIDE OLDTYPES NEWTYPES
    # if we're building a gold reserve (because our keep is too small), force the AI to use expensive high-level recruits
    [store_gold]
        side={SIDE}
    [/store_gold]
    [if]
        {VARIABLE_CONDITIONAL turn_number greater_than 10}
        {VARIABLE_CONDITIONAL gold greater_than 300}
        [then]
            [set_recruit]
                side={SIDE}
                recruit={NEWTYPES}
            [/set_recruit]
        [/then]
        [else]
            [set_recruit]
                side={SIDE}
                recruit={OLDTYPES}
            [/set_recruit]
        [/else]
    [/if]
    {CLEAR_VARIABLE gold}
#enddef
    {REANIMATION_IMPLEMENTATION}
    {GHOSTPLAGUE_IMPLEMENTATION}

    [side]
        type=Lich
        id=Lich2
        name= _ "?"
        side=2
        facing=sw
        [variables]
            random_lich=yes
        [/variables]
        recruit=Skeleton Archer,Skeleton,Revenant,Deathblade,Dark Adept
        {INVADER_AI_STUFF}
        {LOYAL_UNIT 2 (Draug) 57 8} {GUARDIAN}
        {LOYAL_UNIT 2 (Deathblade) 55 6} {GUARDIAN}
    [/side]
    {SILENTLY_LIMIT_LEADER_MOVES 2 2}

    [side]
        type=Lich
        id=Lich3
        name= _ "?"
        side=3
        facing=sw
        [variables]
            random_lich=yes
        [/variables]
        recruit=Dark Sorcerer,Walking Corpse,Soulless,Ghoul,Necrophage,Dark Adept
        {INVADER_AI_STUFF}
        {LOYAL_UNIT 3 (Ghast)      53 21} {GUARDIAN}
        {LOYAL_UNIT 3 (Soulless)   54 18} {GUARDIAN} {VARIATION wose}
        {LOYAL_UNIT 3 (Dark Adept) 54 22} {GUARDIAN}
    [/side]
    {RECRUIT_UNIT_VARIATIONS 3 "Walking Corpse" spider,spider,drake,wose}
    {RECRUIT_UNIT_VARIATIONS 3 "Soulless"       spider,spider,drake,wose}
    {SILENTLY_LIMIT_LEADER_MOVES 3 1}

    [side]
        type=Lich
        id=Lich4
        name= _ "?"
        side=4
        canrecruit=yes
        facing=nw
        [variables]
            random_lich=yes
        [/variables]
        recruit=Vampire Bat,Blood Bat,Skeleton Rider,Bone Knight,Chocobone,Dark Adept
        {INVADER_AI_STUFF}
        {LOYAL_UNIT 4 (Chocobone)      44 28} {GUARDIAN}
        {LOYAL_UNIT 4 (Bone Knight)    52 37} {GUARDIAN}
        {LOYAL_UNIT 4 (Skeleton Rider) 56 37} {GUARDIAN}
    [/side]
    {SILENTLY_LIMIT_LEADER_MOVES 4 1}

    [side]
        type=Lich
        id=Lich5
        name= _ "?"
        side=5
        canrecruit=yes
        facing=nw
        [variables]
            random_lich=yes
        [/variables]
        recruit=Vampire Bat,Blood Bat,Ghost,Shadow,Wraith,Dark Adept
        {INVADER_AI_STUFF}
        {LOYAL_UNIT 5 (Spectre)    34 36} {GUARDIAN}
        {LOYAL_UNIT 5 (Shadow)     33 40} {GUARDIAN}
        {LOYAL_UNIT 5 (Dark Adept) 30 38} {GUARDIAN}
    [/side]
    {SILENTLY_LIMIT_LEADER_MOVES 5 2}

    [side]
        type=Lich
        id=Lich6
        name= _ "?"
        side=6
        canrecruit=yes
        facing=ne
        [variables]
            random_lich=yes
        [/variables]
        recruit=Dark Sorcerer,Walking Corpse,Soulless,Ghoul,Necrophage,Dark Adept
        {INVADER_AI_STUFF}
        {LOYAL_UNIT 6 (Soulless)    7 33} {GUARDIAN} {VARIATION mounted}
        {LOYAL_UNIT 6 (Necrophage)  9 34} {GUARDIAN}
        {LOYAL_UNIT 6 (Dark Adept) 12 30} {GUARDIAN}
    [/side]
    {RECRUIT_UNIT_VARIATIONS 6 "Walking Corpse" none,mounted,mounted,horse}
    {RECRUIT_UNIT_VARIATIONS 6 "Soulless"       none,mounted,mounted,horse}
    {SILENTLY_LIMIT_LEADER_MOVES 6 2}

    [side]
        type=Lich
        id=Lich7
        name= _ "?"
        side=7
        canrecruit=yes
        facing=se
        [variables]
            random_lich=yes
        [/variables]
        recruit=Skeleton,Skeleton Archer,Bone Shooter,Dark Adept
        {INVADER_AI_STUFF}
        {LOYAL_UNIT 7 (Banebow)      4 8} {GUARDIAN}
        {LOYAL_UNIT 7 (Bone Shooter) 7 7} {GUARDIAN}
    [/side]
    {SILENTLY_LIMIT_LEADER_MOVES 7 2}

    [side]
        type=Lich
        id=Lich8
        name= _ "?"
        side=8
        canrecruit=yes
        facing=se
        [variables]
            random_lich=yes
        [/variables]
        recruit=Dark Sorcerer,Walking Corpse,Soulless,Ghoul,Necrophage,Dark Adept
        {INVADER_AI_STUFF}
        {LOYAL_UNIT 8 (Necrophage) 30 9} {GUARDIAN}
        {LOYAL_UNIT 8 (Soulless)   28 9} {GUARDIAN} {VARIATION troll}
        {LOYAL_UNIT 8 (Dark Adept) 30 5} {GUARDIAN}
        {LOYAL_UNIT 8 (Ghoul)      38 6} {GUARDIAN}
        {LOYAL_UNIT 8 (Dark Adept) 37 5} {GUARDIAN}
    [/side]
    {RECRUIT_UNIT_VARIATIONS 8 "Walking Corpse" goblin,dwarf,dwarf,troll}
    {RECRUIT_UNIT_VARIATIONS 8 "Soulless"       goblin,dwarf,dwarf,troll}
    {SILENTLY_LIMIT_LEADER_MOVES 8 1}

    [event]
        name=side 1 turn end
        first_time_only=no
        [filter_condition]
            [not]
                [have_unit]
                    id=Mal-Ravanal
                [/have_unit]
            [/not]
        [/filter_condition]

        {RESET_SIDE_AI (2,3,4,5,6,7,8) offensive 0.8 0.25}

        {MODIFY_AI_ADD_GOAL (2,3,4,5,6,7,8) ({GOAL_LOCATION 11 (x,y=28,22)})} # go after Weldyn

        {RETREAT_WHEN_WEAK 2 {ON_DIFFICULTY 0-6 0-8 0-10} (
            {GOAL_LOCATION 99 (x,y=55,6)}
            {GOAL_LOCATION 66 (x,y=55,5)}
            {GOAL_LOCATION 99 (x,y=57,8)}
            {GOAL_LOCATION 66 (x,y=58,7)}
            {GOAL_LOCATION 77 (x,y=57,6)}
        )}
        {RETREAT_WHEN_WEAK 3 {ON_DIFFICULTY 0-6 0-8 0-10} (
            {GOAL_LOCATION 77 (x,y=53,21)}
            {GOAL_LOCATION 77 (x,y=53,19)}
            {GOAL_LOCATION 77 (x,y=54,18)}
            {GOAL_LOCATION 99 (x,y=54,19)}
            {GOAL_LOCATION 77 (x,y=54,22)}
        )}
        {RETREAT_WHEN_WEAK 4 {ON_DIFFICULTY 0-6 0-8 0-10} (
            {GOAL_LOCATION 99 (x,y=52,37)}
            {GOAL_LOCATION 88 (x,y=55,37)}
            {GOAL_LOCATION 77 (x,y=56,37)}
        )}
        {RETREAT_WHEN_WEAK 5 {ON_DIFFICULTY 0-6 0-8 0-10} (
            {GOAL_LOCATION 99 (x,y=33,38)}
            {GOAL_LOCATION 88 (x,y=30,38)}
            {GOAL_LOCATION 11 (x,y=34,40)}
            {GOAL_LOCATION 11 (x,y=31,41)}
        )}
        {RETREAT_WHEN_WEAK 6 {ON_DIFFICULTY 0-6 0-8 0-10} (
            {GOAL_LOCATION 99 (x,y=12,30)}
            {GOAL_LOCATION 88 (x,y=9,34)}
            {GOAL_LOCATION 55 (x,y=8,33)}
            {GOAL_LOCATION 55 (x,y=7,33)}
            {GOAL_LOCATION 55 (x,y=6,33)}
        )}
        {RETREAT_WHEN_WEAK 7 {ON_DIFFICULTY 0-6 0-8 0-10} (
            {GOAL_LOCATION 99 (x,y=7,7)}
            {GOAL_LOCATION 99 (x,y=6,7)}
            {GOAL_LOCATION 99 (x,y=5,7)}
            {GOAL_LOCATION 99 (x,y=4,8)}
        )}
        {RETREAT_WHEN_WEAK 8 {ON_DIFFICULTY 0-11 0-14 0-17} (
            # this side has more loyal defenders, and tends to attack too early otherwise
            {GOAL_LOCATION 99 (x,y=33,8)}
            {GOAL_LOCATION 88 (x,y=30,5)}
            {GOAL_LOCATION 77 (x,y=38,6)}
        )}

        {CHANGE_RECRUITS_IF_RICH 2 (Dark Adept,Skeleton,Skeleton Archer)             (Draug)       }
        {CHANGE_RECRUITS_IF_RICH 3 (Dark Adept,Walking Corpse,Soulless,Ghoul)        (Necromancer) }
        {CHANGE_RECRUITS_IF_RICH 4 (Dark Adept,Vampire Bat,Blood Bat,Skeleton Rider) (Death Knight)}
        {CHANGE_RECRUITS_IF_RICH 5 (Dark Adept,Vampire Bat,Blood Bat,Ghost)          (Nightgaunt)  }
        {CHANGE_RECRUITS_IF_RICH 6 (Dark Adept,Walking Corpse,Soulless,Ghoul)        (Necromancer) }
        {CHANGE_RECRUITS_IF_RICH 7 (Dark Adept,Skeleton,Skeleton Archer)             (Banebow)     }
        {CHANGE_RECRUITS_IF_RICH 8 (Dark Adept,Walking Corpse,Soulless,Ghoul)        (Necromancer) }

        {VARY_AI_BY_SCHEDULE (2,3,4,5,6,7,8)}
    [/event]

    [side]
        side=9
        color=brightgreen
        type=Dark Adept
        id=Lethin
        #po: in the unlikely event that Mal-Tar survived S03, Lethin gets renamed and has dialogue as Mal-Tar
        name= _ "Lethin"
        canrecruit=yes
        facing=sw
        [modifications]
            {TRAIT_INTELLIGENT} # same traits as S03's Mal-Tar
            {TRAIT_RESILIENT}
        [/modifications]
        recruit=Walking Corpse,Soulless,Ghoul #Skeletal Corpse,Skeletal Soulless
        controller=ai
        team_name=undead
        user_team_name=_"Undead"
        {GOLD 100 300 500}
        income=-2
        village_gold=0
        {FLAG_VARIANT undead}

        {LOYAL_UNIT 9 (Soulless) 50 11} {GUARDIAN}

        [unit]
            x,y=16,8
            name=_ "Rerivyan"
            type=Dark Adept
            canrecruit=yes
            gender=female
            facing=se
        [/unit]
        {LOYAL_UNIT 9 (Walking Corpse) 20 10} {GUARDIAN}
        {LOYAL_UNIT 9 (Ghoul) 15 10} {GUARDIAN}

        [unit]
            x,y=9,26
            name=_ "Vowyn"
            type=Dark Adept
            canrecruit=yes
            gender=female
            facing=se
        [/unit]
        {LOYAL_UNIT 9 (Soulless) 9 22} {GUARDIAN}
    [/side]
    {RECRUIT_UNIT_VARIATIONS 9 "Walking Corpse" none,none,none,none}
    {RECRUIT_UNIT_VARIATIONS 9 "Soulless"       none,none,none,none}
    {SILENTLY_LIMIT_LEADER_MOVES 9 1}
    [event]
        name=prestart

        [filter_condition]
            {VARIABLE_CONDITIONAL mal_tar_alive equals yes}
        [/filter_condition]

        {CLEAR_VARIABLE mal_tar_alive}
        {MODIFY_UNIT id=Lethin name _"Mal-Tar"}
        {MODIFY_UNIT id=Lethin experience 29}
        [event]
            name=last breath
            [filter]
                id=Lethin
            [/filter]
            [message]
                speaker=unit
                #po: last breath for Mal-Tar
                message= _ "Wait, wait, stop, I surrender! I know your leader Gweddry!"
            [/message]
            [message]
                speaker=unit
                #po: last breath for Mal-Tar
                message= _ "He defeated me back in the Estmarks but still let me live! Let me go and I promise you’ll never see me again!"
            [/message]
            [message]
                speaker=second_unit
                message= _ "Well, okay I guess..."
            [/message]
            {MOVE_UNIT id=Lethin 61 6}
            {KILL id=Lethin}
            [message]
                speaker=Gweddry
                #po: speaking of Mal-Tar
                message= _ "It’s been an entire war, and that guy still hasn’t improved his magic..."
            [/message]
        [/event]
    [/event]

    [event]
        name=side 8 turn end
        first_time_only=no
        [filter_condition]
            [not]
                [have_unit]
                    id=Mal-Ravanal
                [/have_unit]
            [/not]
        [/filter_condition]

        {RESET_SIDE_AI (9) offensive 0.9 0.1}

        # avoid the city, at least until Mal-Ravanal shows up
        {MODIFY_SIDE_AI (9) ({GOAL_LOCATION 11 (
            [not]
                x,y=28,22
                radius=13
            [/not]
        )})}
        {MODIFY_SIDE_AI (9) ({GOAL_LOCATION 99 (
            [not]
                x,y=28,22
                radius=9
            [/not]
        )})}

        # hunt enemies not near the city
        {MODIFY_SIDE_AI (9) ({GOAL_LOCATION 9999 (
            [filter]
                side=1
            [/filter]
            [not]
                x,y=28,22
                radius=13
            [/not]
        )})}

        # avoid a little area in the west, so that the southwest and northwest adepts don't merge their armies
        {MODIFY_SIDE_AI (9) ({GOAL_LOCATION 5 (
            [not]
                x,y=1-13,17-21
            [/not]
        )})}

        {CHANGE_RECRUITS_IF_RICH 9 (Walking Corpse,Soulless,Ghoul) (Necrophage,Ghast)}

        {VARY_AI_BY_SCHEDULE (9)}
    [/event]

    # ravanal's side and his escort side
    [side]
        side=10
        controller=ai
        color=black
        no_leader=yes
        hidden=yes
        team_name=undead
        user_team_name=_"Undead"
        {FLAG_VARIANT undead}
    [/side]
    [side]
        side=11
        controller=ai
        color=black
        no_leader=yes
        hidden=yes
        team_name=undead
        user_team_name=_"Undead"
        {FLAG_VARIANT undead}
    [/side]

    # wmllint: recognize Mal-Ravanal
    [event]
        name=prestart
        {VARIABLE fork_18b yes}

        # Gweddry gets the villages within the moat.
        # The ones outside he'll actually have to take.
        {CAPTURE_VILLAGES 1 28 22 3}

        # river walls
        [event]
            name=new turn,draw_walls
            first_time_only=no
            [store_time_of_day]
            [/store_time_of_day]
            [if]
                [variable]
                    name=time_of_day.id
                    equals=morning
                [/variable]

                [then]
                    {REMOVE_IMAGE 28 22}
                    [item]
                        x,y=28,22
                        halo=weldyn/walls_S18b.png
                    [/item]
                [/then]
            [/if]

            [store_time_of_day]
            [/store_time_of_day]
            [if]
                [variable]
                    name=time_of_day.id
                    equals=dusk
                [/variable]

                [then]
                    {REMOVE_IMAGE 28 22}
                    [item]
                        x,y,halo=28,22,weldyn/walls_S18b.png~CS(10,-20,-35)
                    [/item]
                [/then]
            [/if]

            [store_time_of_day]
            [/store_time_of_day]
            [if]
                [variable]
                    name=time_of_day.id
                    equals=first_watch
                [/variable]

                [then]
                    {REMOVE_IMAGE 28 22}
                    [item]
                        x,y,halo=28,22,weldyn/walls_S18b.png~CS(-75,-45,-13)
                    [/item]
                [/then]
            [/if]

            [store_time_of_day]
            [/store_time_of_day]
            [if]
                [variable]
                    name=time_of_day.id
                    equals=dawn
                [/variable]

                [then]
                    {REMOVE_IMAGE 28 22}
                    [item]
                        x,y,halo=28,22,weldyn/walls_S18b.png~CS(-25,-15,0)
                    [/item]
                [/then]
            [/if]
        [/event]
        [fire_event]
            name=draw_walls
        [/fire_event]

        {PLACE_IMAGE "scenery/shipwreck-1.png~FL()" 33 28}
        {PLACE_IMAGE scenery/wreck-3.png 33 27}

        # stuff also visible in 15_Return_To_Wesnoth
        {PLACE_IMAGE scenery/village-human-burned1.png 12 3}
        {PLACE_IMAGE scenery/village-human-burned4.png 12 12}
        {PLACE_IMAGE scenery/village-human-burned3.png 17 1}

        {PLACE_IMAGE scenery/gore-1.png 30 2}
        {PLACE_IMAGE scenery/village-human-burned2.png 30 2}
        {PLACE_IMAGE scenery/gore-2.png 30 3}
        {PLACE_IMAGE "scenery/blood-trail-2.png~FL(horiz)" 31 4}

        {PLACE_IMAGE scenery/gore-1.png 8 10}
        {PLACE_IMAGE scenery/village-human-burned3.png 8 10}
        {PLACE_IMAGE scenery/blood-1.png 8 11}

        {PLACE_IMAGE scenery/blood-2.png 42 17}
        {PLACE_IMAGE scenery/gore-3.png 41 17}

        {PLACE_IMAGE scenery/blood-3.png 30 9}
        {PLACE_IMAGE scenery/blood-1.png 31 10}

        {PLACE_IMAGE scenery/blood-1.png 11 24}
        {PLACE_IMAGE scenery/gore-3.png 15 28}
        {PLACE_IMAGE scenery/gore-2.png 11 3}

        # new stuff
        {PLACE_IMAGE scenery/blood-1.png 21 22}
        {PLACE_IMAGE scenery/gore-3.png 22 23}
        {PLACE_IMAGE scenery/gore-2.png 26 28}
        {PLACE_IMAGE scenery/blood-2.png 25 29}
        {PLACE_IMAGE scenery/blood-3.png 37 24}
        {PLACE_IMAGE scenery/gore-1.png 35 24}
        {PLACE_IMAGE scenery/blood-1.png 34 24}
        {PLACE_IMAGE scenery/blood-2.png 32 19}
        {PLACE_IMAGE scenery/blood-3.png 26 16}
        {PLACE_IMAGE scenery/blood-2.png 16 15}
        {PLACE_IMAGE scenery/blood-1.png 26 19}

        {PLACE_IMAGE scenery/gore-1.png 30 33}
        {PLACE_IMAGE scenery/village-human-burned1.png 30 33}
        {PLACE_IMAGE scenery/blood-trail-1.png 31 34}

        {PLACE_IMAGE scenery/gore-1.png 52 34}
        {PLACE_IMAGE scenery/village-human-burned1.png 52 34}
        {PLACE_IMAGE scenery/blood-trail-2.png 51 35}

        {PLACE_IMAGE scenery/gore-1.png 56 20}
        {PLACE_IMAGE scenery/blood-2.png 57 21}
        {PLACE_IMAGE scenery/blood-1.png 52 22}

        {BRAZIER_ILLUMINATION_MORNING 26 21}
        {BRAZIER_ILLUMINATION_MORNING 26 23}
        {BRAZIER_ILLUMINATION_MORNING 30 21}
        {BRAZIER_ILLUMINATION_MORNING 30 23}

        {VARIABLE liches_to_kill 4}

        [objectives]
            side=1
            [objective]
                description= _ "Kill $liches_to_kill liches to reveal Mal-Ravanal"
                condition=win
                [show_if]
                    [not]
                        [have_unit]
                            id=Mal-Ravanal
                        [/have_unit]
                    [/not]
                [/show_if]
            [/objective]
            [objective]
                description= _ "Defeat Mal-Ravanal"
                condition=win
                [show_if]
                    [have_unit]
                        id=Mal-Ravanal
                    [/have_unit]
                [/show_if]
            [/objective]
            [objective]
                description= _ "Death of Dacyn"
                condition=lose
            [/objective]
            [objective]
                description= _ "Death of Konrad II"
                condition=lose
            [/objective]

            [note]
                description= _ "Konrad II will not leave the center island."
            [/note]
        [/objectives]

#define BONUS_UNIT X Y TYPE FACE XP COLOR TRAIT1 TRAIT2
    {NOTRAIT_UNIT 1 ({TYPE}) {X} {Y}}  {FACING {FACE}}
    [+unit]
        [modifications]
            {TRAIT1}
            {TRAIT2}
        [/modifications]
    [/unit]

    {TEAM_COLOR_OVERRIDE (x,y={X},{Y}) {COLOR}}
    [modify_unit]
        [filter]
            x,y={X},{Y}
        [/filter]

        experience={XP} # using formulas for high-XP units, in case unit XP values get rebalanced
    [/modify_unit]
#enddef
#define GOLD_PICKUP X Y SPEAKER MESSAGE
    {PLACE_IMAGE "items/gold-coins-medium.png" {X} {Y}}
    [event]
        name=moveto

        [filter]
            side=1
            x,y={X},{Y}
        [/filter]

        [message]
            speaker={SPEAKER}
            sound=gold.ogg
            message={MESSAGE}
        [/message]
        [gold]
            side=1
            amount=150
        [/gold]
        {REMOVE_IMAGE $unit.x $unit.y}
        {REMOVE_LABEL $unit.x $unit.y}
    [/event]
#enddef
        [if]
            {VARIABLE_CONDITIONAL Halrad.length greater_than 0}
            [then]
                [unstore_unit]
                    variable=Halrad
                [/unstore_unit]
                [put_to_recall_list]
                    id=Halrad
                    heal=yes
                [/put_to_recall_list]
                {RECALL_XY Halrad 26 17}
                [modify_unit]
                    [filter]
                        id=Halrad
                    [/filter]

                    side=1
                    facing=ne
                    experience=31
                [/modify_unit]
                {TEAM_COLOR_OVERRIDE id=Halrad blue}

                {BONUS_UNIT 27 17 (White Mage)        ne "$($this_unit.max_experience-42)" blue   {TRAIT_RESILIENT}   {TRAIT_QUICK}     }
                {BONUS_UNIT 26 16 (Red Mage)          nw 21                                blue   {TRAIT_INTELLIGENT} {TRAIT_RESILIENT} }
                {BONUS_UNIT 33 18 (Shock Trooper)     ne 13                                blue   {TRAIT_QUICK}       {TRAIT_FEARLESS}  }
                {BONUS_UNIT 22 18 (Heavy Infantryman) nw "$($this_unit.max_experience-11)" blue   {TRAIT_INTELLIGENT} {TRAIT_FEARLESS}  }
                {BONUS_UNIT 25 17 (Duelist)           nw  6                                blue   {TRAIT_STRONG}      {TRAIT_RESILIENT} }
                {BONUS_UNIT 31 17 (Swordsman)         ne 37                                blue   {TRAIT_STRONG}      {TRAIT_RESILIENT} }
                {BONUS_UNIT 32 18 (Spearman)          ne "$($this_unit.max_experience -9)" blue   {TRAIT_QUICK}       {TRAIT_STRONG}    }

                {CAPTURE_VILLAGES 1 26 17 5}
                {MODIFY_TERRAIN Rr^Ebn 33 19} {BRAZIER_ILLUMINATION_MORNING 33 19}
                {MODIFY_TERRAIN Re^Ebn 25 18} {BRAZIER_ILLUMINATION_MORNING 25 18}
                {GOLD_PICKUP 27 18 Halrad _"150 gold remains in my war-chest. I place it at your service, my Liege."}
            [/then]
        [/if]

        [if]
            {VARIABLE_CONDITIONAL Halric.length greater_than 0}
            [then]
                [unstore_unit]
                    variable=Halric
                [/unstore_unit]
                [put_to_recall_list]
                    id=Halric
                    heal=yes
                [/put_to_recall_list]
                {RECALL_XY Halric 34 25}
                [modify_unit]
                    [filter]
                        id=Halric
                    [/filter]

                    side=1
                    facing=se
                    experience=41
                [/modify_unit]
                {TEAM_COLOR_OVERRIDE id=Halric green}

                {BONUS_UNIT 35 25 (White Mage)        ne 33                                green   {TRAIT_QUICK}       {TRAIT_STRONG}      }
                {BONUS_UNIT 32 27 (Red Mage)          se "$($this_unit.max_experience-21)" green   {TRAIT_STRONG}      {TRAIT_RESILIENT}   }
                {BONUS_UNIT 35 21 (Shock Trooper)     ne 18                                green   {TRAIT_INTELLIGENT} {TRAIT_FEARLESS}    }
                {BONUS_UNIT 31 28 (Heavy Infantryman) se "$($this_unit.max_experience -4)" green   {TRAIT_FEARLESS}    {TRAIT_QUICK}       }
                {BONUS_UNIT 34 21 (Duelist)           ne 22                                green   {TRAIT_RESILIENT}   {TRAIT_STRONG}      }
                {BONUS_UNIT 35 26 (Swordsman)         se 16                                green   {TRAIT_INTELLIGENT} {TRAIT_STRONG}      }
                {BONUS_UNIT 33 26 (Spearman)          se "$($this_unit.max_experience-11)" green   {TRAIT_RESILIENT}   {TRAIT_INTELLIGENT} }

                {CAPTURE_VILLAGES 1 34 25 5}
                {MODIFY_TERRAIN Re^Ebn 34 24} {BRAZIER_ILLUMINATION_MORNING 34 24}
                {GOLD_PICKUP 33 25 Halric _"My Liege, I’ve managed to conserve 150 gold from the previous battle. I place it at your disposal."}
            [/then]
        [/if]

        [if]
            {VARIABLE_CONDITIONAL Halrod.length greater_than 0}
            [then]
                [unstore_unit]
                    variable=Halrod
                [/unstore_unit]
                {MODIFY_UNIT id=Halrod side 1}
                [put_to_recall_list]
                    id=Halrod
                    heal=yes
                [/put_to_recall_list]
                {RECALL_XY Halrod 23 26}
                [modify_unit]
                    [filter]
                        id=Halrod
                    [/filter]

                    side=1
                    facing=sw
                    experience=37
                [/modify_unit]
                {TEAM_COLOR_OVERRIDE id=Halrod brightorange}

                {BONUS_UNIT 23 25 (White Mage)        nw 18                                brightorange   {TRAIT_STRONG}    {TRAIT_QUICK}       }
                {BONUS_UNIT 21 23 (Red Mage)          nw 26                                brightorange   {TRAIT_QUICK}     {TRAIT_INTELLIGENT} }
                {BONUS_UNIT 21 22 (Shock Trooper)     nw 35                                brightorange   {TRAIT_FEARLESS}  {TRAIT_QUICK}       }
                {BONUS_UNIT 25 28 (Heavy Infantryman) sw "$($this_unit.max_experience-17)" brightorange   {TRAIT_RESILIENT} {TRAIT_FEARLESS}    }
                {BONUS_UNIT 26 27 (Duelist)           sw "$($this_unit.max_experience-27)" brightorange   {TRAIT_STRONG}    {TRAIT_RESILIENT}   }
                {BONUS_UNIT 22 25 (Swordsman)         sw "$($this_unit.max_experience-22)" brightorange   {TRAIT_STRONG}    {TRAIT_RESILIENT}   }
                {BONUS_UNIT 24 26 (Spearman)          sw "$($this_unit.max_experience-10)" brightorange   {TRAIT_QUICK}     {TRAIT_STRONG}      }

                {CAPTURE_VILLAGES 1 24 25 5}
                {MODIFY_TERRAIN Rr^Ebn  22 24} {BRAZIER_ILLUMINATION_MORNING 22 24}
                {MODIFY_TERRAIN Rrc^Ebn 29 28} {BRAZIER_ILLUMINATION_MORNING 29 28}
                {GOLD_PICKUP 24 25 Halrod _"For you, my Liege: my men have salvaged 150 gold from the ruins of the city outskirts."}
            [/then]
        [/if]

        [modify_unit]
            [filter]
                id=Halric,Halrad,Halrod
            [/filter]

            canrecruit=yes
            [object]
                [effect]
                    apply_to=overlay
                    remove=misc/leader-crown.png
                [/effect]

                [effect]
                    apply_to=overlay
                    add=misc/leader-expendable.png
                [/effect]
            [/object]
            [filter_recall]
                [not]
                    trait=undead
                [/not]
            [/filter_recall]
        [/modify_unit]
        [set_extra_recruit]
            id=Halric,Halrad,Halrod
            extra_recruit={REGULAR_RECRUIT_LIST}
        [/set_extra_recruit]

        {RECALL_XY Konrad 28 22}
    [/event]

    [event]
        name=start
        {RECALL_XY Gweddry 29 23}
        {RECALL_XY Dacyn 27 23}
        {RECALL_XY Owaec 29 22}
        {RECALL_XY Addogin 28 21}
        {RECALL_XY (Hahid al-Ali) 28 21}
        {RECALL_XY Terraent 28 21}
        {RECALL_XY Grug 27 22}
        {RECALL_XY Dolburras 27 22}
        {RECALL_XY Yannic 28 23}
        {RECALL_XY Gaennell 28 22} # any open spot near the king

        [message]
            speaker=Halrad
            message= _ "My forces are in position at the northern wall; awaiting your orders."
        [/message]
        [message]
            speaker=Halric
            message= _ "Eastern flank reclaimed. I stand ready to launch the assault."
        [/message]
        [message]
            speaker=Halrod
            message= _ "The western barricades are manned and ready — it’s payback time."
        [/message]
        [if]
            [have_unit]
                id=Owaec
            [/have_unit]

            [then]
                [message]
                    speaker=Owaec
                    message= _ "Now is the time to strike! In the name of the Clans, Mal-Ravanal will be ended this day!"
                [/message]
            [/then]

            [else]
                [message]
                    speaker=Konrad
                    message= _ "Now is the time to strike! By the might of all Wesnoth, Mal-Ravanal shall be ended this day!"
                [/message]
            [/else]
        [/if]

        {SCROLL_TO 61 1}
        [delay]
            time=200
        [/delay]

        {SCROLL_TO 47 34}
        [delay]
            time=200
        [/delay]

        {SCROLL_TO 1 27}
        [delay]
            time=200
        [/delay]

        {SCROLL_TO 1 1}
        [delay]
            time=200
        [/delay]

        [message]
            speaker=Dacyn
            message= _ "These liches are channeling some dark magic to hide themselves. (cough)(cough) Even if Mal-Ravanal is here, I will not be able to (cough) reveal them until we have killed enough of these liches to break their spell. (cough)"
        [/message]

        [if]
            [have_unit]
                id=Gweddry
            [/have_unit]

            [then]
                [message]
                    speaker=Gweddry
                    message= _ "Then that’s what we’ll have to do. And we will have to do it quickly, before Mal-Ravanal’s reinforcing armies overwhelm us."
                [/message]
                [message]
                    speaker=Konrad
                    message= _ "Stride fearless upon the plain of battle, for today we reclaim our legacy! For Wesnoth!!"
                [/message]
            [/then]

            [else]
                [message]
                    speaker=Konrad
                    message= _ "Then kill them we shall. Stride fearless upon the plain of battle, for today we reclaim our legacy! For Wesnoth!!"
                [/message]
            [/else]
        [/if]

        [set_variables]
            name=random_liches
            # wmllint: markcheck off
            [value]
                name= _ "Mal-Hadanak"
                quote= _ "You dare to attack me?"
            [/value]
            [value]
                name= _ "Mal-Katklagad"
                quote= _ "I will enjoy watching you suffer!"
            [/value]
            [value]
                name= _ "Mal-Xaskanat"
                quote= _ "Death will only be the beginning of your torment!"
            [/value]
            [value]
                name= _ "Mal-Akranbral"
                quote= _ "You will serve me in death!"
            [/value]
            [value]
                name= _ "Mal-Larakan"
                quote= _ "Allow me to free you from your wretched existence!"
            [/value]
            [value]
                name= _ "Mal-Drakanal"
                quote= _ "I am merely toying with you!"
            [/value]
            # wmllint: markcheck on
        [/set_variables]

        [store_unit]
            [filter]
                type=Lich
                canrecruit=yes
            [/filter]

            kill=no
            variable=liches
        [/store_unit]

        [foreach]
            array=liches
            [do]
                [object]
                    [filter]
                        x,y=$this_item.x,$this_item.y
                    [/filter]

                    [effect]
                        apply_to=halo
                        halo="halo/holy/light-beam-5.png~CROP(0,0,150,500)~SCALE(108,144)~CS(-159,-255,-159)~MASK(terrain/misc/smoke-A[01~12].png~SCALE(108,144)):100"
                    [/effect]
                [/object]
            [/do]
        [/foreach]
        {CLEAR_VARIABLE liches}
    [/event]

    # flavor message
    [event]
        name=moveto
        [filter]
            side=1
            x=10-99,13-99,17-99,27-99,39-99,48-99
            y=38-99,34-99,32-99,29-99,27-99,24-99
        [/filter]
        {FIND_NEARBY (type_adv_tree=Spearman,Bowman,Heavy Infantryman,Mage,Cavalryman,Horseman,Mounted Warrior,Sergeant) $unit.x $unit.y 99}
        # in case $unit is a ogre, zombie, dunefolk, etc
        [message]
            speaker=$found_unit.id
            message= _ "The River Weldyn used to be so beautiful, before the undead dammed it and flooded the shores..."
        [/message]
    [/event]

    # konrad flavor, in case he didn't attack in S16
    [event]
        name=attack

        [filter]
            id=Konrad
        [/filter]

        [filter_second]
            [not]
                id=Mal-Ravanal
            [/not]
        [/filter_second]

        [filter_condition]
            {VARIABLE_CONDITIONAL konrad_spoke not_equals yes}
        [/filter_condition]

        [message]
            speaker=Konrad
            message= _ "My legacy will not be one of failure! With all the might of the throne of Wesnoth, I shall strike you down!"
        [/message]
        {VARIABLE konrad_spoke yes}
    [/event]

    # first lich kill dialogue
    [event]
        name=die

        [filter]
            type=Lich
        [/filter]

        [filter_condition]
            [lua]
                code = << return (wesnoth.current.turn<=7) >>
            [/lua]
        [/filter_condition]
        [message]
            speaker=Konrad
            #po: killed a lich
            message= _ "That’s one down! The undead must still be in disarray after their failed attack during the long night."
        [/message]
    [/event]

    # second night dialogue (the AI usually mounts a big assault here)
    [event]
        name=side 2 turn 9
        {FIND_NEARBY (
            side=2,3,4,5,6,7,8
            canrecruit=yes
        ) 34 38 999}
        [message]
            speaker=$found_unit.id
            #po: speaker is a random lich
            message= _ "Night falls on Weldyn! Your counterattack may have caught us by surprise, but this hour is our domain."
        [/message]
        {FIND_NEARBY (
            side=2,3,4,5,6,7,8
            canrecruit=yes
        ) 61 9 999}
        [message]
            speaker=$found_unit.id
            #po: speaker is a random lich, almost certainly a different one than the previous speaker
            message= _ "Now you will pay for your arrogance!"
        [/message]
    [/event]

    # Konrad refuses to flee Weldyn
    [event]
        name=enter hex
        first_time_only=no
        [filter]
            id=Konrad
            [filter_location]
                x=0-24, 25,  25,   26,  26,   27,  27,   28,  28,   29,  29,   30,  30,   31,  31,   32-99
                y=0-99, 0-20,25-99,0-19,25-99,0-19,26-99,0-18,26-99,0-19,26-99,0-19,25-99,0-20,25-99, 0-99
                #                x=20,  21,  21,   22,  22,   23,  23,   24,  24,   25,  25,   26,  26,   27,  27,   28,  28,   29,  29,   30,  30,   31,  31,   32,  32,   33,  33,   34,  34,   35,  35,   36
                #                    y=0-99,0-18,25-99,0-17,26-99,0-17,27-99,0-16,27-99,0-16,29-99,0-15,29-99,0-16,29-99,0-15,29-99,0-16,29-99,0-16,29-99,0-16,29-99,0-16,28-99,0-17,28-99,0-18,26-99,0-20,27-00,0-99
            [/filter_location]
        [/filter]
        [cancel_action]
        [/cancel_action]
        [message]
            speaker=Konrad
            #po: the player is trying to move him away
            message= _ "A king belongs in his capital! I will not abandon my post!"
        [/message]
        {MOVE_UNIT (id=Konrad) $x2 $y2}
        [allow_undo]
        [/allow_undo]
    [/event]

#define WIPE_GOLD_IF_NO_LEADER SIDE
    [if]
        [not]
            [have_unit]
                canrecruit=yes
                side={SIDE}
            [/have_unit]
        [/not]
        [then]
            [modify_side]
                side={SIDE}
                gold=0
            [/modify_side]
        [/then]
    [/if]
#enddef
    [event]
        name=turn refresh
        first_time_only=no

        # don't charge upkeep for any AI sides. Their gold should be strictly regulated
        [modify_unit]
            [filter]
                side=2,3,4,5,6,7,8,9
            [/filter]

            [object]
                id=no_upkeep
                [effect]
                    apply_to=loyal
                [/effect]
            [/object]
        [/modify_unit]

        {WIPE_GOLD_IF_NO_LEADER 2}
        {WIPE_GOLD_IF_NO_LEADER 3}
        {WIPE_GOLD_IF_NO_LEADER 4}
        {WIPE_GOLD_IF_NO_LEADER 5}
        {WIPE_GOLD_IF_NO_LEADER 6}
        {WIPE_GOLD_IF_NO_LEADER 7}
        {WIPE_GOLD_IF_NO_LEADER 8}
        {WIPE_GOLD_IF_NO_LEADER 9}
    [/event]

#define RECORD_LICH_LEADER_COUNT COUNT
    [if]
        [have_unit]
            type=Lich
            canrecruit=yes
            count={COUNT} # not mal-ravanal
        [/have_unit]
        [then]
            {VARIABLE side_count {COUNT}}
        [/then]
    [/if]
#enddef
    [event]
        name=die
        first_time_only=no
        [filter]
            side=2,3,4,5,6,7,8,9
        [/filter]
        [filter_condition] # make sure we have at least 1 leader, or else this is an infinite loop
            [have_unit]
                side=2,3,4,5,6,7,8,9
                canrecruit=yes
                [not]
                    id=Mal-Ravanal
                [/not]
            [/have_unit]
        [/filter_condition]

        {RECORD_LICH_LEADER_COUNT 1}
        {RECORD_LICH_LEADER_COUNT 2}
        {RECORD_LICH_LEADER_COUNT 3}
        {RECORD_LICH_LEADER_COUNT 4}
        {RECORD_LICH_LEADER_COUNT 5}
        {RECORD_LICH_LEADER_COUNT 6}
        {RECORD_LICH_LEADER_COUNT 7} #order matters
        [if]
            [have_unit]
                side=9
                canrecruit=yes
            [/have_unit]

            [then]
                {VARIABLE_OP side_count add 1}
            [/then]
        [/if]

        {VARIABLE refund_amount $unit.cost}
        [while]
            [variable]
                name=refund_amount
                greater_than=0
            [/variable]
            [do]
                [set_variable]
                    name=refund_side
                    rand=2,3,4,5,6,7,8,9
                [/set_variable]
                [if]
                    [have_unit]
                        side=$refund_side
                        canrecruit=yes

                        [not]
                            id=Mal-Ravanal
                        [/not]
                    [/have_unit]

                    [then]
                        [gold]
                            side=$refund_side
                            amount=1
                        [/gold]
                        {VARIABLE_OP refund_amount sub 1}
                    [/then]
                [/if]
            [/do]
        [/while]

        [floating_text]
            x,y=$unit.x,$unit.y
            #po: the parts to translate here are "gold refunded" and "per side"
            text= _ "<span color='#FFD700' size='x-small'>gold refunded</span>
<span color='#FFFFFF' size='xx-small'>  (1/$side_count per side)</span>"
        [/floating_text]
        [delay]
            time=500
        [/delay]

        [fire_event]
            name=explain_refund
        [/fire_event]

        #         {GOLD_TEXT 2 53 10}
        #         {GOLD_TEXT 3 53 21}
        #         {GOLD_TEXT 4 47 34}
        #         {GOLD_TEXT 5 34 36}
        #         {GOLD_TEXT 6  8 27}
        #         {GOLD_TEXT 7 16  8}
        #         {GOLD_TEXT 8 35  6}
    [/event]

    [event]
        name=explain_refund
        [sound]
            name=gold.ogg
        [/sound]

        {FIND_NEARBY (side,canrecruit=8,yes) 35 6 9}
        [message]
            speaker=$found_unit.id
            message = _ "Fools, you have already lost! For each minion you strike down, another shall rise to take its place."
        [/message]
    [/event]

    ###############################
    # DECIDE WHEN TO REVEAL MAL-RAVANAL
    ###############################
    #-------------------
    # REVEAL A GENERIC LICH
    #-------------------
    [event]
        name=attack
        first_time_only=no
        [filter]
            side=1
        [/filter]
        [filter_second]
            [filter_wml]
                [variables]
                    random_lich=yes
                [/variables]
            [/filter_wml]
        [/filter_second]
        [filter_condition]
            [have_unit]
                [filter_wml]
                    [variables]
                        random_lich=yes
                    [/variables]
                [/filter_wml]

                [not]
                    x,y=$x2,$y2
                [/not]
            [/have_unit]
        [/filter_condition]

        {RANDOM "0..$($random_liches.length - 1)"}
        {VARIABLE second_unit.name $random_liches[$random].name}
        {VARIABLE second_unit.variables.random_lich no}
        [unstore_unit]
            variable=second_unit
            find_vacant=no
        [/unstore_unit]
        [object]
            silent=yes
            [filter]
                find_in=second_unit
            [/filter]
            [effect]
                apply_to=halo
                halo=""
            [/effect]
        [/object]
        [message]
            speaker=second_unit
            message=$random_liches[$random].quote
        [/message]
        {CLEAR_VARIABLE random_liches[$random]}
    [/event]

    #-------------------
    # ALL-BUT-ONE LICHES REVEALED
    #-------------------
    # If only one random lich remains (all others have been attacked but not
    # enough of them killed to break the spell), then just reveal Mal-Ravanal
    # since the player already knows where he is
    [event]
        name=attack end
        [filter_condition]
            [have_unit]
                [filter_wml]
                    [variables]
                        random_lich=yes
                    [/variables]
                [/filter_wml]
                count=1
            [/have_unit]
        [/filter_condition]
        [fire_event]
            name=reveal ravanal
            [primary_unit]
                [filter_wml]
                    [variables]
                        random_lich=yes
                    [/variables]
                [/filter_wml]
            [/primary_unit]
        [/fire_event]
    [/event]

    #-------------------
    # BREAKING THE SPELL
    #-------------------
    # Reveal remaining liches when X of them have been killed
    [event]
        name=die
        first_time_only=no

        [filter]
            canrecruit=yes
            type_adv_tree=Lich
        [/filter]

        {VARIABLE_OP liches_killed add 1}

        [if]
            [not]
                [have_unit]
                    id=Mal-Ravanal
                [/have_unit]
            [/not]

            [variable]
                name=liches_killed
                greater_than_equal_to=$liches_to_kill
            [/variable]
            [then]
                {REPLACE_SCENARIO_MUSIC silence.ogg}

                [sound]
                    name=magic-dark-big-miss.ogg
                [/sound]

                {COLOR_ADJUST  127   64  127}
                [delay]
                    time=100
                [/delay]

                {COLOR_ADJUST -127 -191 -127}
                [delay]
                    time=100
                [/delay]

                {COLOR_ADJUST  127   64  127}
                [delay]
                    time=100
                [/delay]

                {COLOR_ADJUST    0    0    0}
                [message]
                    speaker=Owaec
                    message= _ "Their spell is broken!"
                [/message]
                [store_unit]
                    [filter]
                        [filter_wml]
                            [variables]
                                random_lich=yes
                            [/variables]
                        [/filter_wml]

                        [not]
                            x,y=$x2,$y2
                        [/not]
                    [/filter]
                    kill=no
                    variable=remaining_random_liches
                [/store_unit]

                # spawn mal-ravanal at the furthest lich from the player
                {VARIABLE longest_path_to_player 0}
                {VARIABLE farthest_lich_side ""}
                [foreach]
                    array=remaining_random_liches
                    [do]
                        [find_path]
                            [traveler]
                                canrecruit=yes
                                side=$this_item.side
                            [/traveler]
                            [destination]
                                [filter]
                                    side=1
                                [/filter]
                            [/destination]
                            allow_multiple_turns=yes
                            check_zoc=no
                            variable=path_to_player
                        [/find_path]
                        [if] {VARIABLE_CONDITIONAL longest_path_to_player less_than $path_to_player.hexes}
                            [then]
                                {VARIABLE longest_path_to_player $path_to_player.hexes}
                                {VARIABLE farthest_lich_side $this_item.side}
                            [/then]
                        [/if]
                    [/do]
                [/foreach]
                [fire_event]
                    name=reveal ravanal
                    [primary_unit]
                        canrecruit=yes
                        side=$farthest_lich_side
                    [/primary_unit]
                [/fire_event]

                # clear halo from remaining liches
                [store_unit]
                    [filter]
                        find_in=remaining_random_liches

                        [not]
                            side=$farthest_lich_side
                        [/not]
                    [/filter]
                    kill=no
                    variable=remaining_random_liches
                [/store_unit]
                [foreach]
                    array=remaining_random_liches
                    [do]
                        {RANDOM "0..$($random_liches.length - 1)"}
                        {VARIABLE this_item.name $random_liches[$random].name}
                        {VARIABLE this_item.variables.random_lich no}
                        [unstore_unit]
                            variable=this_item
                            find_vacant=no
                        [/unstore_unit]
                        [object]
                            silent=yes
                            [filter]
                                x,y=$this_item.x,$this_item.y
                            [/filter]
                            [effect]
                                apply_to=halo
                                halo=""
                            [/effect]
                        [/object]
                        {CLEAR_VARIABLE random_liches[$random]}
                    [/do]
                [/foreach]
                {CLEAR_VARIABLE longest_path_to_player,farthest_lich_side,path_to_player,liches_killed,remaining_random_liches}
            [/then]
        [/if]
    [/event]

    ###############################
    # REVEAL THE PRIMARY UNIT AS MAL-RAVANAL
    ###############################
    [event]
        name=reveal ravanal
        {REPLACE_SCENARIO_MUSIC silence.ogg}
        {SCROLL_TO $unit.x $unit.y}

        # guarantee Ravanal has at least a 6-hex encampment to recruit on
        [terrain]
            x,y=$unit.x,$unit.y
            radius=1
            terrain=Cer
        [/terrain]
        [terrain]
            x,y=$unit.x,$unit.y
            terrain=Ker
        [/terrain]
        [redraw]
        [/redraw]

        #-------------------
        # JUGGLE SIDES, FOR ESCORTING AND REANIMATION
        #-------------------
        {VARIABLE ravanal_side 10}
        {VARIABLE ravanal_reanimate_side 11}
        {MODIFY_UNIT side=$ravanal_side side 9} # change side of all existing ravanal_side units, so we don't reanimate them
        {MODIFY_UNIT side=$ravanal_reanimate_side side 9}

        #-------------------
        # CREATE MAL-RAVANAL
        #-------------------
        [animate_unit]
            [filter]
                id=$unit.id
            [/filter]
            flag=levelout
        [/animate_unit]
        [store_locations]
            owner_side=$unit.side
            variable=stored_villages
        [/store_locations]
        {KILL id=$unit.id}
        [unit]
            side=$ravanal_side
            x,y=$unit.x,$unit.y
            facing=$unit.facing
            {CHARACTER_STATS_RAVANAL}
        [/unit]
        [capture_village]
            find_in=stored_villages
            side=$ravanal_side
        [/capture_village]
        {CLEAR_VARIABLE stored_villages}
        [animate_unit]
            [filter]
                id=Mal-Ravanal
            [/filter]
            flag=levelin
        [/animate_unit]

        [fire_event]
            name=moveto
            [primary_unit]
                id=Mal-Ravanal # create the terror visual
            [/primary_unit]
        [/fire_event]
        {LIMIT_CONTEMPORANEOUS_RECRUITS $ravanal_side "Death Knight" 4} # this is just barely enough to spend all his max 750 gold
        {LIMIT_CONTEMPORANEOUS_RECRUITS $ravanal_side "Banebow"      4}
        {LIMIT_CONTEMPORANEOUS_RECRUITS $ravanal_side "Lich"         4}
        {LIMIT_CONTEMPORANEOUS_RECRUITS $ravanal_side "Spectre"      4}

        #-------------------
        # SET GOLD
        #-------------------
        # vary mal-ravanal's gold somewhat, based on the player's army strength (sum of unit levels + gold/20). He's supposed to be a credible threat
        # higher army strength is still better for the player, because you need it to fight off all the regular lichs' recruits
        # (hopefully not completely unreasonable, since Mal-Ravanal still thinks he's guaranteed to win and can afford to toy with Dacyn a little bit)
        {CALCULATE_ARMY_STRENGTH side=1 1}
        {VARIABLE amount 600} # default amount. No variation with difficulty, because Reanimation already varies
        [if] {VARIABLE_CONDITIONAL army_strength less_than 80}
            [then]
                {VARIABLE amount 550}
            [/then]
        [/if]
        [if] {VARIABLE_CONDITIONAL army_strength less_than 70}
            [then]
                {VARIABLE amount 500}
            [/then]
        [/if]
        [if] {VARIABLE_CONDITIONAL army_strength less_than 60}
            [then]
                {VARIABLE amount 450}
            [/then]
        [/if]
        [if] {VARIABLE_CONDITIONAL army_strength less_than 50}
            [then]
                {VARIABLE amount 400}
            [/then]
        [/if]
        [if] {VARIABLE_CONDITIONAL army_strength less_than 40}
            [then]
                {VARIABLE amount 350}
            [/then]
        [/if]
        [if] {VARIABLE_CONDITIONAL army_strength less_than 30}
            [then]
                {VARIABLE amount 300}
            [/then]
        [/if]
        {CLEAR_VARIABLE army_strength}
        [modify_side] # set gold, don't add. This side might have gold from earlier for some reason.
            side=$ravanal_side
            gold=$amount
        [/modify_side]
        {CLEAR_VARIABLE amount}

        #-------------------
        # ATTACK WHEN POOR
        #-------------------
        [event]
            name=new turn
            first_time_only=no
            [store_gold]
                side=$ravanal_side
            [/store_gold]
            [if]
                [variable]
                    name=gold
                    less_than=50
                [/variable]

                [then]
                    # Mal-Ravanal should try to avoid getting exposed
                    {MODIFY_SIDE_AI $ravanal_side (aggression=-9)}
                    {MODIFY_SIDE_AI $ravanal_side (caution=9)}
                    {MODIFY_SIDE_AI $ravanal_side (
                        [avoid] # stay out of water/swamp, I think?
                            terrain=Ww,Ww^Edt,Ww^Edb,Wwg,Wwg^Edt,Wwg^Edb,Wo,Ss,Sm
                        [/avoid]
                    )}
                    {MODIFY_SIDE_AI $ravanal_side leader_ignores_keep=yes}
                    {MODIFY_SIDE_AI $ravanal_side retreat_factor=0}

                    # swap ravanal's units to ravanal_reanimate_side, and have them escort him
                    # this has to be a different side so mal-ravanal moves first (otherwise he moves after and leaves the escorts behind)
                    # ravanal only has 4 moves, so his escort should have no problem keeping up
                    {MODIFY_UNIT (
                        side=$ravanal_side
                        [not]
                            id=Mal-Ravanal
                        [/not]
                    )
                    side $ravanal_reanimate_side}
                    [micro_ai]
                        side=$ravanal_reanimate_side
                        ai_type=zone_guardian
                        action=add

                        [filter]
                            side=$ravanal_reanimate_side
                        [/filter]

                        [filter_location]
                            radius=1
                            [filter]
                                id=Mal-Ravanal
                            [/filter]
                        [/filter_location]

                        [filter_location_enemy]
                            [filter]
                                id=Mal-Ravanal
                            [/filter]

                            radius=10 # large radius, so that they attack 1 or 2 turns before Mal-Ravanal
                        [/filter_location_enemy]
                    [/micro_ai]
                [/then]
            [/if]
        [/event]

        #-------------------
        # SET LICH AGGRESSION
        #-------------------
        # once mal-ravanal is on the field, everybody gets permanently aggressive
        # (the each-turn ai disables itself when Mal-Ravanal exists)
        {RESET_SIDE_AI (2,3,4,5,6,7,8,9) offensive 0.8 0.25}
        {MODIFY_AI_ADD_GOAL (2,3,4,5,6,7,8) ({GOAL_LOCATION 11 (x,y=28,22)})} # go after Weldyn
        {MODIFY_AI_ADD_GOAL (9)             ({GOAL_LOCATION 11 (x,y=28,22)})} # go after Weldyn
        {MODIFY_UNIT () ai_special ""}
        {MODIFY_UNIT () status.guardian "no"}

        #-------------------
        # DIALOGUE AND MUSIC
        #-------------------
        [message]
            speaker=Mal-Ravanal
            message=_"Enough of this farce! I shall end this personally."
        [/message]
        {REPLACE_SCENARIO_MUSIC the_dangerous_symphony.ogg}
        {APPEND_MUSIC heavens-remix.ogg}
        {APPEND_MUSIC siege_of_laurelmor.ogg}

        [show_objectives]
        [/show_objectives]
    [/event]

    [event]
        name=last breath

        [filter]
            id=Mal-Ravanal
        [/filter]

        [filter_condition]
            [not]
                [have_unit]
                    side=2,3,4,5,6,7,8,9

                    [not]
                        id=Mal-Ravanal
                    [/not]
                [/have_unit]
            [/not]
        [/filter_condition]

        [set_achievement]
            content_for=eastern_invasion
            id=ei_S17b
        [/set_achievement]
    [/event]

    # put this after the other Mal-Ravanal "last breath" event
    {campaigns/Eastern_Invasion/utils/final_battle/final_battle.cfg}

    {LATE_DEFEAT}

    {HERODEATH_GWEDDRY_EXPENDABLE}
    {HERODEATH_OWAEC_EXPENDABLE}
    {HERODEATH_DACYN_FINALBATTLE}
    {HERODEATH_ADDOGIN}
    {HERODEATH_TERRAENT}
    {HERODEATH_HAHID_FINALBATTLE}
    {HERODEATH_DOLBURRAS}
    {HERODEATH_GRUG}
    {HERODEATH_GAENNELL}
    {HERODEATH_YANNIC}

    {HERODEATH_KONRAD}
    {HERODEATH_HALRAD}
    {HERODEATH_HALRIC}
    {HERODEATH_HALROD}
[/scenario]

#undef INVADER_AI_STUFF
#undef GOLD_PICKUP
#undef BONUS_UNIT
