#####################################################################
#              SANDBOX SPACE
#####################################################################

default quest_mapmissionloc = []
  
#####################################################################
#                STARFIELD ANI SCREEN AND WRAPPER
#####################################################################

init python:

    #####################################################################
    #                SPACE TRAVEL
    #####################################################################

    from random import randrange

    class ProjectionStarfield(renpy.Displayable):
        def __init__(self,count=0, depth=0,*args,**kwargs):
            super(renpy.Displayable, self).__init__(*args,**kwargs)

            self.count = count
            self.depth = depth

            self.origin_x = config.screen_width /2
            self.origin_y = config.screen_height /2

            #If a perspective amount is provided, use it. If not, use default.
            try:
                self.perspective = kwargs["perspective"]
            except:
                self.perspective = 128.0

            #If a displayable is provided, use that as the star. If not, make a star to use.
            try:
                self.one_star = kwargs["child"]
            except:
                star_colour = Solid((255,255,255,255))
                self.one_star = Fixed(star_colour,xysize=(1,1))
            self.star_positions()

        def star_positions(self):
            #Create the starting positions for the stars, represented as: [X,Y,Z]
            self.stars = []

            for item in range(self.count):
                star = [randrange(-25,25), randrange(-25,25), randrange(1, self.depth)]
                self.stars.append(star)

        def render(self,width,height,st,at):
            render = renpy.Render(0,0)

            for star in self.stars:

                #Z coordinate decreases each redraw.
                star[2] -= 0.19

                #If the star exits the screen, move it to the back of the projection with random X and Y coordinates.
                if star[2] <= 0:
                    star[0] = randrange(-25,25)
                    star[1] = randrange(-25,25)
                    star[2] = self.depth

                #Convert the 3D coordinates to 2D using perspective projection.
                k = self.perspective / star[2]
                x = int(star[0] * k + self.origin_x)
                y = int(star[1] * k + self.origin_y)

                #Draw the star (if it's visible on screen).
                #Using Linear Interpolation, distant stars are smaller and darker than closer stars.
                if 0 <= x < config.screen_width and 0 <= y < config.screen_height:
                    size = (1 - float(star[2]) / self.depth) * 3
                    shade = (1 - float(star[2]) / self.depth)

                    #Apply the size and shade using Transform()
                    t = Transform(child=self.one_star, zoom=size, alpha=shade)
                    child_render = renpy.render(t,0,0,st,at)
                    render.blit(child_render,(x,y))

            renpy.redraw(self,0)
            return render

        def visit(self):
            return [self.one_star]

init:
    define stars = ProjectionStarfield(count=512,depth=16)

screen starfield_scr:
    add stars

label travel(message):
    scene space_bg_smart
    show screen starfield_scr
    "[message]"
    hide screen starfield_scr
    return()

#####################################################################
#              INTERCEPTS (POST ENTRY)
#####################################################################
label sandbox_intercept_space(*args):
    python:
        try:
            transitionInfo = args[2]
        except IndexError:
            transitionInfo = None
    if transitionInfo == "beacon_to_arellarti":
        # animation
        queue sound "audio/teleport.wav"
        scene expression("05_gui/hyperjump.png") with blueflash
        $ n = 5
        while n:
            $ n -= 1 
            queue sound "audio/teleport.wav"
            scene expression("05_gui/hyperjump.png") with vpunch 
        play sound "audio/explode.wav" 
        # prep arrival
        if GAME.ship.starSysID == "SSIDArellarti":
            scene space_bg_smart
            call arellarti_arrival() from _call_arellarti_arrival 

    return(True)
#####################################################################
#                NAVIGATE SPACE
#####################################################################

screen sandbox_space_scr(*args):

    $ starSys = GAME.getStarSys()
    $ dueMissionPoints = args[0]
    #text "{}".format("/".join(dueMissionPoints))


    #####################################################################
    #                SPACE LOCS
    #####################################################################
    $ station = {"SSIDArellarti": "LIDStationArellarti", "SSIDXenos": "LIDStationXenos", "SSIDIltari": "LIDStationIltari", "SSIDQuthor": "LIDStationQuthor", "SSIDNX010": "LIDStationNX010", "SSIDWaystation": "LIDWaystation"}[GAME.getStarSys().ID]
    
    for k in starSys.locs.keys():
        $ xCoord = starSys.locs[k].coord[0]
        $ yCoord = starSys.locs[k].coord[1]
        $ l = starSys.locs[k]

        if l.found:
            imagebutton auto "02_locations/ico {}_%s.png".format(l.guiImg) focus_mask True xalign 0.5 yalign 0.5 xpos xCoord ypos yCoord action Return(["loc", l]) tooltip [l.name, l.coord[0], l.coord[1] ]
            if l.ID in dueMissionPoints: 
                
                $ i_index = -1
                for i in dueMissionPoints:
                    $i_index += 1
                    if "Rendezvous" in dueMissionPoints[i_index]:
                        if i == l.ID and i in quest_mapmissionloc:
                            $ xshift = xCoord - 100 + (i_index * 10)
                            $ yshift = yCoord + (i_index * 10)
                            image "05_gui/star.png"  xpos xshift ypos yshift-48
                        else:
                            if i == l.ID:
                                $ xshift = xCoord - 126 + (i_index * 10)
                                $ yshift = yCoord + (i_index * 10)
                                $ mission = GAME.missionSys.missions[i_index]
                            
                                if mission.kind == "bounty":
                                    image "03_minigames/mg_combat_crosshair.png" xpos xshift ypos yshift-48 zoom 0.5
                                
                                elif mission.kind in ["transport", "smuggling"] and eval(mission.cond):
                                    image "05_gui/check.png" xpos xshift ypos yshift zoom 0.5
                                
                                else:  
                                    image "05_gui/ico_attention.png"  xpos xshift ypos yshift-48
                    else:
                        if i == l.ID:
                            $ xshift = xCoord - 126 + (i_index * 10)
                            $ yshift = yCoord + (i_index * 10)
                            $ mission = GAME.missionSys.missions[i_index]
                            
                            if mission.kind == "bounty":
                                image "03_minigames/mg_combat_crosshair.png" xpos xshift ypos yshift-48 zoom 0.5
                                
                            elif mission.kind in ["transport", "smuggling"] and eval(mission.cond):
                                image "05_gui/check.png" xpos xshift ypos yshift zoom 0.5
                                
                            else:  
                               image "05_gui/ico_attention.png"  xpos xshift ypos yshift-48
    

            if GAME.missionSys.shortages.get(l.ID, False):
                $ item = GAME.items[GAME.missionSys.shortages.get(l.ID)]
                frame xsize 220 ysize 60 xpos xCoord-74 ypos yCoord+40+48-160  background Solid("#005b7a88"):
                    image "05_gui/ico_gui_crate.png" zoom 0.2  xpos -20 yalign 0.5
                    text "[C_OR_B]SHORTAGE![C_OR_E] "+ "\n{}".format(item.getName(["noArt", "cap"])) size FSIZE_MED xpos 70 yalign 0.5

    $ tooltip = GetTooltip()
    if tooltip and isinstance(tooltip, list):
        text "{}".format(tooltip[0]) xpos tooltip[1] ypos tooltip[2]  

    #####################################################################
    #                SHIP
    #####################################################################
    $ l = GAME.getSpaceLoc()
    $ xCoord = l.coord[0]
    $ yCoord = l.coord[1]
    imagebutton auto "02_locations/ico GUIShip_%s.png" focus_mask True  xpos xCoord+84 ypos yCoord+64 xalign 0.5 yalign 0.5 action Return(["ship", None]) tooltip ["Ship", xCoord+112,yCoord+80 ]
    vbox  xalign 0.5 yalign 0.95:
        text "X = Return To Ship / P = Missions & Quests / B = Back to Station / Due Missions: Click on Location with Red '!' Symbol" size FSIZE_MED
        
    #OhWee_mod_code
    
    textbutton "SHIP STATS" text_style "text_std" action ToggleVariable("showshipstats") xpos 25 ypos 15
            
    if showshipstats and GAME.questSys.isActive("QID_INTRO_ENGINE"): # CR-0597
                # SUBSYSTEMS
        $ sysSummary = GAME.ship.getSubSysSummary()
        $ sysName = {
                     "CA": "Cargo", 
                     "EN": "Engine",
                     "HY": "H.Drive", 
                     "LA": "Launcher",
                     "MI": "M.Laser",
                     "SH": "Shields", 
                     "UP": "Uplink", 
                     "WE":"Weapon"
                    }
        vbox xpos 20 ypos 75:
          vpgrid:
            cols 2 
            spacing 5 
            margin 0,0
            for i in range(len(sysSummary)):
                #if i < len(sysSummary):
                    frame xsize 130 ysize 26 background Solid("#0088FF35"): #Solid("#88888888") padding 0,0 margin 0,0
                        text sysName[sysSummary[i][0]] size 18
                        text sysSummary[i][1] size 20 xpos 80 yoffset -2
                #else:
                    #frame xsize 150 ysize 35 background Solid("#00000000")
                        
          if not GAME.ship.subSys["launcher"][0] == False and GAME.guiInt["ship_stats"]:
            $ maxLoadout = GAME.ship.getLoadoutMax("launcher")
            $ addOns = GAME.ship.getAddOns("launcher")
            hbox spacing 8 yoffset 6:
                for i in range(6):
                    if maxLoadout > i:
                        frame xsize 36 ysize 36 background Solid("#00000088"):
                            image "03_minigames/ico_slot_subunit.png" xalign 0.5 yalign 0.5 zoom 0.375
                            if khelara in GAME.crew:
                                button action Return(["managetorploadout2", "launcher", i, addOns[i]])
                            if addOns[i]:
                                image "08_items/ico {}.png".format(addOns[i].ID) xalign 0.5 yalign 0.5 zoom 0.125

        # HULL
        frame xsize 64 ysize 64 background Solid("#00000000") xpos 150 ypos -1:
            $ hull = GAME.ship.getHullState()
            image "05_gui/hull_ship.png" xalign 0.5 yalign 0.5 zoom 0.125
            for i in hull.keys():
                image "05_gui/hull_{}_{}.png".format(i, hull[i]) xalign 0.5 yalign 0.5 zoom 0.125
                
            if "red" in hull.values():
                image "05_gui/ico_attention_256x256.png" xpos -3 ypos -10 zoom 0.25
        text "{:,} GW".format(round(GAME.ship.getTotalAblation_NEW(),1)) xpos 215 ypos 40 size 18
                                
    #End OhWee_mod_code
                                    
                                    
    #####################################################################
    #              SPECIAL COMMANDS
    #####################################################################
    key "b" action Return(["loc", starSys.locs[station]])
    key "x" action Return(["ship", None])
    key "p" action Return(["quest_help", None])

    # if player has hyperdrive and owns active voron gate
    if GAME.ship.hasSubSysType("ITMHyperdriveVoron") and GAME.ship.getSubSysStatus("hyperdrive") > 99 and GAME.surfaces["SUIDTenaris"].elems["SEIDTenarisGate"].found:
        key "j" action Return(["jump_to_base", None])
        fixed pos 1775,-15:
            imagebutton auto "05_gui/ico_nav_beacon2_%s.png" action Return(["jump_to_base", None])
            text "Deploy Beacon &\n     go to Tenaris Base (J)" size 20 pos -90,85 # CR-0860

label sandbox_space():
    # prep scene
    $ transition = False
    scene nav_screen_smart with fade
    play music "audio/{}".format(GAME.getStarSys().ambient) fadein 3.0

    show screen header()
    $ GAME.ship.status = "in space"
    $ GAME.setLocID("LOCSpace") # DEPRECATED
    $ GAME.getStarSys().visited = True

    # nav screen loop
    while True:

        ##################################################################### # CR-0342
        #					REFRESH BACKGROUND		                          # CR-0342
        ##################################################################### # CR-0342
        scene nav_screen_smart

        #####################################################################
        #					REFRESH VISIBLE MISSION POINTS		
        #####################################################################
        $ GAME.missionSys.markMissionLocs(GAME.getStarSys().ID)
        # $ navPoints = [x for x in GAME.getStarSys().locs if "Rendezvous" in x]
        # $ missionPoints = [x.sLocID for x in GAME.missionSys.missions]
        # # $ dueMissionPoints = [x.sLocID for x in GAME.missionSys.getDueMissions() if (x.kind == "bounty" or x.due == GAME.day)]

        # python:
        #     for i in navPoints:
        #         if i in dueMissionPoints:
        #             GAME.getSpaceLoc(i).found = True 
        #         else:
        #             GAME.getSpaceLoc(i).found = False 

        #     if GAME.questSys.inProgress("QID_MULT_FIND"):
        #         GAME.getSpaceLoc("LIDRendezvous75").found = True
        #         dueMissionPoints.append("LIDRendezvous75")
        #     if GAME.questSys.inProgress("QID_MULT_TRANSPORT"):  
        #         GAME.getSpaceLoc("LIDRendezvous50").found = True
        #         dueMissionPoints.append("LIDRendezvous50")
        #     if GAME.questSys.inProgress("QID_SERAPHINE_ARELLARTI_FIND"):  
        #         GAME.getSpaceLoc("LIDRendezvousArellarti25").found = True
        #         dueMissionPoints.append("LIDRendezvousArellarti25")    
        #     if GAME.questSys.inProgress("QID_KRELL_INTERCEPT"):  
        #         GAME.getSpaceLoc("LIDRendezvousArellarti25").found = True
        #         dueMissionPoints.append("LIDRendezvousArellarti25")    
        #     if GAME.questSys.inProgress("QID_KRELL_VORON_LOM"):  
        #         GAME.getSpaceLoc("LIDRendezvousArellarti25").found = True
        #         dueMissionPoints.append("LIDRendezvousArellarti25")    
        #     if GAME.questSys.inProgress('QID_KRELL_YLYEE_PACKAGE'):
        #         GAME.getSpaceLoc("LIDRendezvousArellarti50").found = True
        #         dueMissionPoints.append("LIDRendezvousArellarti50")    
        #     if GAME.questSys.inProgress('QID_MAIN_QUTHOR_CONTACT'):
        #         GAME.getSpaceLoc("LIDRendezvousQuthor75").found = True
        #         dueMissionPoints.append("LIDRendezvousQuthor75")  
        #     if GAME.questSys.inProgress("QID_MAIN_SWARMMODULE_B"):  
        #         GAME.getSpaceLoc("LIDRendezvousArellarti25").found = True
        #         dueMissionPoints.append("LIDRendezvousArellarti25") 

        #     # ===== CR-0428 / CR-0430 START =====
        #     # multiverse prod presence
        #     if os.path.exists(GAME.podDir+"/multiverse_pod.json") and "pod_retrieved" not in GAME.tags:
        #         GAME.tags.append("pod_located")
        #         GAME.getSpaceLoc("LIDRift").found = True
        #     else:
        #         GAME.getSpaceLoc("LIDRift").found = False
        #     # ===== CR-0428 / CR-0430 END =====

        #####################################################################
        #					CHECK FOR ACHIEVEMENTS, IN-SPACE REPORTS, ETC		
        #####################################################################
        if GAME.mc.getTally("Eliminated Ships") >= 30 and not GAME.mc.hasAchievement("combat veteran"):
            call achievement_notify(GAME.mc, "combat veteran") from _call_achievement_notify_8 
        if GAME.mc.getTally("Eliminated Seekers") >= 50 and not GAME.mc.hasAchievement("seeker hunter"):
            call achievement_notify(GAME.mc, "seeker hunter") from _call_achievement_notify_9 
        if GAME.mc.getTally("Mined (t)") >= 1000 and not GAME.mc.hasAchievement("mining tycoon"):
            call achievement_notify(GAME.mc, "mining tycoon") from _call_achievement_notify_10 
        
        #####################################################################
        #              NAV SCREEN
        #####################################################################

        $ dueMissionPoints = [x.sLocID for x in GAME.missionSys.getDueMissions()]
        call screen sandbox_space_scr(dueMissionPoints)
        play sound "audio/click.wav"

        #####################################################################
        #					RETURN TO SHIP		
        #####################################################################
        if "ship" in _return:
            $ GAME.setLocID("LOCBridge")
            $ transition = ["transition", GAME.locs["LOCBridge"]]
            #call sandbox_interior_prepare_scene()
            return(transition)
        #####################################################################
        #              QUEST HELP xxx
        #####################################################################
        elif "quest_help" in _return:
            call quest_help("missions") from _call_quest_help
            show screen header()
        #####################################################################
        #              HYPERJUMP TO BASE
        #####################################################################
        elif "jump_to_base" in _return:
            if not any([x == GAME.items["ITMBeacon"] for x in GAME.ship.getAddOns("hyperdrive")]):
                queue sound "audio/tech_fail.wav"
                "Navigation Control" "\"No Beacons equipped in Hyperdrive.\""
            elif GAME.hour > 20:
                mc "\"I should do that when I'm better rested...\""
            else:
                queue sound "audio/load.wav"
                "You deploy an Anchor Beacon and get ready for a Hyperjump..."
                # animation
                queue sound "audio/teleport.wav"
                scene expression("05_gui/hyperjump.png") with blueflash
                $ n = 5
                while n:
                    $ n -= 1 
                    queue sound "audio/teleport.wav"
                    scene expression("05_gui/hyperjump.png") with vpunch 
                play sound "audio/explode.wav"     
                # deploy one beacon
                $ GAME.ship.beacon = GAME.getSpaceLoc().ID
                $ beacons = GAME.ship.getAddOns("hyperdrive")
                $ slotNum = beacons.index(GAME.items["ITMBeacon"])
                $ GAME.ship.removeAddOn("hyperdrive", slotNum)

                # Set StarSys and SpaceLoc
                $ jumpFromSys = GAME.getStarSys().ID # CR-0747
                $ GAME.ship.starSysID = "SSIDIltari"
                $ GAME.setSpaceLocID("LIDTenaris")

                scene space_bg_smart with fade

                if jumpFromSys == "SSIDArellarti":
                    call arellarti_leave() from _call_arellarti_leave_1 

                # Sandbox to surface   
                $ surface = GAME.surfaces["SUIDTenaris"]
                call hour_passes() from _call_hour_passes_68 
                return(["transition", surface])      
                
        #####################################################################
        #     OhWeeMod_ShipStats
        #####################################################################
        
            
        elif "managetorploadout2" in _return:
            $ subSysKey = _return[1]
            $ slot = _return[2]
            $ equipped = _return[3]
            # addon selection
            if equipped:
                $ result = GAME.ship.unEquipAddOn(subSysKey, slot)
                if result:
                    play sound "audio/install.wav"
                else:
                    play sound "audio/tech_fail.wav"
            else:
                show image "room_engine_smart"
                call item_show(GAME.ship.cargo, ["module"], "CARGO - ADDON MODULES") from _call_item_show_556 
                hide image "room_engine_smart"                 
                $ item = _return 

                if _return:
                    # paranoid duplicate pointer cleanup (from bad patch)
                    $ itemScrubbed = item.scrub() # WIP 1.60 Cleanup
                    if itemScrubbed in GAME.ship.supportedAddOns(subSysKey): # WIP 1.60 Cleanup
                        $ GAME.ship.equipAddOn(subSysKey, item.ID, slot)
                        $ GAME.ship.cargo.remove(item)
                        play sound "audio/install.wav"
                    else:
                        play sound "audio/tech_fail.wav"            

        #####################################################################
        #              SPACE LOCS
        #####################################################################
        elif "loc" in _return:
            $ spaceLoc = _return[1]
            #####################################################################
            #                NAV AND ENGINE INTERCEPTS
            #####################################################################

            if GAME.ship.getSubSysStatus("engines") < 0.1:
                play sound "audio/tech_fail.wav"
                "Navigation Control" "\"Engines are inoperative.\""
                if not  GAME.mc.hasDone("engines inoperative"):
                    mc "\"I better have a look at that engine configuration...\""
                call quest_updater() from _call_quest_updater_182 

            elif GAME.ship.getSubSysStatus("engines") < spaceLoc.zone:
                play sound "audio/tech_fail.wav"
                "Navigation Control" "\"Destination cannot be reached with current engine performance.\""
                if not GAME.mc.hasDone("refuse navigate"):
                    mc "\"I better earn some money and upgrade my engines...\""

                call quest_updater() from _call_quest_updater_183 

            elif GAME.ship.cargoLoaded() > GAME.ship.cargoLimit():
                play sound "audio/tech_fail.wav"
                "Navigation Control" "\"Ship overloaded. Adjust your cargo.\""
                if not GAME.mc.hasDone("refuse_overload"):
                    mc "\"I better get rid of some cargo items first...\""

            #####################################################################
            #					MISSION CHECK		
            #####################################################################
            elif GAME.missionSys.getLocActive(spaceLoc.ID) and spaceLoc.ID == GAME.ship.spaceLocID:
                $ mission = GAME.missionSys.getLocActive(spaceLoc.ID)

                # Transport Mission
                if mission.kind in ["transport", "smuggling"]:
                    if eval(mission.cond):
                        call mission_scripts(mission, "on_complete") from _call_mission_scripts 
                        $ GAME.missionSys.purgeMission(mission)  
                        if "veronica" in mission.ID.lower():
                            $ GAME.mc.done.append("mission_veronica")

                # Bounty Mission 
                elif mission.kind == "bounty" and GAME.hour > 20:
                    mc "\"I should tackle that bounty when I am better rested tomorrow...\""

                elif mission.kind == "bounty":
                    queue sound "audio/notify.wav"
                    call simple_notify("BOUNTY MISSION", "Locating hostiles...", ["Engage", "Abort"], "05_gui/ico_gui_hostile_human.png", "red") from _call_simple_notify_86 
                    if _return == "Engage":
                        hide screen header
                        call mg_combat_scenario(mission.attr["mProfile"]) from _call_mg_combat_scenario_3 
                        $ result = _return
                        if "victory" in result: # EXP returned
                            $ damage = result[1]
                            $ exp = result[2]
                            queue sound "audio/triumph.wav"
                            call simple_notify("VICTORY", "+[exp:,] EXP gained", ["Continue"], "05_gui/ico_gui_cup.png") from _call_simple_notify_87 
                            queue sound "audio/click.wav"            
                            $ GAME.mc.exp += exp
                            call attr_mod(GAME.mc, "NOT", 1, 20, 100, True) from _call_attr_mod_71 
                            call mission_scripts(mission, "on_complete") from _call_mission_scripts_1 
                            $ GAME.missionSys.purgeMission(mission) 
                            $ GAME.mc.hasDone("first_bounty") # CR-0264
                            $ GAME.mc.tallyUp("Bounty Missions",1)
                            
                        else:
                            $ damage = result[1]
                            "You decide to try your luck another time..."
                            call attr_mod(GAME.mc, "NOT", -1, 0, 100, True) from _call_attr_mod_72 

                        if damage:  
                            queue sound "audio/notify.wav"
                            call simple_notify("DAMAGE REPORT", "Subunits lost: {}".format(len(damage)), ["Continue"], "05_gui/ico Ship.png") from _call_simple_notify_88 
                            queue sound "audio/click.wav"   
                        show screen header()
                    call quest_updater() from _call_quest_updater_184 
                    call hour_passes() from _call_hour_passes_69 

            #####################################################################
            #              SPECIAL / LOCATION INTERCEPTS / NO ACCESS
            #####################################################################
            elif spaceLoc.ID in ["LIDStationXenos", "LIDLibraryXenos", "LIDXenos"] and "expo_library_ylyee" not in ylyee.done:
                queue sound "audio/beep.wav"
                "Navigation Control" "\"Xenos Inner System Access Not Authorized.\""
                if not GAME.mc.hasDone("xenos_rejected"):
                    queue sound "audio/drone_beep.wav"
                    bb2 "\"The Vorons do not allow Outsiders into their Inner Systems...\""
                    bb2 "\"They maintain a precarious balance among various Factions...\""
                    bb2 "\"Outsider presence is seen as a complicating factor...\""
                    mc "\"How can we gain access?\""
                    bb2 "\"Ylyee brought us here.\""
                    bb2 "\"I suggest we wait until word of our arrival has spread...\""
                    bb2 "\"The Vorons knew we are here the moment we exited the Gate...\""
                    mc "\"I see...\""
                    bb2 "\"Maybe we can explore accessible locations and make some profits in the meantime...\""
                    mc "\"Agreed.\""
                    $ GAME.timerSet("T_XENOS_WAIT",1)
                    call quest_updater() from _call_quest_updater_185 
                    call quest_updater() from _call_quest_updater_186 

            elif spaceLoc.ID in ["LIDStationNX010"] and "swarm_barrier" not in vee.done:
                queue sound "audio/notify.wav"
                v "\"The Interdimensional Field around the Nexus cannot be penetrated.\""
                v "\"It negates all known Spacedrive Technology.\""
                mc "\"How are Swarm Ships traversing it?\""
                v "\"Sections of the Field can be deactivated by the Nexus.\""
                mc "\"I see...\""


            #####################################################################
            #              SPECIAL / LOCATION INTERCEPTS 
            #####################################################################

            elif spaceLoc.ID == "LIDLibraryXenos" and not all(GAME.mc.hasItem(x) for x in ["ITMMapPrecursorIltari", "ITMMapPrecursorArellarti"]) and not GAME.questSys.isActive("QID_XENOS_LIBRARY_MISSION"):
                mc "\"Ylyee said I need the Map Fragments from Arellarti and Iltari first...\""
                mc "\"Otherwise the Library can't help me with the Analysis....\""

            elif spaceLoc.ID == "LIDLibraryXenos" and GAME.ship.spaceLocID == "LIDLibraryXenos" and GAME.questSys.inProgress ('QID_MAIN_QUTHOR_MAP3'): 
                call cutscene_quthor("library_quthor_map") from _call_cutscene_quthor_17 

            elif spaceLoc.ID == "LIDLibraryXenos" and GAME.ship.spaceLocID == "LIDLibraryXenos" and GAME.questSys.inProgress ('QID_MAIN_SWARM5THMAP'): 
                call cutscene_quthor("library_nx010_map") from _call_cutscene_quthor_18 

            elif spaceLoc.ID == "LIDLibraryXenos" and GAME.ship.spaceLocID == "LIDLibraryXenos":
                if 'archive_task_assigned' not in kythera.done:
                    call cutscene("briefing_library") from _call_cutscene_28 
                    return(["transition", GAME.locs["LOCHallway1"]])
                elif "mission_debrief" in kythera.done:
                    mc "\"I wouldn't know what to do there now...\""
                elif not all([GAME.mc.hasItem(x) for x in ["ITMMapPrecursorIltari", "ITMMapPrecursorArellarti", "ITMMapPrecursorXenos"] ]): # CR-1095
                    mc "\"I better have all three Map Fragments ready before reporting back.\"" 
                # ===== CR-0691 START    
                elif GAME.hour >= 18:
                    mc "\"It's late.\""
                    mc "\"I better go there tomorrow...\""
                # ===== CR-0691 END
                else:
                    call cutscene("debrief_library") from _call_cutscene_29 
                    queue sound "audio/teleport.wav"
                    return(["transition", GAME.locs["LOCHallway1"]])

            elif spaceLoc.ID == "LIDRendezvousQuthor75" and GAME.ship.spaceLocID == "LIDRendezvousQuthor75" and GAME.questSys.inProgress('QID_MAIN_QUTHOR_CONTACT'):
                queue sound "audio/notify.wav"
                mc "\"No one here yet...\""
                mc "\"I should spend a night here and wait...\""

            # CR-0962 START ==============
            elif spaceLoc.ID == "LIDRendezvousArellarti25" and GAME.ship.spaceLocID == "LIDRendezvousArellarti25" and GAME.questSys.inProgress('QID_MAIN_SWARMMODULE_A'):
                queue sound "audio/notify.wav"
                mc "\"Here we are...\""
                queue sound "audio/notify.wav"
                khe "\"Let's attack the Site by force and get the Gate Module...\""
                khe "\"As payback for those uniforms...\""
                queue sound "audio/notify.wav"
                tri "\"Your emotions are misguided...\""
                tri "\"It is better to have the infiltrator retrieve it by stealth...\""
                mc "\"Hmmm....\""
                call large_notify("THE KRELL MILITARY SITE", "In order to retrieve the Gate Module, you could attack the Krell Site by force...\n\nIt will certainly be well defended.", ["Attack", "Reconsider"], "05_gui/ico_gui_quest.png", "green" ) from _call_large_notify_46 
                if _return == "Attack":
                    mc "\"Luck favours those prepared...\""
                    queue sound "audio/alert.wav"
                    mc "\"Get ready for combat!\""
                    hide screen header # CR-1005
                    call mg_combat_scenario("the_gate_module") from _call_mg_combat_scenario_4 
                    show screen header() # CR-1005
                    

            # CR-0962 END ================


            #####################################################################
            #					MISSION CHECK		
            #####################################################################
            elif GAME.missionSys.getLocActive(spaceLoc.ID) and spaceLoc.ID == GAME.ship.spaceLocID:
                $ mission = GAME.missionSys.getLocActive(spaceLoc.ID)

                # Transport Mission
                if mission.kind in ["transport", "smuggling"]:
                    if eval(mission.cond):
                        call mission_scripts(mission, "on_complete") from _call_mission_scripts_2 
                        $ GAME.missionSys.purgeMission(mission)  
                        if "veronica" in mission.ID.lower():
                            $ GAME.mc.done.append("mission_veronica")

                # Bounty Mission 
                elif mission.kind == "bounty":
                    queue sound "audio/notify.wav"
                    call simple_notify("BOUNTY MISSION", "Locating hostiles...", ["Engage", "Abort"], "05_gui/ico_gui_hostile_human.png", "red") from _call_simple_notify_89 
                    if _return == "Engage":
                        hide screen header
                        call mg_combat_scenario(mission.attr["mProfile"]) from _call_mg_combat_scenario_5 
                        $ result = _return
                        if "victory" in result: # EXP returned
                            $ damage = result[1]
                            $ exp = result[2]
                            queue sound "audio/triumph.wav"
                            call simple_notify("VICTORY", "+[exp:,] EXP gained", ["Continue"], "05_gui/ico_gui_cup.png") from _call_simple_notify_90 
                            queue sound "audio/click.wav"            
                            $ GAME.mc.exp += exp
                            call attr_mod(GAME.mc, "NOT", 1, 20, 100, True) from _call_attr_mod_73 
                            call mission_scripts(mission, "on_complete") from _call_mission_scripts_3 
                            $ GAME.missionSys.purgeMission(mission) 
                            $ GAME.mc.hasDone("first_bounty") # CR-0264
                            $ GAME.mc.tallyUp("Bounty Missions",1)
                            
                        else:
                            $ damage = result[1]
                            "You decide to try your luck another time..."
                            call attr_mod(GAME.mc, "NOT", -1, 0, 100, True) from _call_attr_mod_74 

                        if damage:  
                            queue sound "audio/notify.wav"
                            call simple_notify("DAMAGE REPORT", "Subunits lost: {}".format(len(damage)), ["Continue"], "05_gui/ico Ship.png") from _call_simple_notify_91 
                            queue sound "audio/click.wav"   
                        show screen header()

                    call quest_updater() from _call_quest_updater_187 
                    call hour_passes() from _call_hour_passes_70 


            #####################################################################
            #                MINING
            #####################################################################
            elif spaceLoc.ID in ["LIDAsteroidsOuter"] and not GAME.ship.hasSubSysType("ITMMiningMkII"):
                mc "\"I need at least a Mining Laser MkII to mine this Field...\""

            elif spaceLoc.ID in ["LIDRubbleIltari", "LIDAsteroidsIltari", "LIDAsteroidsOuter", "LIDAsteroidsArellarti", "LIDFieldsXenos", "LIDBurningFields", "LIDExpanse", "LIDElementalFields"] and spaceLoc.ID == GAME.ship.spaceLocID :
                $ mChoice = False
                # Mining Intercepts
                if GAME.questSys.inProgress("QID_PIRATE_TASK") and spaceLoc.ID == "LIDAsteroidsIltari":
                    queue sound "audio/notify.wav"
                    call large_notify("GHAD THE RENEGADE", "From the information Vigo provided, you are able to locate the renegade pirate in the Asteroid Field.\n\nDo you want to confront him?", ["Confront", "Abort", "Mining"], "05_gui/ico Ship.png", "orange") from _call_large_notify_47 
                    if _return == "Abort":
                        $ mChoice = True
                    elif _return == "Confront":
                        hide screen header
                        call mg_combat_scenario("renegade_ghad") from _call_mg_combat_scenario_6 
                        $ mChoice = True
                        show screen header()
                        call hour_passes() from _call_hour_passes_71 
            
                # Infiltrator
                elif GAME.questSys.inProgress("QID_NIMHE_RETRIEVE_KICKOFF") and spaceLoc.ID == "LIDAsteroidsOuter":
                    queue sound "audio/notify.wav"
                    call large_notify("THE LOST MILITARY BASE", "From the information Nimhe provided, you are able to locate the military research station among the asteroids.\n\nDo you want to explore it?", ["Explore", "Abort", "Mining"], "05_gui/ico Ship.png", "orange") from _call_large_notify_48 
                    if _return == "Abort":
                        $ mChoice = True
                    elif _return == "Explore":
                        hide screen header
                        call cutscene_nimhe("shell_find") from _call_cutscene_nimhe_20 
                        call hour_passes() from _call_hour_passes_72 
                        $ mChoice = True
                        scene nav_screen_smart with fade
                        show screen header()

                # infiltrator escape noob recovery:
                elif GAME.questSys.isDone("QID_NIMHE_RETRIEVE_KICKOFF") and spaceLoc.ID == "LIDAsteroidsOuter" and not GAME.tallyInfiltrators() and GAME.questSys.isDone("QID_NIMHE_RETRIEVE_INFORM"): # CR-2014
                    queue sound "audio/beep.wav"
                    bb2 "\"Captain [GAME.mc.name], might I suggest to look for another Infiltraor Shell here?\""
                    mc "\"How so?\""
                    bb2 "\"We have lost our Infiltrator a while ago...\""
                    mc "\"Ah, right...\""
                    mc "\"Let's scour the Military Facility once more...\""
                    "Searching the wreckage of the Facility you locate a discarded I-Shell!"
                    "It is of lower quality but might serve your purpose..."
                    $ part = GAME.sbPartsData["SBPShell2TypeI"].clone({"pref": "subpar"}) # CR-1072
                    queue sound "audio/notify.wav"
                    call simple_notify("ITEM FOUND", "Subpar Infiltrator Shell", ["Continue"], "03_minigames/ico SBPShell2TypeI.png", "red") from _call_simple_notify_92 
                    queue sound "audio/load.wav"
                    $ GAME.lab.parts.append(part)
                    mc "\"Let's make sure we don't lose that again...\""


                elif GAME.questSys.inProgress("QID_QUTHOR_MOIRA_VISIT") and spaceLoc.ID == "LIDAsteroidsOuter":
                    stop music fadeout 2.0
                    queue sound "audio/notify.wav"
                    call large_notify("THE ELUSIVE DOC", "From the information Khelara provided, you are able to locate the Research Facility among the asteroids.\n\nDo you want to contact it?", ["Contact", "Abort", "Mining"], "05_gui/ico Ship.png", "orange") from _call_large_notify_49 
                    if _return == "Abort":
                        $ mChoice = True
                    elif _return == "Contact":
                        hide screen header
                        call cutscene_quthor("moira_contact") from _call_cutscene_quthor_19 
                        call hour_passes() from _call_hour_passes_73 
                        $ mChoice = True
                        scene nav_screen_smart with fade
                        show screen header()

                elif GAME.questSys.inProgress("QID_QUTHOR_MOIRA_GEAR") and spaceLoc.ID == "LIDAsteroidsOuter":
                    stop music fadeout 2.0
                    queue sound "audio/notify.wav"
                    call large_notify("THE ELUSIVE DOC", "You have promised Dr. Morgan to return with the specified amount of Krell Bio Wares.\n\nDo you want to contact her?", ["Contact", "Abort", "Mining"], "05_gui/ico Ship.png", "orange") from _call_large_notify_50 
                    if _return == "Abort":
                        $ mChoice = True
                    elif _return == "Contact":
                        hide screen header
                        call cutscene_quthor("moira_pickup") from _call_cutscene_quthor_20 
                        call hour_passes() from _call_hour_passes_74 
                        $ mChoice = True
                        scene nav_screen_smart with fade
                        show screen header()

                elif spaceLoc.ID == "LIDElementalFields" and "intro_ele_fields" not in GAME.mc.done:
                    queue sound "audio/notify.wav"
                    $ GAME.mc.hasDone("intro_ele_fields")
                    khe "\"This site looks like the remains of a disintegrated planet...\""
                    queue sound "audio/notify.wav"
                    v "\"Data indeed indicates a planet was moved to this location and dismantled...\""
                    tri "\"No doubt to serve as raw material for constructing this System... \""
                    mc "\"That is some impressive Technology...\"" # CR-2037
                    mc "\"Imagine moving a whole planet through Intergalactic Space...\""
                    v "\"Precursor Technology was formidable...\""
                    mc "\"Let's have a look at the Asteroids then...\""
                    mc "\"I bet there is all kinds of material to be found here...\"" # CR-2037
                #  Mining
                if mChoice:
                    pass               
                elif GAME.ship.getSubSysStatus("mining") <= 0.0:
                    play sound "audio/beep.wav"
                    "Ship Control" "\"Mining laser is offline.\""
                elif GAME.hour >= 18:
                    mc "\"I should resume that, when I am better rested...\""
                else:
                    #hide screen header
                    call mg_mining_pick(spaceLoc.name.upper()) from _call_mg_mining_pick 
                    call hour_passes(18-GAME.hour) from _call_hour_passes_75 

            #####################################################################
            #                MULTIVERSE POD
            #####################################################################
            elif spaceLoc.ID in ["LIDRift"] and spaceLoc.ID == GAME.ship.spaceLocID :
                #hide screen header
                hide screen header
                call multiverse_manager("retrieve") from _call_multiverse_manager_1 
                show screen header

            #####################################################################
            #                HYPERGATE
            #####################################################################
            elif spaceLoc.ID in ["LIDGateQuthor"] and GAME.questSys.inProgress("QID_MAIN_SWARMGATE") and spaceLoc.ID == GAME.ship.spaceLocID:
                call cutscene_quthor("gate_analyze") from _call_cutscene_quthor_21 

            elif spaceLoc.ID in ["LIDGateQuthor"] and GAME.questSys.inProgress("QID_MAIN_SWARMGATE_REPAIR") and spaceLoc.ID == GAME.ship.spaceLocID:
                call cutscene_quthor("gate_repair") from _call_cutscene_quthor_22 

            elif spaceLoc.ID in ["LIDGateIltari", "LIDGateArellarti", "LIDGateXenos", "LIDGateQuthor", "LIDGateNX010", "LIDGateWaystation"] and spaceLoc.ID == GAME.ship.spaceLocID :  # CR-0698  
            
                if "gate_talk" not in tris.done:
                    mc "\"I'm not sure I should venture out ...\""
                    # vee not awoken or in crew
                    if GAME.questSys.isDone("QID_VEE_PASSENGER") and not GAME.questSys.isDone("QID_VEE_FAMILIARIZE"):
                        mc "\"I better learn more about Vee first...\""
                    # someone else missing
                    elif not all([x in GAME.crew for x in [nimhe, vee, khelara]]): 
                        mc "\"I have the feeling my crew is not complete yet...\""

                    # vee hasn't reported on seraphine yet
                    elif not GAME.questSys.isActive('QID_VEE_TRAIN'): 
                        mc "\"I should wait a few days until Vee is familiar with our ship...\""

                    # vee training not started
                    elif not GAME.questSys.isDone('QID_VEE_TRAIN'): 
                        mc "\"I should get to know Vee a bit better first...\""
                        mc "\"Maybe some light training might help...\""

                    # ready
                    elif GAME.questSys.isActive('QID_SERAPHINE_KICKOFF'):
                        mc "\"I am ready to move beyond Iltari...\""
                        mc "\"I should talk to T'Ris.\""
                    # vee not found or some other basic thing
                    else:
                        mc "\"I better find out more about this system first...\""

                elif not GAME.ship.hasSubSys("hyperdrive"):
                    queue sound "audio/drone_beep.wav"
                    bb2 "\"We need a Hyperdrive Subsystem to use the Gate, Captain [GAME.mc.name].\""
                    mc "\"Right.\""
                    mc "\"I better buy one then.\""
                    bb2 "\"Make sure to fully configure it.\""
                    bb2 "\"Hyperdrives need full power to use the Gate.\""
                    mc "\"Understood.\""

                elif GAME.ship.getSubSysStatus("hyperdrive") < 99: # paranoid boundary 
                    queue sound "audio/drone_beep.wav"
                    bb2 "\"We need our Hyperdrive Subsystem at 100 percent to use the Gate, Captain [GAME.mc.name].\""
                    bb2 "\"Otherwise we might end up lost in Hyperspace...\""
                    mc "\"Right, I forgot.\""

                elif not GAME.questSys.isDone('QID_SERAPHINE_CLASS_TRIS'):
                    queue sound "audio/beep.wav"
                    "Jumpgate Control" "\"Jumpgate Access Declined.\""
                    mc "\"Arrgghh....!\""
                    "Jumpgate Control" "\"You do not possess the required [C_HI_B]Hyperjump License.[C_HI_E]\""
                    if not GAME.mc.hasDone("hypergate_reject"):
                        mc "\"Where can I obtain such a License?\""
                        "Jumpgate Control" "\"Hyperjump Licenses are issued at Iltari Station Administration.\""
                    "Jumpgate Control" "\"Iltari Gate Control Out.\""
                    call quest_updater() from _call_quest_updater_188 

                elif GAME.hour > 17:
                    mc "\"I should do that when I am better rested.\""

                else:   
                    call navigate_galaxy() from _call_navigate_galaxy 

            #####################################################################
            #                WAYPOINTS / QUEST STUFF
            #####################################################################
            elif spaceLoc.ID == "LIDRendezvous75" and GAME.questSys.inProgress("QID_MULT_FIND") and spaceLoc.ID == GAME.ship.spaceLocID:
                scene space_bg_smart
                show image "05_gui/mask_cockpit_space.png"                 
                mc "\"Now let's see whether we can find that crate...\""
                call simple_notify("SCANNING", "You scan the area...", ["Continue"], "05_gui/ico Ship.png") from _call_simple_notify_93 
                queue sound "audio/success.wav"
                $ item = GAME.items["ITMCrateLiquor"]
                call find_notify(item, "ITEM FOUND") from _call_find_notify_47 
                queue sound "audio/load.wav"
                $ GAME.setLocID("LOCCargo")
                mc "\"Let's have a look at what we found...\""  
                scene room_cargo_smart with fade 
                "You open the crate in the cargobay..."
                $ item = GAME.items["ITMLiquorVortex"] 
                call find_notify(item, "ITEM FOUND", 5) from _call_find_notify_48 
                $ GAME.mc.hasDone("vortex_found")
                mc "\"Looks mighty expensive...\""
                mc "\"Let's bring that back to Ylyee...\""
                call quest_updater() from _call_quest_updater_189 
                $ GAME.mc.inventory += [item]*5
                call sandbox_interior_navigate_to("LOCBridge") from _call_sandbox_interior_navigate_to_81 
                #$ GAME.getStarSys().locs["LIDRendezvous75"].found = True
                return(["transition", GAME.locs["LOCBridge"]]) # CR-0590

            elif spaceLoc.ID == "LIDRendezvous50" and GAME.questSys.inProgress("QID_MULT_TRANSPORT") and spaceLoc.ID == GAME.ship.spaceLocID and "escort" in ylyee.status: # CR-0382
                scene expression("05_gui/mask_cockpit_space.png") with fade 
                mc "\"Let's scan for crafts in the vicinity...\"" 
                queue sound "audio/teleport.wav"
                scene expression("06_cutscenes/cutscene_voronian_cruiser_two.png") with dissolve
                mc  "\"Whoaaa...\""
                queue sound "audio/beep.wav"
                "Voronian Cruiser" "\"This is Imperial Voronian Cruiser Lagdash.\""
                "Voronian Cruiser" "\"Hand over her Exalted Highness immediately!\""
                mc "\"Highness?\"" 
                yly "\"That's me.\"" 
                mc "\"I thought you were some kind of Diplomat?\""
                yly "\"In a sense...\"" 
                yly "\"Lagdash, stand down and prepare for transport.\""
                "Voronian Cruiser" "\"Affirmative.\""
                yly "\"You have been of great service to me.\""
                yly "\"Accept this as a token of my gratitude.\""
                $ item = GAME.items["ITMMultiPod"]
                queue sound "audio/success.wav"
                call find_notify(item, "You receive ") from _call_find_notify_49 
                $ GAME.mc.inventory.append(item)
                mc "\"What is that?\""
                yly "\"A mysterious and powerful device...\""
                yly "\"It can extend itself through the Multiverse...\""
                mc "\"Through what?\""
                yly "\"Use it, when you are ready.\""
                mc "\"Ready?\""
                yly "\"You will know.\"" 
                yly "\"Lagdash, ready to transport.\""
                queue sound "audio/teleport.wav"
                mc "\"Whoaa...\"" with blueflash 
                scene expression("05_gui/mask_cockpit_space.png") with dissolve 
                mc "\"That was odd...\"" 
                $ GAME.mc.hasDone('ylyee_escorted')
                $ ylyee.status.remove("escort") # CR-0382
                mc "\"I better store that pod safely until I am ready to use it.\"" 
                $ GAME.mc.exp += 1000                
                call quest_updater() from _call_quest_updater_190 
                call sandbox_interior_navigate_to("LOCBridge") from _call_sandbox_interior_navigate_to_82 
                #$ GAME.getStarSys().locs["LIDRendezvous50"].found = False
                return(["transition", GAME.locs["LOCBridge"]]) # CR-0590

            elif spaceLoc.ID == "LIDRendezvousArellarti25" and GAME.questSys.inProgress("QID_SERAPHINE_ARELLARTI_FIND") and spaceLoc.ID == GAME.ship.spaceLocID:
                queue sound "audio/notify.wav"
                call large_notify("RESCUE QUEST!", "Scanning the dense Asteroid Field for anomalous signatures, you locate the vessel of Princess Seraphine. A large group of Krell Lashers is searching nearby...\n\nWhat do you want to do?", ["Attack", "Withdraw"], "05_gui/ico_gui_quest.png", "orange") from _call_large_notify_51 
                if _return == "Withdraw":
                    $ mChoice = True
                    "You withdraw until you are better prepared..."
                elif _return =="Attack":
                    hide screen header
                    call mg_combat_scenario("rescue_seraphine") from _call_mg_combat_scenario_7 
                    $ mChoice = True
                    show screen header() 
                    call hour_passes() from _call_hour_passes_76 

            elif spaceLoc.ID == "LIDRendezvousArellarti25" and GAME.questSys.inProgress("QID_KRELL_INTERCEPT") and spaceLoc.ID == GAME.ship.spaceLocID:
                if GAME.hour >= 18:
                    mc "\"I should do that when I am better rested.\""
                else:
                    queue sound "audio/notify.wav"
                    call large_notify("INTERCEPT MISSION!", "Scanning the dense Asteroid Field you locate a vessel which is en route to Arellarti Station from Kranor Biolabs. \n\nWhat do you want to do?", ["Attack", "Withdraw"], "05_gui/ico_gui_quest.png", "orange") from _call_large_notify_52 
                    if _return == "Withdraw":
                        $ mChoice = True
                        "You withdraw until you are better prepared..."
                    elif _return =="Attack":
                        hide screen header
                        call mg_combat_scenario("intercept_merchant") from _call_mg_combat_scenario_8 
                        $ mChoice = True
                        show screen header() 
                        call hour_passes(18-GAME.hour) from _call_hour_passes_77 

            elif spaceLoc.ID == "LIDRendezvousArellarti25" and GAME.questSys.inProgress("QID_KRELL_VORON_LOM") and spaceLoc.ID == GAME.ship.spaceLocID:
                if GAME.hour >= 18:
                    mc "\"I should do that when I am better rested.\""
                else:
                    queue sound "audio/notify.wav"
                    call large_notify("INTERCEPT MISSION!", "Scanning the dense Asteroid Field you locate a convoy which is en route to Arellarti Station from Kranor Biolabs. \n\nWhat do you want to do?", ["Attack", "Withdraw"], "05_gui/ico_gui_quest.png", "orange") from _call_large_notify_53 
                    if _return == "Withdraw":
                        $ mChoice = True
                        "You withdraw until you are better prepared..."
                    elif _return =="Attack":
                        hide screen header
                        call mg_combat_scenario("intercept_convoy") from _call_mg_combat_scenario_9 
                        $ mChoice = True
                        show screen header() 
                        call hour_passes(18-GAME.hour) from _call_hour_passes_78 

            elif spaceLoc.ID == "LIDRendezvousArellarti50" and GAME.questSys.inProgress("QID_KRELL_YLYEE_PACKAGE") and spaceLoc.ID == GAME.ship.spaceLocID:
                queue sound "audio/notify.wav"
                "At the designated coordinates, you find a container drifting in space..."
                queue sound "audio/notify.wav"
                $ item = GAME.items["ITMShieldVoron"]
                call find_notify(item, "EQUIPMENT FOUND") from _call_find_notify_50 
                queue sound "audio/load.wav"
                $ GAME.ship.cargo.append(item)
                call quest_updater() from _call_quest_updater_191 

            #####################################################################
            #                DOCKING / TRANSITION
            #####################################################################

            elif spaceLoc.ID in ["LIDStationIltari"] and GAME.ship.spaceLocID == spaceLoc.ID and len([x for x in GAME.ship.cargo if not spaceLoc.isLegal(x.ID)]) > GAME.ship.cargoLimitCloak():
                play sound "audio/drone_beep.wav"
                bb2 "\"I recommend to not dock here.\""
                bb2 "\"You are carrying illegal wares which are not, ahem, cloaked.\""
                bb2 "\"You should eject them prior to docking.\""
                mc "\"Right...\""
                scene nav_screen_smart with fade

            elif spaceLoc.ID in ["LIDStationIltari"] and GAME.ship.spaceLocID == spaceLoc.ID:
                scene expression ("06_cutscenes/cutscene_station_one.png") with fade # CR-0847
                play sound "audio/beep.wav"
                $ response = "Proceed"
                if not GAME.mc.hasDone("docked iltari"):
                    call large_notify("{} Control".format(spaceLoc.name), "\"This is {} Control. Your Docking request has been received. Please standby for Docking Procedure.\n\nDocking fee will be 200 Credits.\"".format(spaceLoc.name), ["Proceed", "Abort"], "05_gui/ico_gui_station.png") from _call_large_notify_54 
                    $ response = _return

                if response == "Proceed":
                    if GAME.money < 200:
                        "You lack the required docking fees."
                        scene nav_screen_smart with fade
                    else:
                        scene expression ("06_cutscenes/cutscene_station_three.png") with fade # CR-0847
                        window hide
                        pause
                        play sound "audio/load.wav"
                        $ GAME.ship.status = "docked"
                        $ GAME.setLocID("LOCBridge")
                        call sandbox_interior_prepare_scene() from _call_sandbox_interior_prepare_scene_27 
                        call transaction("Docking Fees", -200, True) from _call_transaction_31 
                        if "first docking" not in GAME.mc.done:
                            play sound "audio/notify.wav"
                            tri "\"Well, you managed to get us here in one piece.\""
                            tri "\"Impressive.\""
                            tri "\"Thankfully, most ship functions are automated...\""
                            tri "\"I recommend you look for that map now.\""
                            tri "\"I shall continue my diagnostic of the Ship's systems.\""
                            $ GAME.mc.hasDone("first docking")
                        return(["transition", GAME.locs["LOCBridge"]]) # CR-0589

                elif _return == "Abort":
                    scene nav_screen_smart with fade

            elif spaceLoc.ID in ["LIDPirate"] and GAME.ship.spaceLocID == spaceLoc.ID:
                scene expression ("06_cutscenes/cutscene_pirate_hideout.png") with fade
                play sound "audio/beep.wav"
                $ response = "Proceed"
                call large_notify("{} Control".format(spaceLoc.name), "\"This is Tango 4. Your Docking request has been received. Please standby for Docking Procedure.\n\nDocking fee will be 10,000 Credits.\"", ["Proceed", "Abort"], "05_gui/ico_gui_station_pirate.png", "orange") from _call_large_notify_55 
                $ response = _return
                if response == "Proceed":
                    $ GAME.mc.hasDone("docked_pirate")
                    if GAME.money < 10000:
                        "You lack the required docking fees."
                        scene nav_screen_smart with fade
                    else:
                        scene expression ("06_cutscenes/cutscene_pirate_hideout_one.png") with fade
                        window hide
                        pause
                        play sound "audio/load.wav"
                        $ GAME.ship.status = "docked"
                        $ GAME.setLocID("LOCBridge")
                        call sandbox_interior_prepare_scene() from _call_sandbox_interior_prepare_scene_28 
                        call transaction("Docking Fees", -10000, True) from _call_transaction_32 
                        if not GAME.mc.hasDone("first_docking_pirate"):
                            play sound "audio/notify.wav"
                            nim "\"So far so good.\""
                            nim "\"But we better tread lightly here.\""
                            nim "\"I suggest we pay Vigo, my contact, a visit.\""
                            nim "\"I think we can find him in the Cantina.\""
                        return(["transition", GAME.locs["LOCBridge"]]) # CR-0589

                elif _return == "Abort":
                    scene nav_screen_smart with fade

            elif spaceLoc.ID in ["LIDStationArellarti"] and GAME.ship.spaceLocID == spaceLoc.ID:
                scene expression ("06_cutscenes/cutscene_arellarti_station_exterior.png") with fade
                play sound "audio/beep.wav"
                $ response = "Proceed"
                $ fee = 5000
                call large_notify("{} Control".format(spaceLoc.name), "\"This is Arellarti Station. Your Docking request has been received. Please standby for Docking Procedure.\n\nDocking fee will be [fee:,] Credits.\"", ["Proceed", "Abort"], "05_gui/ico_arellarti_station.png", "green") from _call_large_notify_56 
                $ response = _return
                if response == "Proceed":
                    $ GAME.mc.hasDone("docked_arellarti_station")
                    if GAME.money < fee:
                        "You lack the required docking fees."
                        scene nav_screen_smart with fade
                    else:
                        scene expression ("06_cutscenes/cutscene_arellarti_station.png") with fade
                        window hide
                        pause
                        play sound "audio/load.wav"
                        $ GAME.ship.status = "docked"
                        $ GAME.setLocID("LOCBridge")
                        call sandbox_interior_prepare_scene() from _call_sandbox_interior_prepare_scene_29 
                        call transaction("Docking Fees", -fee, True) from _call_transaction_33 
                        if not GAME.mc.hasDone("first_docking_arellarti"):
                            play sound "audio/notify.wav"
                            mc "\"So far so good.\""
                            mc "\"I wonder what opportunities exist for us here...\""
                            mc "\"Those Krell seem very business minded...\""
                        return(["transition", GAME.locs["LOCBridge"]]) # CR-0589

                elif _return == "Abort":
                    scene nav_screen_smart with fade

            elif spaceLoc.ID == "LIDDomeArellarti" and spaceLoc.ID == GAME.ship.spaceLocID:
                if not GAME.questSys.isActive('QID_SERAPHINE_SUB_DOME'):
                    play sound "audio/beep.wav"
                    "Arellarti Dome Administrator" "\"No Access For Humans.\""
                    mc "\"I see...\""
                    mc "\"I better go elsewhere then...\""
                else:
                    scene expression ("06_cutscenes/cutscene_arellarti_dome_exterior.png") with fade
                    play sound "audio/beep.wav"
                    $ response = "Proceed"
                    $ fee = 10000
                    call large_notify("{} Control".format(spaceLoc.name), "\"This is Arellarti Dome Docking Control. Your Docking request has been received. Please standby for Docking Procedure.\n\nDocking fee will be [fee:,] Credits.\"", ["Proceed", "Abort"], "05_gui/ico_arellarti_station.png", "green") from _call_large_notify_57 
                    $ response = _return
                    if response == "Proceed":
                        if GAME.money < fee:
                            "You lack the required docking fees."
                            scene nav_screen_smart with fade
                        else:
                            scene expression ("06_cutscenes/cutscene_arellarti_dome_approach.png") with fade
                            window hide
                            pause
                            play sound "audio/load.wav"
                            $ GAME.ship.status = "docked"
                            $ GAME.setLocID("LOCBridge")
                            call sandbox_interior_prepare_scene() from _call_sandbox_interior_prepare_scene_30 
                            call transaction("Docking Fees", -fee, True) from _call_transaction_34 
                            if not GAME.mc.hasDone("first_docking_dome"):
                                play sound "audio/notify.wav"
                                mc "\"So far so good.\""
                                mc "\"I wonder what is going on in here...\""
                                mc "\"Those Krell seem very eccentric...\""
                                mc "\"I best wait for Krogneath to show up tomorrow...\""
                                $ GAME.mc.hasDoneToday("first_docking_dome")
                            return(["transition", GAME.locs["LOCBridge"]]) 

                    elif _return == "Abort":
                        scene nav_screen_smart with fade                    


            elif spaceLoc.ID in ["LIDStationXenos"] and GAME.ship.spaceLocID == spaceLoc.ID:
                scene expression ("06_cutscenes/cutscene_xenos_station_exterior.png") with fade
                play sound "audio/beep.wav"
                $ response = "Proceed"
                $ fee = 5000
                call large_notify("{} Control".format(spaceLoc.name), "\"This is Xenos Station. Your Docking request has been received. Please standby for Docking Procedure.\n\nDocking fee will be [fee:,] Credits.\"", ["Proceed", "Abort"], "05_gui/ico_xenos_station.png", "cyan") from _call_large_notify_58 
                $ response = _return
                if response == "Proceed":
                    $ GAME.mc.hasDone("docked_xenos_station")
                    if GAME.money < fee:
                        "You lack the required docking fees."
                        scene nav_screen_smart with fade
                    else:
                        scene expression ("06_cutscenes/cutscene_xenos_station_approach.png") with fade
                        window hide
                        pause
                        play sound "audio/load.wav"
                        $ GAME.ship.status = "docked"
                        $ GAME.setLocID("LOCBridge")
                        call sandbox_interior_prepare_scene() from _call_sandbox_interior_prepare_scene_31 
                        call transaction("Docking Fees", -fee, True) from _call_transaction_35 
                        return(["transition", GAME.locs["LOCBridge"]]) # CR-0589

                elif _return == "Abort":
                    scene nav_screen_smart with fade

            elif spaceLoc.ID in ["LIDStationQuthor"] and GAME.ship.spaceLocID == spaceLoc.ID:
                scene expression ("06_cutscenes/cutscene_quthor_station_exterior.jpg") with fade
                play sound "audio/beep.wav"
                $ response = "Proceed"
                $ fee = 15000
                call large_notify("{} Control".format(spaceLoc.name), "\"This is Quthor Station. Your Docking request has been received. Please standby for Docking Procedure.\n\nDocking fee will be [fee:,] Credits.\"", ["Proceed", "Abort"], "05_gui/ico_quthor_station.png", "blue") from _call_large_notify_59 
                $ response = _return
                if response == "Proceed":
                    $ GAME.mc.hasDone("docked_quthor_station")
                    if GAME.money < fee:
                        "You lack the required docking fees."
                        scene nav_screen_smart with fade
                    else:
                        scene expression ("06_cutscenes/cutscene_quthor_station_approach.jpg") with fade
                        window hide
                        pause
                        play sound "audio/load.wav"
                        $ GAME.ship.status = "docked"
                        $ GAME.setLocID("LOCBridge")
                        call sandbox_interior_prepare_scene() from _call_sandbox_interior_prepare_scene_32 
                        call transaction("Docking Fees", -fee, True) from _call_transaction_36 
                        return(["transition", GAME.locs["LOCBridge"]]) # CR-0589

                elif _return == "Abort":
                    scene nav_screen_smart with fade

            elif spaceLoc.ID in ["LIDWaystation"] and GAME.ship.spaceLocID == spaceLoc.ID:
                scene expression ("06_cutscenes/cutscene_waystation_approach_one.png") with fade
                play sound "audio/beep.wav"
                $ response = "Proceed"
                $ fee = 3
                call large_notify("Waystation Control".format(spaceLoc.name), "\"This is Waystation Automated Control. Your Docking request has been received. Please standby for Docking Procedure.\n\nDocking requires [fee]t of Chtonium Ore for Galactic Field Compensation.\"", ["Proceed", "Abort"], "05_gui/ico_gui_waystation.png", "pink") from _call_large_notify_60 
                $ response = _return
                if response == "Proceed":
                    if not GAME.ship.hasCargo(["ITMOreChtonium"]*3):
                        "You lack the required docking materials."
                        scene nav_screen_smart with fade
                    else:
                        $ GAME.mc.hasDone("docked_waystation_station")
                        scene expression ("06_cutscenes/cutscene_waystation_approach_two.png") with fade
                        window hide
                        pause
                        play sound "audio/load.wav"
                        $ GAME.ship.status = "docked"
                        $ GAME.setLocID("LOCBridge")
                        call sandbox_interior_prepare_scene() from _call_sandbox_interior_prepare_scene_33 
                        python:
                            for i in range(3):
                                GAME.ship.unloadWare("ITMOreChtonium")
                        if not GAME.mc.hasDone("first_docking_waystation"):
                            play sound "audio/notify.wav"
                            mc "\"So far so good.\""
                            mc "\"Now let's take a look at that Station...\""

                        if "galactic_gate_duty" in vee.done:
                            $ vee.setLocOverride("LOCWayControlRoom")
                        return(["transition", GAME.locs["LOCBridge"]]) 

                elif _return == "Abort":
                    scene nav_screen_smart with fade


            #####################################################################
            #                TENARIS
            #####################################################################
            elif spaceLoc.ID == "LIDTenaris" and GAME.ship.getSubSysStatus("weapons") == 0:
                play sound "audio/drone_beep.wav"
                bb2 "\"The area around Tenaris is considered dangerous.\""
                bb2 "\"There are slave traders and pirates around.\""
                bb2 "\"You shouldn't go there without shields and weapons.\""
                mc "\"I see...\""
                mc "\"I better get my ship upgraded then...\""

            elif spaceLoc.ID == "LIDTenaris" and GAME.surfaces["SUIDTenaris"].found and GAME.ship.spaceLocID == spaceLoc.ID:
                queue sound "audio/notify.wav"
                call large_notify("TENARIS BASE", "You scan Tenaris, pinpointing the location of the Surface Base. You could land on the Base or go into Orbit.\n\nWhat do you want to do?", ["Land", "Orbit"], "05_gui/ico Ship.png", "blue") from _call_large_notify_61 
                if _return == "Land":
                    hide screen header
                    $ surface = GAME.surfaces["SUIDTenaris"]
                    return(["transition", surface]) 
                                
            #####################################################################
            #                JUNKYARD
            #####################################################################
            elif spaceLoc.ID in ["LIDJunkyardArellarti","LIDJunkyardIltari", "LIDJunkyardXenos", "LIDJunkyardQuthor", "LIDJunkyardNX010"] and spaceLoc.ID == GAME.ship.spaceLocID:
                $ mapFragmentsPre = len([x for x in GAME.mc.inventory if "ITMMapPre" in x.ID])
                # argus not ready
                if nimhe not in GAME.crew: # CR-0327
                    play sound "audio/beep.wav"
                    queue sound "audio/red alert.wav"
                    pga "\"This area is interdicted.\"" with redflash
                    pga "\"Violators will be disintegrated.\""
                    if not GAME.mc.hasDone("intro_interdiction"):
                        play sound "audio/drone_beep.wav"
                        bb2 "\"Those drones are not to be trifled with.\""
                        mc "\"I need to find a way to incapacitate them...\""
                        bb2 "\"Direct confrontation is not advised.\""
                        bb2 "\"They are Precursor technology and virtually indestructible.\""
                        bb2 "\"Otherwise the wrecks would long have been stripped of their AI Cores...\""
                        mc "\"A more surreptitious approach then...\""
                        mc "\"Maybe I can find a competent hacker to take them offline...\""
                        call quest_updater() from _call_quest_updater_192 
                    else:
                        mc "\"This was a, ahem... navigational error.\""
                        mc "\"I'm gone already...\""

                elif GAME.ship.getSubSysStatus("uplink") < 75: # CR-0974
                    queue sound "audio/notify.wav"
                    mc "\"I better bring my Argus System up to max before trying this...\"" 

                # late in the day
                elif GAME.hour >= 18:
                    mc "\"I should do that when I am better rested...\""

                # gear not up to scratch
                elif GAME.ship.getSubSysStatus("shields") == 0 or GAME.ship.getSubSysStatus("weapons") == 0:
                    queue sound "audio/drone_beep.wav"
                    if not GAME.mc.hasDone("illegal_bot_warning"):
                        bb2 "\"I would not go in there yet, Captain [GAME.mc.name].\""
                        mc "\"Why?\""
                        bb2 "\"Although the Argus allows us to sneak in, dangers lurk inside.\""
                        bb2 "\"Our ship should at least be equipped with shields and weapons...\""
                        mc "\"Where can I get those...?\""
                        bb2 "\"There are Pirates who are willing to sell them to you for a price.\""
                        bb2 "\"Nimhe might be able to tell you how to find them...\""
                        mc "\"How so?\""
                        bb2 "\"When she was trading in illegal bots she built up contacts...\""
                        bb2 "\"Just ask her about her illegal bots...\""
                        call quest_updater() from _call_quest_updater_193 
                    else:
                        bb2 "\"We better arm our ship before going in there...\""
                        mc "\"Ah, right.\""
                        mc "\"We should pay the Pirate Base a visit for that.\""

                # quest-specific intercepts
                elif spaceLoc.ID == "LIDJunkyardQuthor" and "quthos_pre_approved" not in GAME.mc.done and not GAME.questSys.isDone('QID_MAIN_QUTHOR_QUARRY_MAP'):
                    stop music fadeout 1.0
                    $ GAME.mc.hasDone("quthor_pre_rejected")
                    queue sound "audio/alert.wav"
                    "Quthor Command" "\"This Site is Military Research Use only.\"" with redflash
                    "Quthor Command" "\"Be advised to leave this location immediately.\""
                    queue sound "audio/beep.wav"
                    "Quthor Command" "\"Quthor Command Out.\""
                    mc "{i}\"Too bad...\"{/i}"
                    mc "{i}\"We need to find a way in there somehow...\"{/i}"
                    call quest_updater() from _call_quest_updater_194 

                elif "pre_"+GAME.getStarSys().name.lower()+"_3" not in GAME.mc.done:

                    scene expression("11_backgrounds/backdrop_junkyard.jpg") with fade
                    if not GAME.mc.hasDone("argus_comment"):
                        mc "\"Now let's see whether that money for the Argus Uplink was well spent...\""
                    if GAME.getSpaceLoc().ID == "LIDJunkyardQuthor" and GAME.questSys.isDone('QID_MAIN_QUTHOR_QUARRY_MAP'):
                        "Navigating the spacial tendrils of The Quarry, you make your way into the Junkyard..." with fade
                    else:
                        "Scrambling the Guardian's sensors, you make your way into the Junkyard..." with fade
                    $ GAME.mc.hasDone('precursor_core_found') # for first precursor quest progression

                    # ===== CR-0438 START =====
                    # select scenario 
                    $ scenarioID = False
                    if "pre_"+GAME.getStarSys().name.lower()+"_1" not in GAME.mc.done:
                        $ scenarioID = "pre_"+GAME.getStarSys().name.lower()+"_1"
                    elif "pre_"+GAME.getStarSys().name.lower()+"_2" not in GAME.mc.done:
                        $ scenarioID = "pre_"+GAME.getStarSys().name.lower()+"_2"
                    elif "pre_"+GAME.getStarSys().name.lower()+"_3" not in GAME.mc.done:
                        $ scenarioID = "pre_"+GAME.getStarSys().name.lower()+"_3"

                    # combat execution
                    if scenarioID:
                        ###########################################################
                        #              ZEALOT INTERCEPT
                        ###########################################################
                        if "pre_xenos" in scenarioID:
                            if "zealot_accept" in GAME.mc.done:
                                "At strategic positions, you notice the Zealot Guards..."
                                mc "\"Worth a try, but I better not break that deal with the Zealots...\""
                                return(["transition", GAME.getStarSys().locs["LIDJunkyardXenos"]])

                            elif "zealot_oppose" in GAME.mc.done and scenarioID not in GAME.mc.done:
                                $ resume_scenarioID = str(scenarioID) # paranoid
                                call cutscene("zealot_guards") from _call_cutscene_30 
                                if "victory" not in _return:
                                    # booted to space
                                    return(["transition", GAME.getStarSys().locs["LIDJunkyardXenos"]])
                                # continue with precursor scenario 
                                mc "\"That was tough...\""
                                mc "\"Now for the Precursors...\""
                                $ scenarioID = resume_scenarioID



                            elif "zealot_encounter" not in GAME.mc.done or "zealot_reconsider" in GAME.mc.done:
                                call cutscene("zealot_encounter") from _call_cutscene_31 
                                call quest_updater() from _call_quest_updater_195 
                                call quest_updater() from _call_quest_updater_196 
                                return(["transition", GAME.getStarSys().locs["LIDJunkyardXenos"]])
 
                        ###########################################################
                        #              PRECURSOR COMBAT
                        ###########################################################
                        call mg_combat_scenario(scenarioID) from _call_mg_combat_scenario_10 
                        $ result = _return
                        if "victory" in result: # EXP returned
                            $ damage = result[1]
                            $ exp = result[2]
                            queue sound "audio/triumph.wav"
                            call simple_notify("VICTORY", "+[exp:,] EXP gained", ["Continue"], "05_gui/ico_gui_cup.png") from _call_simple_notify_94 
                            queue sound "audio/click.wav"            
                            $ GAME.mc.exp += exp
                            call attr_mod(GAME.mc, "NOT", 1, 100, 100, True) from _call_attr_mod_75 
                        else:
                            mc "\"That was close...\""

                        $ mapFragmentsPost = len([x for x in GAME.mc.inventory if "ITMMapPre" in x.ID])
                        
                        if scenarioID == "pre_"+GAME.getStarSys().name.lower()+"_3" and mapFragmentsPost > mapFragmentsPre: # CR-0685
                            tri "\"Excellent!\""
                            tri "\"We have gained a Hyperspace map fragment from this site!\""
                            call attr_mod(tris, "APP", 5, 100, 100, True) from _call_attr_mod_76 
                        # =====  CR-0685 START
                        elif scenarioID == "pre_"+GAME.getStarSys().name.lower()+"_3" and mapFragmentsPost <= mapFragmentsPre:
                            tri "\"We failed to gain a Precursor Map Fragment from the site!\""
                            tri "\"We might have to venture in again better prepared.\""                   
                        # =====  CR-0685 END

                        call hour_passes(18-GAME.hour) from _call_hour_passes_79 
                        scene nav_screen_smart with fade
                        show screen header()
                        
                    else:
                        mc "\"There is nothing for me left to discover here...\""
                        mc "\"I should look for Precursor sites in other Star Systems...\""

                elif "pre_"+GAME.getStarSys().name.lower()+"_3" in GAME.mc.done:
                    queue sound "audio/notify.wav"
                    mc "\"I have cleaned out that location already...\""
                    mc "\"Maybe there are similar locations in other Star Systems...\""

                # ===== CR-0438 END =====


            #####################################################################
            #                ANOMALY
            #####################################################################
            elif spaceLoc.ID == "LIDAnomalyIltari" and GAME.questSys.inProgress('QID_MAIN_ANOMALY') and spaceLoc.ID == GAME.ship.spaceLocID:
                if GAME.hour > 18:
                    mc "\"We should rest before venturing inside...\""
                else:
                    call cutscene_vee("anomaly investigate") from _call_cutscene_vee_7 
                    # "Foo1" CR-0606
                    $ GAME.hour = 20
                    $ GAME.setLocID("LOCCargo")
                    call sandbox_interior_prepare_scene() from _call_sandbox_interior_prepare_scene_34 
                    # "Foo2" CR-0606
                    return(["transition", GAME.locs["LOCCargo"]]) # CR-0590

            #####################################################################
            #					ODDITY UNDERVERSE		
            #####################################################################
            elif spaceLoc.ID in ["LIDOddityNX010"] and spaceLoc.ID == GAME.ship.spaceLocID:
                scene intermission with fade 
                $ vShipID = "VID04"
                if not GAME.vaultships["VID02"].encountered:
                    $ vShipID = "VID02"
                elif not GAME.vaultships["VID03"].encountered:
                    $ vShipID = "VID03"
                #execute interaction 
                call mg_vaultship_interact(vShipID) from _call_mg_vaultship_interact_1 
                $ spaceLoc.found = False
 
            #####################################################################
            #					ODDITY / MYSTERY		
            #####################################################################
            elif spaceLoc.ID in ["LIDOddityIltari"] and spaceLoc.ID == GAME.ship.spaceLocID:
                $ roll = random.randint(1,100) # CR-0609
                if GAME.hour >= 18:
                    mc "\"It is too late to explore this site...\""
                
                elif roll < 75 or not GAME.ship.hasSubSys("mining"):
                    queue sound "audio/notify.wav"
                    call simple_notify("ENCOUNTER FROM THE VOID", "Swarm Vessels Emerge!", ["Engage", "Flee"], "05_gui/ico_gui_hostile_swarm.png", "pink") from _call_simple_notify_95 
                    queue sound "audio/click.wav"
                    if _return == "Engage":
                        call mg_combat_scenario(random.choice(["swarm_1", "swarm_2", "swarm_3", "swarm_5", "swarm_convoy"])) from _call_mg_combat_scenario_11 
                        if "abort" not in _return:
                            $ spaceLoc.found = False      
                    else:
                        mc "\"Maybe when I am better prepared...\""

                elif False: # CR-0919
                    call vaultship_encounter() from _call_vaultship_encounter 
                    $ spaceLoc.found = False  

                else:
                    queue sound "audio/notify.wav"
                    call simple_notify("THE VOID FIELDS", "Wormhole to The Void!", ["Enter", "Abort"], "08_items/ico ITMNanotubes.png", "pink") from _call_simple_notify_96 
                    queue sound "audio/click.wav"
                    if _return == "Enter":
                        # save current loc
                        $ saveSpaceLoc = GAME.getSpaceLoc()
                        $ saveStarSys = GAME.getStarSys()

                        # transfer to void, mining 
                        $ GAME.ship.starSysID = "SSIDVoid"
                        $ GAME.setSpaceLocID("LIDAsteroidsVoid")
                        call mg_mining_pick("THE VOID - ASTEROID FIELD") from _call_mg_mining_pick_1 
                        call hour_passes(18-GAME.hour) from _call_hour_passes_80 

        
                        # restor loc
                        $ GAME.ship.starSysID = saveStarSys.ID
                        $ GAME.setSpaceLocID(saveSpaceLoc.ID)
                        $ spaceLoc.found = False
                    else:
                        mc "\"Maybe some other time...\""

            #####################################################################
            #                KRELL / LAB
            #####################################################################
            elif spaceLoc.ID == "LIDLabsArellarti" and spaceLoc.ID == GAME.ship.spaceLocID:
                # if not GAME.questSys.isActive('QID_KRELL_KICKOFF'):
                #     play sound "audio/beep.wav"
                #     "Kranor Labs Administrator" "\"Top Secret Research going on here.\""
                #     "Kranor Labs Administrator" "\"Move along!\""
                #     mc "\"I see...\""
                #     mc "\"I better go elsewhere then...\""
                
                if not GAME.questSys.isActive('QID_KRELL_INTERCEPT'):
                    call cutscene("inquire_biolab") from _call_cutscene_32 

                elif not GAME.questSys.isDone('QID_KRELL_YLYEE_WAIT'):
                    "Kranor Labs Administrator" "\"I've told you to seek business elsewhere!\""

                else:
                    queue sound "audio/beep.wav"
                    "Kranor Labs Administrator" "\"Lab is closed for repairs.\""
                    "Kranor Labs Administrator" "\"Area is not safe!\""
                    mc "\"I see...\""
                    mc "\"I better go elsewhere then...\""

            #####################################################################
            #              QUTHOR
            #####################################################################
            elif spaceLoc.ID == "LIDQuarry" and spaceLoc.ID == GAME.ship.spaceLocID:
                if GAME.hour >= 22:
                    mc "{i}\"It's late...\"{/i}"
                    mc "{i}\"I better do that tomorrow...\"{/i}"
                    
                elif GAME.questSys.isDone("QID_MAIN_SWARMCORDON") and not "belit_special" in belit.done and GAME.hour < 20:
                    call cutscene_quthor("belit_special") from _call_cutscene_quthor_23 
      
                elif GAME.questSys.isDone("QID_MAIN_SWARMCORE"):
                    queue sound "audio/notify.wav"
                    call large_notify("THE QUARRY", "You approach the Quarry, an area of Fractured Space. You can proceed to Belit's Hideout or navigate to the Vaultship Wreck.\n\nWhat do you want to do?", ["Belit", "Wreck", "Abort"], "05_gui/ico Ship.png", "orange") from _call_large_notify_62 
                    if _return == "Belit":
                        "You pay Belit a visit..."
                        queue sound "audio/beep.wav"
                        call belit_trader() from _call_belit_trader 
                    elif _return == "Wreck":
                        # CR-1004 START ====
                        $ vShipKey = "VID00"
                        if GAME.vaultships["VID00"].encountered:
                            $ vShipKey = "VID01"
                        call mg_vaultship_interact(vShipKey) from _call_mg_vaultship_interact_2 
                        # CR-1004 END =====

                elif GAME.questSys.inProgress('QID_MAIN_SWARMCORE'):
                    call cutscene_quthor("belit_reward") from _call_cutscene_quthor_24 
                    call quest_updater() from _call_quest_updater_197 

                elif GAME.questSys.inProgress('QID_MAIN_SWARMWEAPON'):
                    call cutscene_quthor("belit_weapon") from _call_cutscene_quthor_25 
                    call quest_updater() from _call_quest_updater_198 

                elif GAME.questSys.inProgress('QID_MAIN_QUTHOR_BELIT_CASH'):
                    call cutscene_quthor("belit_cash") from _call_cutscene_quthor_26 
                    call quest_updater() from _call_quest_updater_199 

                elif GAME.questSys.inProgress('QID_MAIN_QUTHOR_BELIT_SHIELD'):
                    call cutscene_quthor("belit_shield") from _call_cutscene_quthor_27 
                    call quest_updater() from _call_quest_updater_200 

                elif GAME.questSys.isActive('QID_MAIN_QUTHOR_BELIT_MAP'):
                    queue sound "audio/notify.wav"
                    call simple_notify("THE QUARRY", "Contact Belit", ["Contact", "Abort"], "05_gui/ico Ship.png", "orange") from _call_simple_notify_97 
                    if _return == "Contact":
                        "You contact Belit..."
                        queue sound "audio/beep.wav"
                        call belit_trader() from _call_belit_trader_1 

                else:
                    queue sound "audio/drone_beep.wav"
                    bb2 "\"I advise to stay clear of that area, Captain [GAME.mc.name].\""
                    mc "\"Why?\""
                    bb2 "\"Sensors indicate a complex pattern of Fractured Space...\""
                    bb2 "\"We better stay out of there...\""
                    mc "\"Agreed.\""

            elif spaceLoc.ID == "LIDLedruhk" and spaceLoc.ID == GAME.ship.spaceLocID and GAME.questSys.inProgress('QID_MAIN_QUTHOR_ORE'):
                call cutscene_quthor("infernium_delivery") from _call_cutscene_quthor_28 
                call quest_updater() from _call_quest_updater_201 
            
            elif spaceLoc.ID == "LIDMinosForge" and spaceLoc.ID == GAME.ship.spaceLocID and GAME.questSys.inProgress('QID_MAIN_QUTHOR_PLATING2'):
                call cutscene_quthor("infernium_plating_delivered") from _call_cutscene_quthor_29 
                call quest_updater() from _call_quest_updater_202 

            elif spaceLoc.ID == "LIDMinosForge" and spaceLoc.ID == GAME.ship.spaceLocID and GAME.questSys.inProgress('QID_MAIN_QUTHOR_MIL_GREASE'):
                call cutscene_quthor("minos_vortex") from _call_cutscene_quthor_30 
                call quest_updater() from _call_quest_updater_203 

            #####################################################################
            #              NX010
            #####################################################################
            elif spaceLoc.ID == "LIDChtonos" and spaceLoc.ID == GAME.ship.spaceLocID:
                if GAME.hour >= 18:
                    mc "\"I better do that when I am better rested...\""
                else:
                    call activity_bar("SCANNING ORBITAL FRAGMENTS...") from _call_activity_bar 
                    $ result = hardRandInt(1,100)
                    if result > 50:
                        queue sound "audio/success.wav"
                        $ item = GAME.items["ITMOreChtonium"]
                        $ amount = hardRandInt(2,7)
                        call find_notify(item, "ITEM FOUND!", amount) from _call_find_notify_51 
                        mc "\"Nice...\""
                        queue sound "audio/load.wav"
                        $ GAME.ship.cargo += [item]*amount
                    else:
                        "You do not find anything of interest..."
                    call hour_passes(min(18-GAME.hour, 3)) from _call_hour_passes_81 


            #####################################################################
            #              WAYSTATION SYSTEM LOCATIONS
            #####################################################################
            elif GAME.ship.activateSpaceLoc("LIDAssembly", spaceLoc.ID):
                $ result = random.randint(1,100)
                "You venture into the Cluster of Debris and Nanites..."
                if result > 90: # assembler 
                    stop music 
                    queue sound "audio/alert.wav"
                    "Out of a dense Debris Cloud a huge shape speeds  towards you..." with redflash
                    call mg_combat_scenario("assembler") from _call_mg_combat_scenario_12 
                    # process result 
                    mc "\"That was close...\""
                elif result > 50: # Space find
                    $ lootPool = [GAME.items[x] for x in ["ITMOreChtonium", "ITMCarbonPowder", "ITMNanotubes", "ITMCarbonFiberSpools", "ITMComputer"]]
                    $ loot = [random.choice(lootPool) for x in range(random.randint(3,10)) ]
                    $ lootKinds = set(loot)
                    while lootKinds:
                        $ item = lootKinds.pop()
                        $ amount = loot.count(item)
                        call find_notify(item, "ITEM FOUND", amount) from _call_find_notify_52 
                        $ GAME.ship.cargo += [item]*amount

                else: # nothing
                    "You search the Area without success..."

            elif GAME.ship.activateSpaceLoc("LIDEvacWreck", spaceLoc.ID):
                if "explored" not in GAME.getSpaceLoc().tags:
                    call cutscene("waystation_wreck") from _call_cutscene_33 
                else:
                    "There is nothing more of interest in the Abandoned Wreck..."

            #####################################################################
            #              BEACON OF ELEMENTS
            #####################################################################
            elif spaceLoc.ID == "LIDBeaconElements" and spaceLoc.ID == GAME.ship.spaceLocID:
                scene expression ("06_cutscenes/cutscene_beacon_approach.jpg") with fade 
                "You approach the Beacon Tower for Landing..."
                # window hide
                # pause
                play sound "audio/load.wav"
                $ GAME.ship.status = "docked"
                # $ GAME.setLocID("LOCLandingElements")
                $ GAME.setLocID("LOCBridge")
                call sandbox_interior_prepare_scene() from _call_sandbox_interior_prepare_scene_35 
                if not GAME.mc.hasDone("beacon_ele_landing"):
                    play sound "audio/notify.wav"
                    tri "\"Well, we managed to land.\""
                    tri "\"Let us proceed to explore the Beacon...\""
                return(["transition", GAME.locs["LOCBridge"]]) 


            #####################################################################
            #              BEACON OF AUTOMATONS
            #####################################################################
            elif spaceLoc.ID == "LIDBeaconAutomatons" and spaceLoc.ID == GAME.ship.spaceLocID:
                scene expression ("06_cutscenes/cutscene_beacon_approach.jpg") with fade 
                "You approach the Beacon Tower for Landing..."
                # window hide
                # pause
                play sound "audio/load.wav"
                $ GAME.ship.status = "docked"
                $ GAME.setLocID("LOCLandingAutomatons")
                call sandbox_interior_prepare_scene() from _call_sandbox_interior_prepare_scene_36 
                return(["transition", GAME.locs["LOCBridge"]]) 

            elif GAME.ship.activateSpaceLoc("LIDAutomatonFields", spaceLoc.ID):
                call mg_automaton_fields() from _call_mg_automaton_fields 

            #####################################################################
            #              BEACON OF ASSEMBLY
            #####################################################################
            elif spaceLoc.ID == "LIDBeaconAssembly" and spaceLoc.ID == GAME.ship.spaceLocID:
                scene expression ("06_cutscenes/cutscene_beacon_approach.jpg") with fade 
                "You approach the Beacon Tower for Landing..."
                # window hide
                # pause
                play sound "audio/load.wav"
                $ GAME.ship.status = "docked"
                $ GAME.setLocID("LOCLandingAssembly")
                call sandbox_interior_prepare_scene() from _call_sandbox_interior_prepare_scene_37 
                return(["transition", GAME.locs["LOCBridge"]]) 
                
            elif GAME.ship.activateSpaceLoc("LIDAssemblyFields", spaceLoc.ID):
                call mg_assembly_fields() from _call_mg_assembly_fields 

            #####################################################################
            #              BEACON OF STARS
            #####################################################################
            elif spaceLoc.ID == "LIDBeaconStars" and spaceLoc.ID == GAME.ship.spaceLocID:
                scene expression ("06_cutscenes/cutscene_beacon_approach.jpg") with fade 
                "You approach the Beacon Tower for Landing..."
                # window hide
                # pause
                play sound "audio/load.wav"
                $ GAME.ship.status = "docked"
                $ GAME.setLocID("LOCLandingStars")
                call sandbox_interior_prepare_scene() from _call_sandbox_interior_prepare_scene_38 
                return(["transition", GAME.locs["LOCBridge"]]) 
                
            #####################################################################
            #              WAYSTATION
            #####################################################################
            elif spaceLoc.ID == "LIDWaystation" and not "waystation_unlocked" in GAME.mc.done and spaceLoc.ID != GAME.ship.spaceLocID:
                queue sound "audio/beep.wav"
                "Navigation Control" "\"No safe route to Target identified.\""
                queue sound "audio/notify.wav"
                tri "\"Strong spatial distortions emanate from The Waystation.\""
                tri "\"Without navigational aid we cannot lay in a course...\""
                mc "\"Navigational aid?\""
                tri "\"Some sort of Beacon.\""
                mc "\"Understood.\""

            #####################################################################
            #					EXECUTE TRAVEL							  #
            #####################################################################
            elif _return[1].ID != GAME.ship.spaceLocID: # travel
                if GAME.hour >= 22:
                    mc "\"I should resume exploring tomorrow...\""
            
                elif GAME.ship.cargoLoaded() > GAME.ship.cargoLimit():
                    queue sound "audio/beep.wav"
                    bb2 "\"The ship is overloaded, Captain [GAME.mc.name]\""
                    bb2 "\"This may endanger ship integrity during travel...\"" 
                    mc "\"I better check my manifest then...\"" 

                else:
                    $ tgtLocID = _return[1].ID
                    $ tgtLoc = _return[1] 
                    call travel("You speed towards your target...") from _call_travel 
                    $ GAME.hour += 1
                    # enable visited locations for missions once intro done
                    if GAME.questSys.isDone("QID_MAIN_STUDYMAP"):
                        $ tgtLoc.mission = True

                    #####################################################################
                    #					QUTHOR BELT CROSSING		
                    #####################################################################
                    if GAME.getStarSys().ID == "SSIDQuthor" and "belt_crossed" not in GAME.mc.doneToday and GAME.getSpaceLoc().zone >=75 and tgtLoc.zone <= 50:
                        queue sound "audio/notify.wav"
                        call large_notify("THE ASTEROID BELT", "Entering the dangerous Quthor Asteroid Belt, you must decide on a course of action.\n\nYou can either risk damage or navigate the pirate infested passages.", ["Damage", "Passage", "Abort"], "05_gui/ico Ship.png", "orange") from _call_large_notify_63 
                        if _return == "Abort":
                            "You turn back your ship and reconsider..."
                            $ tgtLocID = GAME.ship.spaceLocID
                        elif _return == "Damage" and random.randint(1,100) > 30:
                            call check_occurrence(tgtLoc, random.choice(["OCCAsteroidsQuthor001"])) from _call_check_occurrence 
                            if random.randint(1,100) > 50:
                                call check_occurrence(tgtLoc, random.choice(["OCCWreckDrengar02", "OCCBotContainer001"])) from _call_check_occurrence_1 
                        elif _return == "Damage":
                            "Unexpectedly, you make it through the belt without damage..."
                        elif _return == "Passage" and random.randint(1,100) > 30:
                            call check_occurrence(tgtLoc, random.choice(["OCCHostileDrengar02"])) from _call_check_occurrence_2 
                        elif _return == "Passage":
                            "Unexpectedly, you make it through the belt unscathed..."
                        
                        call travel("You resume your travels...") from _call_travel_1 
                        $ GAME.mc.hasDoneToday("belt_crossed")

                    #####################################################################
                    #					KRELL BELT CROSSING		
                    #####################################################################
                    if GAME.getStarSys().ID == "SSIDArellarti" and "belt_crossed" not in GAME.mc.doneToday and GAME.getSpaceLoc().zone >=50 and tgtLoc.zone <= 25:
                        queue sound "audio/notify.wav"
                        call large_notify("THE ASTEROID BELT", "Entering the dense Arellarti Asteroid Belt, you must decide on a course of action.\n\nYou can either risk damage or navigate the pirate infested passages.", ["Damage", "Passage", "Abort"], "05_gui/ico Ship.png", "green") from _call_large_notify_64 
                        if _return == "Abort":
                            "You turn back your ship and reconsider..."
                            $tgtLocID = GAME.ship.spaceLocID
                        elif _return == "Damage" and random.randint(1,100) > 30:
                            call check_occurrence(tgtLoc, random.choice(["OCCAsteroids001"])) from _call_check_occurrence_3 
                            if random.randint(1,100) > 50:
                                call check_occurrence(tgtLoc, random.choice(["OCCWreckKrell02", "OCCBotContainer001"])) from _call_check_occurrence_4 
                        elif _return == "Damage":
                            "Unexpectedly, you make it through the belt without damage..."
                        elif _return == "Passage" and random.randint(1,100) > 30:
                            call check_occurrence(tgtLoc, random.choice(["OCCHostileKrell01", "OCCHostileKrell02"])) from _call_check_occurrence_5 
                        elif _return == "Passage":
                            "Unexpectedly, you make it through the belt unscathed..."
                        
                        call travel("You resume your travels...") from _call_travel_2 
                        $ GAME.mc.hasDoneToday("belt_crossed")
                            
                    #####################################################################
                    #					GENERAL OCCURRENCE		
                    #####################################################################
                    elif "occurrence" not in GAME.mc.doneToday and random.randint(1,100) > 50 and GAME.day > 2:
                        call check_occurrence(tgtLoc) from _call_check_occurrence_6 
                        call achievement_updater() from _call_achievement_updater 
                        $ GAME.mc.hasDoneToday("occurrence")
                        if _return:
                            if _return == True:
                                pass
                            elif "newloc" in _return:
                                $ tgtLocID = _return[1]
                        call travel("You resume your travels...") from _call_travel_3 

                    $ GAME.ship.spaceLocID = tgtLocID
                    scene nav_screen_smart with fade


            #####################################################################
            #					MISSION WITHOUT REQUIRED CARGO		
            #####################################################################
            elif GAME.missionSys.getLocActive(spaceLoc.ID, "loc_only") and spaceLoc.ID == GAME.ship.spaceLocID:
                queue sound "audio/notify.wav"
                mc "\"I don't have all the required cargo loaded yet to fulfil this mission...\"" 
                mc "\"I better check my manifest...\"" 
            #####################################################################
            #					SHORTAGES		xxx
            #####################################################################
            elif spaceLoc.ID == GAME.ship.spaceLocID and GAME.missionSys.shortages.get(spaceLoc.ID,False) and GAME.ship.hasCargo([GAME.missionSys.shortages.get(spaceLoc.ID,False)]):
                $ item = GAME.items[GAME.missionSys.shortages.get(spaceLoc.ID,False)]
                queue sound "audio/notify.wav"
                call large_notify("SHORTAGE RELIEF", "{} suffers from a {} Shortage. You have such parts in Cargo.\n\nDo you want to unload all parts you have (for a premium)?".format(spaceLoc.name, item.getName(["noArt", "col", "cap"])), ["Unload", "Keep"], "05_gui/ico_gui_crate.png", "orange") from _call_large_notify_65 
                if _return == "Unload":
                    $ wares = [x for x in GAME.ship.cargo if x == item] 
                    $ amount = len(wares)
                    $ proceeds = spaceLoc.getPrice(item, "sell")*5*amount 
                    queue sound "audio/load.wav"
                    call simple_notify("ITEMS UNLOADED", "{} ({}x)".format(item.getName(["noArt", "col", "cap"]), amount), ["Continue"], "08_items/ico {}.png".format(item.ID)) from _call_simple_notify_98 
                    call transaction("Shortage Supplies", proceeds, True) from _call_transaction_37 
                    call simple_notify("PAYMENT RECEIVED", "{:,} Cr".format(proceeds),["Continue"], "05_gui/ico_gui_crate.png", "gold") from _call_simple_notify_99 
                    if not GAME.mc.hasDoneToday("shortages"):
                        call attr_mod(GAME.mc, "REP", 1,60, 100, True) from _call_attr_mod_77 
                    while wares:
                        $ ware = wares.pop()
                        $ GAME.ship.cargo.remove(ware)


            #####################################################################
            #					DEFAULT		
            #####################################################################
            else:
                mc "\"There is nothing for me to do here right now...\""
