#####################################################################
#              AWAY MISSION CHECKS
#####################################################################
label away_mission_checks():
    # Intercepts / Infos 
    if tris.getLocOverride() == "LOCNavClass" and (GAME.hour >= 18 or "away_mission" not in tris.doneToday) and GAME.getSpaceLoc().ID == "LIDStationIltari":
        call interact_tris("mission_report", False, ["nav_class"]) from _call_interact_tris 

    # Intercepts / Infos 
    if tris.getLocOverride() == "LOCPetClass" and (GAME.hour >= 18 or "away_mission" not in tris.doneToday) and GAME.getSpaceLoc().ID == "LIDStationArellarti":
        call interact_tris("mission_report", False, ["pet_class"]) from _call_interact_tris_1 

    # Intercepts / Infos 
    if moira.getLocOverride() == "LOCPetClass" and (GAME.hour >= 18 or "away_mission" not in moira.doneToday) and GAME.getSpaceLoc().ID == "LIDStationArellarti":
        call interact_moira("mission_report", False, ["pet_class"]) from _call_interact_moira 


    return()

label night_passes_pre():
    stop music
    hide screen header

    call away_mission_checks() from _call_away_mission_checks 

    #OhWee mod code transplant
    
    if GAME.racingSys.getTodaysRace():
        $ race = GAME.racingSys.getTodaysRace()
        if race.ownBets:
            queue sound "audio/notify.wav"
            mc "\"I still have open Bets on todays Race.\""
            "You call up the streaming program for today's race on your PDA..."
            scene intermission with fade
            # CR-2134 END
            hide screen header

            if False: # WIP 1.60 Cleanup
                call visualize_race(GAME.racingSys.getTodaysRace()) from _call_visualize_race_PDA

            call visualize_race(GAME.racingSys.getTodaysRace()) from _call_visualize_race_new_PDA
            
            #call sandbox_interior_navigate_to("LOCArellartiDomePL") from _call_sandbox_interior_navigate_to_21
            #call hour_passes(capValue(21-GAME.hour,1,15)) from _call_hour_passes_34
            return(False) 
            
    #End OhWee mod code transplant

    if [x for x in GAME.books if x[0] == GAME.day]:
        queue sound "audio/beep.wav"
        scene expression("11_backgrounds/backdrop_planet_sunrise_02.jpg") with fade 
        call daily_financial_report(GAME.day) from _call_daily_financial_report 
    scene intermission with fade
    #####################################################################
    #                EVENTS PRE WAKEUP
    #####################################################################

    $ reloadingbanter = False
    # Swarm Exposition
    if GAME.questSys.isDone("QID_MAIN_ANOMALY"):
        if not GAME.mc.hasDone("swarm intro"):
            call cutscene("swarm intro") from _call_cutscene 

    #  CR-0974 START ==========
    # Vee Energy Consumption
    while vee.hasItem("ITMPodEnergy"):
        $ vee.tallyUp("Energy Consumed",1)
        $ vee.remItem("ITMPodEnergy")
        $ vee.hasDoneToday("consumed_energy")

    # Vee Dreams
    if GAME.questSys.isDone("QID_VEE_PASSENGER") and not vee.hasItem("ITMPodEnergy") and "awake" not in vee.status and 'consumed_energy' not in vee.doneToday:
    #  CR-0974 END ==========

        $ vee.hasDone("dream_one")
        call cutscene_vee("dream_one") from _call_cutscene_vee 
        $ GAME.mc.status.append("dream_one")

    elif vee.getTally("Energy Consumed")>=6 and "dream_two" not in vee.done:
        $ vee.hasDone("dream_two")
        call cutscene_vee("dream_two") from _call_cutscene_vee_1 
        $ GAME.mc.status.append("dream_two")

    elif vee.getTally("Energy Consumed")>=12 and "dream_three" not in vee.done: # CR-0974
        $ vee.hasDone("dream_three")
        call cutscene_vee("dream_three") from _call_cutscene_vee_2 
        $ GAME.mc.status.append("dream_three")

    # Infiltrator Mission / Collector
    if GAME.questSys.inProgress("QID_NIMHE_RETRIEVE_SEND") and GAME.getSpaceLoc().ID == "LIDStationIltari" and GAME.ship.status=="docked" and GAME.ship.getSubSysStatus("uplink") > 99.0:
        call cutscene_nimhe("infiltrator_mission") from _call_cutscene_nimhe 

    # Infiltrator Mission / Biolab 
    if GAME.lab.infiltratorStandby() and GAME.getSpaceLoc().ID == "LIDLabsArellarti" and GAME.ship.getSubSysStatus("uplink") > 99.0 and  GAME.ship.getSP() >= 1 and GAME.questSys.inProgress('QID_KRELL_YLYEE_TASK'):
        call cutscene("biolab_infiltrate") from _call_cutscene_1 

    # Infiltrator Mission / Krell Gate Module
    if GAME.questSys.inProgress("QID_MAIN_SWARMMODULE_B") and GAME.getSpaceLoc().ID == "LIDRendezvousArellarti25" and GAME.ship.getSubSysStatus("uplink") > 99.0 and GAME.ship.getSP() >= 1 and GAME.lab.infiltratorStandby(['military grade', 'elite']):
        call cutscene_quthor("infiltrator_gate_module") from _call_cutscene_quthor 

    # Seraphine Exposition        
    if GAME.questSys.isDone("QID_VEE_FAMILIARIZE") and "teaser_seraphine" not in GAME.mc.done:
        call cutscene_seraphine("teaser_seraphine") from _call_cutscene_seraphine 

    # Biolab Exposition
    if GAME.questSys.isDone('QID_KRELL_LAB_RETURN') and not "expo_biolab" in GAME.mc.done:
        call cutscene("expo_biolab") from _call_cutscene_2 
        call quest_updater() from _call_quest_updater_4 

    "One night passes..."
    $ GAME.mc.hasDone("sleep")

    #####################################################################
    #              NIGHT JOBS
    #####################################################################
    python:
        for actor in GAME.crew:
            actor.workNightAI()
    #####################################################################
    #                QUEST DATABASE HOUSEKEEPING
    #####################################################################
    # call init_quests() 

    #####################################################################
    #                MISCELLANEOUS HOUSEKEEPING
    #####################################################################

    # silent repair reward if no ship encounter with TRis happened
    if "delegation_comment" not in tris.doneToday and "repair" in khelara.doneToday:
        $ tris.fp += 2 

    # daily tracker, log resets etc...

    python:
        GAME.day += 1
        GAME.hour = 7
        GAME.ap = 5
        GAME.log = []
        GAME.missionSys.shortages = {}

        for k in GAME.timers.keys():
            GAME.timers[k] = max(0,GAME.timers[k]-1)

        for actor in GAME.npc + [GAME.mc]: # all characters
            actor.doneToday = []
            
            # accessories
            # actor.accessory = [] # CR-2005
            
            # clothing counter
            for i in actor.outfit:
                actor.counters[i.ID] = actor.counters.get(i.ID,0) + 1

            # milkmod related
            if actor.milkMod:
                actor.milkMod.produce()

            # remove perishable goods
            for item in [x for x in actor.inventory if x.ID in ["ITMDrinkAstropolitan", "ITMDrinkDrengarianIceTea", "ITMDrinkPanGalactica", "ITMDrinkStarburst69", "ITMDrinkStellarShake"]]:
                actor.inventory.remove(item)

            if actor.hasItem("ITMPirateMagazine") and actor == moira:
                actor.hasDoneToday("read_pirate_novel")
                actor.remItem("ITMPirateMagazine")
                actor.setAttr("MOD", min(100,actor.attr["MOD"]+20))
                actor.setAttr("STS", max(0,actor.attr["STS"]-10))

            if actor.isPlugged() == "ITMPlugAntiStress":
                actor.setAttr("STS", max(0,actor.attr["STS"]-20))


        for actor in [sector]: # deprecated, check npc unification and remove in V6
            actor.doneToday = []

        for actor in GAME.crew:
            if (actor == vee and GAME.questSys.isActive("QID_VEE_FAMILIARIZE")) or actor != vee:
                actor.tallyUp("Days in Crew",1)
            if "MOD" in actor.attr.keys():
                actor.attr["MOD"] = min(100, actor.attr["MOD"]+5)
            else:
                actor.attr["MOD"] = 5
            # khelara sees revealing 
            if actor == khelara and all([x for x in [nimhe, tris] if x.uniform == "UID3_Revealing"]) and GAME.questSys.inProgress("QID_KHELARA_REVEALING"): # CR-0359
                khelara.done.append("seen_revealing")    # LEGACY 
                khelara.tallyUp("Revealing Seen",1)      
            if actor == moira and all([x for x in [nimhe, tris, khelara] if x.uniform == "UID3_Revealing"]) and GAME.questSys.inProgress("QID_MOIRA_REVEALING"): # CR-0359
                moira.tallyUp("Revealing Seen",1)       

        # location memory wipes
        for s in GAME.starSys.values():
            for l in s.locs.values():
                l.doneToday = []
        for i in GAME.traders: # these are dynamic spacelocs not npc!
            i.doneToday = []

        # wipe all space oddities / dynamic location found tags
        for i in GAME.starSys.values():
            for k in i.locs:
                if "LIDOddity" in k:
                    REGISTRY.setKey(k, "found", False) 

        # clean up not done repair tasks
        for actor in [tris]:
            for a in actor.status:
                if "QID_TSK" in a:
                    actor.status.remove(a)
            if GAME.questSys.inProgress("QID_TRIS_SEXTRAIN2"):
                tris.tallyUp("Autotrained", 1)

        for q in GAME.questSys.activeQuests:
            if "QID_TSK" in q.ID:
                GAME.questSys.purgeQuest(q.ID)

        # quest related tasks xxx
        if GAME.questSys.inProgress("QID_TRIS_DILDOPRACTICE"):
            tris.tallyUp("Dildo Practice", 1)

        if GAME.questSys.inProgress('QID_MAIN_QUTHOR_QUARRY_MAP') and GAME.getSpaceLoc().ID == "LIDQuarry":
            vee.counters["quarry_analysis"] = vee.counters.get("quarry_analysis",0)+1
            vee.setAttr("ENE", max(vee.getAttr("ENE")-50, 0))

        # T'Ris stress management override
        if "tris_advice" in moira.done:
            tris.setAttr("STS", min(tris.getAttr("STS")+20, 100))

        nimhe_mags = [x for x in ["ITMPonyMag01", "ITMPonyMag02", "ITMPonyMag03"] if nimhe.hasItem(x)]
        if nimhe_mags:
            nimhe.hasDoneToday(random.choice(nimhe_mags))

        # various scrubbers / housekeeping 
        if "krell_tag" in moira.tags:
            moira.tags.remove("krell_tag")



    call hour_passes() from _call_hour_passes 
    scene exterior_smart with fade

    # repair animation housekeeping:
    if "intro_repair" in GAME.mc.done: 
        $ unrepaired = len(GAME.repQueue)
        python:
            for i in GAME.repQueue:
                GAME.repMisses.append(i)
        $ rMax = 4-unrepaired
        # $ GAME.repQueue = []
        $ spots = [x.ID for x in GAME.aElem.values() if "AERep" in x.ID]
        if rMax > 0:
            $ GAME.repQueue += random.sample(spots,random.randint(0,rMax)) # repairs for the day

    # quest trigger housekeeping 
    if len (GAME.lab.parts) >= 10 and not GAME.questSys.isActive("QID_BOT_MYSTERY"):
        $ nimhe.hasDone("parts_missing_noticed")

    # fill mission rosters & traders 

    python:
        # CR-0827 START ==========
        for x in GAME.starSys.values():
            mTypes = ["transport"] 
            if GAME.questSys.isDone("QID_PIRATE_TASK"):
                mTypes.append("bounty")    
            if GAME.questSys.isDone('QID_PIRATE_LANDING'):
                mTypes.append("smuggling")
            x.missionsRestock(mTypes)
        # CR-0827 END ============

    # Re-fill Incoming orders
    if GAME.questSys.isDone('QID_BOT_ARCADE'):
        call bot_roll_order() from _call_bot_roll_order_1 

    # Miscellaneous housekeeping
    if "intro_mess_pre" in bb_2.done: # CR-0803 weird fix, clean up in V1.20
        $ bb_2.hasDone("intro_mess") # CR-0803

    #####################################################################
    #				NIGHT ACTION / EVENT REPORTS	  						    #
    #####################################################################

    # player base related / special recovery 
    # construction of base buildings
    if GAME.base.unlocked:
        python:
            for x in [elem for elem in GAME.base.getSurface().elems.values()]:
                if x.status > 0:
                    x.status -= 1
                    if x.status == 0:
                        GAME.reports.append(["CONSTRUCTION COMPLETED", "The construction of your {}{}{} on Tenaris has been completed. \n\nThe unit is ready for use now.".format(C_OR_B, x.name, C_OR_E), ["Continue"], "05_gui/ico_gui_quest.png", "blue"])  
                        x.found = True 
                        
    # crew recovery & events
    if GAME.ship.status == "landed" and GAME.ship.surfaceID in ["SUIDTenaris"]:
        python:
            for actor in GAME.crew:
                actor.setAttr("MOD",100) 
                actor.setAttr("STS",0) 
                if actor == vee: # CR-0825
                    actor.setAttr("ENE",100) # CR-0825
            GAME.reports.append(["FULL RELAXATION", "Having spent a night on the Base, everyone's stress is relieved and a positive mood has spread throughout the crew...".format(), ["Continue"], "05_gui/ico_gui_heart.png", "blue"])  
    

    $ GAME.base.autoStock()

    # base reporting
    while GAME.reports:
        $ report = GAME.reports.pop()
        queue sound "audio/notify.wav"

        # special cutscenes
        # pet uniform replating khelara
        if report[0] == "HULL REPAIR REPORT" and GAME.getSpaceLoc().ID == "LIDStationArellarti":
            call cutscene_khelara("replate_arellarti") from _call_cutscene_khelara
        else:
            # standard notificatons
            call large_notify(report[0], report[1], report[2], report[3], report[4]) from _call_large_notify_2 

    call drone_handler() from _call_drone_handler 

    # Ignored repair damages 
    if GAME.repMisses:
        pass
    # Trophy assessments 
    call trophy_assessment() from _call_trophy_assessment 

    # Failed Missions 
    call mission_overnight_check() from _call_mission_overnight_check 

    # Escaped Bots  
    call sexbot_escape() from _call_sexbot_escape 

    # Arcade Earnings 
    call sexbot_arcade_earnings() from _call_sexbot_arcade_earnings 

    # autotrain execute and results 
    call sexbot_autotrainer() from _call_sexbot_autotrainer 

    # incoming item queue 
    call incoming_cargo_queue() from _call_incoming_cargo_queue 

    # exploration bonus 
    if "INV_EXPLORE" in GAME.investments:
        call check_exploration_bonus() from _call_check_exploration_bonus 

    return()

label night_passes_post():

    #####################################################################
    #                EVENTS POST WAKEUP
    #####################################################################

    # "You awaken to a new day..." with dissolve
    $ GAME.log = []
    $ GAME.occurredToday = []

    scene room_captain_smart with fade

    show screen header()    
    if levelUpAt(300, GAME.mc.lvl) <= GAME.mc.exp:
        queue sound "audio/success.wav" 
        $ GAME.mc.lvl += 1
        call simple_notify("LEVEL UP!", "You have reached Level {}.".format(GAME.mc.lvl), ["Continue"], "08_items/ico ITMCup.png") from _call_simple_notify_7 
 
    # dream comments after visits by V
    if "dream_one" in GAME.mc.status:
        queue sound "audio/notify.wav"
        $ GAME.mc.status.remove("dream_one")
        mc "{i}\"What a strange dream...\"{/i}"
        if not GAME.mc.hasDone("first_dream"):
            mc "{i}\"I wonder what 'Give Me Energy' meant...\"{/i}"
            mc "{i}\"Maybe that's a way to open the glass container.\"{/i}"
        
    if "dream_two" in GAME.mc.status:
        queue sound "audio/notify.wav"
        $ GAME.mc.status.remove("dream_two")
        mc "{i}\"I feel tired...almost like I've been drained of life.\"{/i}"

    if "dream_three" in GAME.mc.status:
        queue sound "audio/notify.wav"
        $ GAME.mc.status.remove("dream_three")
        mc "{i}\"I feel tired, ...\"{/i}"
        mc "{i}\"And my dreams are getting more intense...\"{/i}"        
        mc "{i}\"I am getting closer to something...\"{/i}"
    call quest_updater() from _call_quest_updater_5 
        
    # quest related advancement comments
    if GAME.mc.getTally("Repair Jobs") >= 8 or (GAME.mc.getTally("Repair Jobs") >= 2 and GAME.day >= 8): # CR-0983
        if not GAME.mc.hasDone("favour_idea"):
            play sound "audio/notify.wav"
            mc "\"{i}With all those repair jobs I've been doing lately...{/i}\""
            mc "\"{i}I think T'Ris should give me some reward...{/i}\""
            mc "\"{i}I've never seen her clean a single plasma duct...{/i}\""
            mc "\"{i}I'll ask her for a favour tonight!{/i}\""
            mc "\"{i}Here comes Captain [GAME.mc.name]...{/i}\""
            mc "\"{i}...Seducer of Galactic Maidens!{/i}\""
    call quest_updater() from _call_quest_updater_6 

    # uniform complaint Nimhe 
    if GAME.questSys.inProgress("QID_UNIFORM_ROLLOUT"):
        call cutscene("uniform_argument") from _call_cutscene_3 

    #####################################################################
    #					ORDERS		
    #####################################################################
    # Crew Daily AI Update
    call crew_assessment() from _call_crew_assessment 

    # Crew and MC incremental skill tracker assessment
    call skill_assessment() from _call_skill_assessment 

    # orders of the day 
    if "intro_repair" in GAME.mc.done:
        queue sound "audio/notify.wav"
        mc "\"Let's review today's orders...\""
        call daily_orders() from _call_daily_orders 
        scene room_captain_smart with fade        

    #####################################################################
    #					INFO EVENTS MORNING POST-ORDERS	/ STACKABLE	xxx
    #####################################################################
    # signal inhibitor sidequest
    if GAME.questSys.isDone("QID_VEE_FAMILIARIZE") and not "signal_inhibitor_talk" in nimhe.done:
        call cutscene_nimhe("signal_inhibitor_talk") from _call_cutscene_nimhe_1 
        $ GAME.mc.hasDoneToday("news")
        call quest_updater() from _call_quest_updater_7 
    # nx010 quests
    if GAME.questSys.isDone("QID_MAIN_SWARMGATE_REPAIR") and REGISTRY.getKey("SSIDQuthor", "SSIDIltari") == "blocked":
        call cutscene_quthor("repair_bulletin") from _call_cutscene_quthor_1 
        $ GAME.mc.hasDoneToday("news") # CR-0960

    
    # Quthor Map waiting for news
    if "4th_map" in kythera.done and GAME.timerGet("T_MAP4") == 0 and "contact_nx010" not in ylyee.done: # CR-2007 
        call cutscene_quthor("contact_nx010") from _call_cutscene_quthor_2 
        $ GAME.timerPurge("T_MAP4")
        $ GAME.mc.hasDoneToday("news")
        $ ylyee.hasDone("contact_nx010")
        call quest_updater() from _call_quest_updater_8 

    # NX010 Map waiting for news
    if "5th_map" in kythera.done and GAME.timerGet("T_MAP5") == 0 and "ylyee_waystation_mission" not in ylyee.done: # CR-2007
        call cutscene_quthor("ylyee_waystation_mission") from _call_cutscene_quthor_3 
        $ GAME.timerPurge("T_MAP5")
        $ GAME.mc.hasDoneToday("news")
        $ ylyee.hasDone("ylyee_waystation_mission")
        call quest_updater() from _call_quest_updater_9 

    # CR-2007 START - DEPRECATED / DOUBLE CODE / REMOVE V1.50 =====================
    if GAME.timerGet("T_MAP4") == 0 and "4th_map_result" not in ylyee.done and GAME.questSys.isDone('QID_MAIN_QUTHOR_MAP3') and False: # DEACTIVATED
        $ ylyee.hasDone("4th_map_result")
        call cutscene_quthor("contact_nx010") from _call_cutscene_quthor_4 
        $ GAME.timerPurge("T_MAP4")
        $ GAME.mc.hasDoneToday("news")
        call quest_updater() from _call_quest_updater_10 
    # CR-2007 END - DEPRECATED / DOUBLE CODE / REMOVE V1.50 =======================

    if GAME.timerGet("T_MINOS_NEWS") == 0 and "minos_news" not in GAME.mc.done and GAME.questSys.inProgress('QID_QUTHOR_PRE_KICKOFF'):
        $ GAME.mc.hasDone("news_quthor")
        call cutscene_quthor("minos_news") from _call_cutscene_quthor_5 
        $ GAME.timerPurge("T_MINOS_NEWS")
        $ GAME.mc.hasDoneToday("news")
        call quest_updater() from _call_quest_updater_11 

    if GAME.timerGet("T_BUREAUCRACY") == 0 and GAME.questSys.inProgress('QID_MAIN_QUTHOR_MIL_WAIT'):
        call cutscene_quthor("forge_news") from _call_cutscene_quthor_6 
        call quest_updater() from _call_quest_updater_12 

    if GAME.questSys.inProgress('QID_MAIN_QUTHOR_CONTACT') and GAME.getSpaceLoc().ID == "LIDRendezvousQuthor75":
        call cutscene_quthor("belit_met") from _call_cutscene_quthor_7 
        call quest_updater() from _call_quest_updater_13 
        scene room_captain_smart with fade

    if vee.counters.get("quarry_analysis",0)>=2 and GAME.questSys.inProgress('QID_MAIN_QUTHOR_QUARRY_MAP'):
        call cutscene_quthor("quarry_mapped") from _call_cutscene_quthor_8 
        call quest_updater() from _call_quest_updater_14 

    # moira uniform exemption
    if  "ITMUniformKrell" in moira.done and "exemption_talk" not in moira.done:
        $ moira.hasDone("exemption_talk")
        queue sound "audio/notify.wav"
        "Moira pays you a surprise visit..."
        call cutscene_moira("exemption_talk") from _call_cutscene_moira 

    # moira antivirus checked
    if GAME.timerGet("T_ARRIVAL") == 0 and GAME.questSys.inProgress('QID_QUTHOR_WAIT'):
        call cutscene_quthor("moira_resolution_drengar") from _call_cutscene_quthor_9 
        $ GAME.timerPurge("T_ARRIVAL")
        call quest_updater() from _call_quest_updater_15 

    # moira antivirus done
    if GAME.timerGet("T_ANTIVIRUS") == 0 and GAME.questSys.inProgress('QID_QUTHOR_MOIRA_CURE'):
        call cutscene_quthor("moira_cure") from _call_cutscene_quthor_10 
        $ GAME.timerPurge("T_ANTIVIRUS")
        call quest_updater() from _call_quest_updater_16 

    # moira_locate
    if GAME.timerGet("T_MOIRA_LOCATE") == 0 and GAME.questSys.inProgress('QID_QUTHOR_MOIRA_LOCATE'):
        $ khelara.hasDone("moira_located")
        call cutscene_quthor("moira_khelara_located") from _call_cutscene_quthor_11 
        $ GAME.timerPurge("T_MOIRA_LOCATE")
        call quest_updater() from _call_quest_updater_17 

    # quthor news virus
    if GAME.timerGet("T_QUTHOR") == 0 and "news_quthor" not in GAME.mc.done and "quthor_barred" in GAME.mc.done:
        $ GAME.mc.hasDone("news_quthor")
        call cutscene_quthor("moira_news") from _call_cutscene_quthor_12 
        $ GAME.timerPurge("T_QUTHOR")
        call quest_updater() from _call_quest_updater_18 

    # lower deck repair mission 
    if GAME.questSys.inProgress("QID_INTRO_LOWER3"):
        $ bb_2.hasDone("lower_deck_cleared") 
        $ bb_2.status.remove("repair_mission")  
        queue sound "audio/notify.wav"
        "In the morning you are visted by BB-2..." 
        queue sound "audio/drone_beep.wav"
        bb2 "\"Lower Deck repair is complete.\"" 
        bb2 "\"The Turbolift has been activated.\"" 
        bb2 "\"Decks 2 and 3 are now accessible.\"" 
        mc "\"Excellent!\"" 
        mc "\"What's down there?\""
        bb2 "\"All kind of quarters and facilties.\""
        bb2 "\"I suggest you take a look around.\""
        mc "\"Did you see any sign of V?\""
        bb2 "\"Curiously enough, no.\"" 
        mc "\"How peculiar...\""
        call quest_updater() from _call_quest_updater_19 
        $ GAME.hasOccurredToday("morning_event") 
    
    # corridor anomaly report by bb_2 
    if khelara in GAME.crew and GAME.ship.getSubSysStatus("uplink") >= 50 and 'nanite_report' not in bb_2.done and 'intro_corridor' in GAME.mc.done:
        call cutscene_vee("bb2_corridor_anomaly") from _call_cutscene_vee_3 
        call hour_passes() from _call_hour_passes_1 
        $ GAME.hasOccurredToday("morning_event") 

    # Pirate base second kickoff path
    if (GAME.mc.getTally("Arcade Deliveries") >= 1 or False) and not GAME.questSys.isActive("QID_PIRATE_KICKOFF"): # CR-0297
        queue sound "audio/notify.wav"
        "BB-2 pays you a surprise visit..."
        queue sound "audio/drone_beep.wav"
        bb2 "\"Captain [GAME.mc.name], I have a business proposal to make...\""
        mc "\"What is it?\""
        bb2 "\"I noticed that you sent a bot to the Arcade for earnings.\""
        mc "\"Yes, we need to earn some money.\""
        bb2 "\"We could make considerably more money, if we made illegal bots.\""
        mc "\"Nimhe once talked about illegal Bots but she didn't go into detail...\""
        bb2 "\"Authorities don't like artificial lifeforms to become too intelligent...\""
        bb2 "\"So they prohibited all bot trade with entities of IQ 140 or higher...\""
        mc "\"And?\""
        bb2 "\"As can be expected, now such Bots are in high demand...\""
        bb2 "\"Nimhe has a history of making them to satisfy the market needs...\""
        bb2 "\"There is a lot of money to be made...\""
        bb2 "\"I suggest you talk to her...\""
        mc "\"Thank you for the hint.\""
        mc "\"I will discuss it with her.\""
        $ GAME.mc.hasDone("illegal_bot_warning")
        call quest_updater() from _call_quest_updater_20 
        $ GAME.hasOccurredToday("morning_event") 

    # missing bot part quest 
    if "parts_missing_noticed" in nimhe.done and not GAME.questSys.isActive('QID_BOT_MYSTERY') and GAME.questSys.isActive("QID_PIRATE_WEAPONS"):
        call cutscene_nimhe("parts_missing_complaint") from _call_cutscene_nimhe_2 
        $ GAME.hasOccurredToday("morning_event") 

    # nimhe retrieve quest
    if GAME.mc.attr["NOT"] > 10 and not GAME.questSys.isActive("QID_NIMHE_RETRIEVE_KICKOFF") and REGISTRY.getKey("LIDAsteroidsOuter", "found"):
        call cutscene_nimhe("retrieve_kickoff") from _call_cutscene_nimhe_3 
        $ GAME.hasOccurredToday("morning_event") 

    # v request 
    if vee.getTally('Days in Crew') >= 3 and "morning_visit" not in vee.done:
        queue sound "audio/notify.wav"
        "Vee pays you a visit..."
        v "\"I have concluded my studies of the crew's social interactions.\""
        mc "\"Good to hear.\""
        v "\"I found that Swarm knowledge of biological species is superior but one sided.\"" # CR-0298
        mc "\"How so?\""
        v "\"It is purely theoretical.\""
        v "\"You are therefore to assist me in acquiring practical social skills.\""
        v "\"Visit me in my charging station once my energy levels are at a maximum.\""
        mc "\"Happy to assist.\""
        v "\"In return for your assistance I shall analyse astronomical phenomena...\""
        v "\"My Swarm knowledge allows me to detect patterns invisible to biological lifeforms.\""
        v "\"This concludes our interaction.\""
        queue sound "audio/notify.wav"
        call large_notify("JOB UNLOCKED - ASTRO ANALYSIS", "Vee has offered to analyse spatial patterns around you for noteworthy phenomena. They might yield information or rare items if explored.\n\nYou can assign Vee this job in the morning.", ["Continue"], "05_gui/ico_gui_hostile_swarm.png", "pink") from _call_large_notify_3 
        $ vee.jobs.append("JOB_Astro")
        $ vee.hasDone("morning_visit")
        call quest_updater() from _call_quest_updater_21 
        $ GAME.hasOccurredToday("morning_event") 

    # khelara appreciation / uniform quest trigger 
    if khelara.attr["APP"] >= 3 and not GAME.questSys.isActive("QID_KHELARA_KICKOFF"):
        $ GAME.mc.hasDone("khelara_idea")
        call quest_updater() from _call_quest_updater_22 
        $ GAME.hasOccurredToday("morning_event") 

    if khelara.attr["EXH"] >= 4 and not GAME.questSys.isActive("QID_KHELARA_REVEALING"):
        queue sound "audio/notify.wav"
        mc "{i}\"I think Khelara has grown accustomed to her uniform by now.\"{/i}"
        mc "{i}\"It's time I bring her a more revealing version I'd say...\"{/i}"
        $ GAME.hasOccurredToday("morning_event") 

    if khelara.attr["EXH"] >= 6 and not 'khelara_training_idea' in GAME.mc.done:
        queue sound "audio/notify.wav"
        mc "{i}\"Khelara has grown used to her uniform...\"{/i}"
        mc "{i}\"I think it's time I start training her for real...\"{/i}"
        $ GAME.mc.hasDone("khelara_training_idea")
        $ GAME.hasOccurredToday("morning_event") 

    if GAME.questSys.inProgress('QID_TRIS_SEXTRAIN2') and 'autotrain_reflect' not in tris.done and GAME.timerGet("T_TRIS_AUTO") == 0:
        $ tris.hasDone("autotrain_reflect")
        queue sound "audio/notify.wav"
        mc "{i}\"T'Ris has had some time now to think about her Autotrainer experience...\"{/i}"
        mc "{i}\"Maybe it is time I make my move...\"{/i}"
        $ GAME.timerPurge("T_TRIS_AUTO")
        call quest_updater() from _call_quest_updater_23 
        call quest_updater() from _call_quest_updater_24 

    # seraphine quest tiggers
    if GAME.questSys.isDone('QID_VEE_TRAIN') and not GAME.questSys.isActive('QID_SERAPHINE_KICKOFF'):
        queue sound "audio/notify.wav"    
        "Vee pays you a surprise visit..."
        v "\"I have important information.\""
        mc "\"What is it?\""
        v "\"After experiencing some interesting 'interactions' on this ship, I decided to stay onboard.\""
        mc "\"That is, ahem... much appreciated.\""
        v "\"As such, this vessel's continued existence is in my interest.\""
        mc "\"I am glad to hear that.\""
        v "\"Reflecting on The Swarms purpose for this ship I recalled a similar incident.\""
        mc "\"A similar incident?\""
        v "\"An occurrence linked to your Galaxy of Origin.\""
        v "\"Another craft has been translocated to this vicinity a short while ago.\""
        mc "\"With a visitor from our Galaxy?\""
        v "\"Yes.\""
        v "\"For unknown reasons it proved to be unsuitable for The Swarm's purpose.\""
        mc "\"Where is it?\""
        v "\"It appeared in the Arellarti System in Krell Space.\""
        mc "\"Transfer the star data to T'Ris, she should be able to mark it on your maps.\""
        v "\"Affirmative.\""
        "As quickly as she has appeared Vee leaves you..." with fade
        $ vee.hasDone("reported_incident")
        call quest_updater() from _call_quest_updater_25 
        $ GAME.hasOccurredToday("morning_event") 

    # crew ready for krell 
    if all([x.attr["EXH"]>=6 for x in [khelara, tris, vee, nimhe]]) and all([x.hasItem('ITMUniformKrell') for x in [khelara, tris, vee, nimhe]]) and not "crew_ready_krell" in GAME.mc.done:
        queue sound "audio/notify.wav"
        "T'Ris pays you a visit..."
        tri "\"The crew is ready for conforming to Krell regulations.\""
        tri "\"I suggest we proceed to the Gate.\""
        tri "\"After arrival in Krell Space I'll assemble the crew for a uniform roll call. \""
        mc "\"Excellent!\""
        $ GAME.mc.hasDone("crew_ready_krell")
        scene room_captain_smart with fade
        call quest_updater() from _call_quest_updater_26 
        $ GAME.hasOccurredToday("morning_event") 

    # holodeck fixed 
    if GAME.questSys.inProgress('QID_HOLO_REPAIR') and GAME.timerGet("T_FIXHOLO") == 0:
        call cutscene_seraphine("holo_repair") from _call_cutscene_seraphine_1 
        $ GAME.hasOccurredToday("morning_event") 
        $ GAME.timerPurge("T_FIXHOLO")

    # lab ship incident after sabotage
    if GAME.questSys.inProgress('QID_KRELL_YLYEE_WAIT') and "biolab_choice" not in GAME.mc.done:
        call cutscene("biolab_choice") from _call_cutscene_4 

    if GAME.questSys.inProgress("QID_MOIRA_SUB_PET_INSPECT") and "machine_setup" not in khelara.done and GAME.timerGet("T_MACHINE") == 0:
        call cutscene_khelara("machine_setup") from _call_cutscene_khelara_1 
        $ GAME.occurredToday.append("morning_event")

    # krogneath parade 
    elif  GAME.questSys.inProgress('QID_SERAPHINE_SUB_PARADE') and "dome_meeting" not in krogneath.done:
        call cutscene_seraphine("seraphine_parade") from _call_cutscene_seraphine_2 
        $ GAME.occurredToday.append("morning_event")

    #####################################################################
    #					POSTPONABLE EVENTS/ NON STACKING	
    #####################################################################
    if "morning_event" not in GAME.occurredToday: 
        if False:
            pass

        # moira tris visit
        elif GAME.questSys.isDone('QID_TRIS_SEXTRAIN3') and moira in GAME.crew and GAME.timerGet("T_TRIS_ADVICE") == 0 and 'tris_advice' not in moira.done:
            call cutscene_moira("tris_advice") from _call_cutscene_moira_1 

        # bb2 report on seraphine being bored
        elif GAME.timerGet("T_BORED") == 0 and "mood_talk" not in bb_2.done and GAME.questSys.isDone("QID_SERAPHINE_DEMANDS_BATHCHECK"): # CR-0736
            call cutscene_seraphine("bb2_seraphine_talk") from _call_cutscene_seraphine_3 
            $ GAME.timerPurge("T_BORED")
            call quest_updater() from _call_quest_updater_27 

        # seraphine shopping setup / nimhe repots back
        elif GAME.timerGet("T_SHOPPING_SETUP") == 0 and GAME.questSys.inProgress('QID_SERAPHINE_JOB_WAIT'):
            $ nimhe.hasDone("shopping_setup_report")
            call cutscene_seraphine("shopping_setup_report") from _call_cutscene_seraphine_4 
            $ GAME.timerPurge("T_SHOPPING_SETUP")
            call quest_updater() from _call_quest_updater_28 

        # seraphines uniform
        elif seraphine.counters.get('crates',0) >= 3 and not GAME.questSys.isActive('QID_SERAPHINE_UNIFORM_RACY'):
            queue sound "audio/notify.wav"
            mc "{i}\"Thinking of it, Seraphine has come along nicely as of late...\"{/i}"
            mc "{i}\"She has proven herself useful getting those crates...\"{/i}"
            mc "{i}\"I should integrate her better into the crew...\"{/i}"
            mc "{i}\"It's time I give her the first uniform...\"{/i}"
            $ seraphine.hasDone("uniform_kickoff")
            call quest_updater() from _call_quest_updater_29 


        # ylyee special mission contact 
        elif GAME.questSys.isDone('QID_KRELL_INTERCEPT') and GAME.questSys.isDone('QID_MULT_TRANSPORT') and "convoy_talk" not in ylyee.done:
            call cutscene("ylyee_contact") from _call_cutscene_5 

        elif GAME.questSys.inProgress('QID_KRELL_YLYEE_WAIT') and GAME.timerGet("T_VIRUS_DEPLOYED") == 0:
            call cutscene("ylyee_confirm") from _call_cutscene_6 
            $ GAME.timerPurge("T_VIRUS_DEPLOYED")
            $ GAME.hasOccurredToday("morning_event")

        # xenos library expo 
        elif GAME.questSys.inProgress('QID_XENOS_WAIT_ACCESS') and "expo_library" not in kythera.done:
            $ kythera.hasDone("expo_library")
            call cutscene("expo_library") from _call_cutscene_7 

        # ylyee xenos mission contact 
        elif GAME.questSys.inProgress('QID_XENOS_WAIT_ACCESS') and GAME.timerGet("T_XENOS_WAIT") == 0:
            call cutscene("expo_library_ylyee") from _call_cutscene_8 
            $ GAME.timerPurge("T_XENOS_WAIT")

        # ylyee library analysis 
        elif GAME.questSys.inProgress('QID_XENOS_LIBRARY_RESEARCH') and GAME.timerGet("T_LIBRARY_RESULT") == 0:
            call cutscene("library_research_report") from _call_cutscene_9 
            $ GAME.timerPurge("T_LIBRARY_RESULT")

        # zealot present 
        elif GAME.timerGet("T_ZEALOT") == 0 and GAME.questSys.inProgress('QID_XENOS_LIBRARY_DEAL'):
            queue sound "audio/notify.wav"
            "A transport drone from the Zealots of Yr has arrived."
            mc "\"Ah, the items the Zealots promised...\""
            $ GAME.mc.hasDone("xenos_fragment_delivered")
            $ item = GAME.items["ITMMapPrecursorXenos"]
            queue sound "audio/notify.wav"
            call find_notify(item, "ITEM FOUND") from _call_find_notify 
            queue sound "audio/load.wav"
            $ GAME.mc.addItem(item.ID)
            mc "\"Time I report back to Kythera...\""
            $ GAME.timerPurge("T_ZEALOT")
            call quest_updater() from _call_quest_updater_30 
            call quest_updater() from _call_quest_updater_31 
            

        # krogneath's request / bio supplies
        elif GAME.questSys.isDone('QID_SERAPHINE_ARELLARTI_FIND') and "krog_trading_kickoff" not in GAME.mc.done:
            queue sound "audio/beep.wav"
            "You receive an urgent message from Krogneath!"
            "It is vague and asks that you contact him in the Pirate Cantina."
            queue sound "audio/notify.wav"
            mc "{i}\"I wonder what he wants...?\"{/i}"
            mc "{i}\"I better see him at the next opportunity...\"{/i}"
            $ GAME.mc.hasDone("krog_trading_kickoff") 
            call quest_updater() from _call_quest_updater_32 
            $ GAME.hasOccurredToday("morning_event") 

        # krogneath's request / seraphine discovered
        elif not GAME.questSys.isActive('QID_SERAPHINE_SUB_KICKOFF') and seraphine.getAttr("EXH") >= 6:
            queue sound "audio/beep.wav"
            "You receive an urgent message from Krogneath!"
            "It is vague and asks that you contact him in the Pirate Cantina..."
            queue sound "audio/notify.wav"
            mc "{i}\"I wonder what Krogneath wants this time...?\"{/i}"
            mc "{i}\"I better see him at the next opportunity...\"{/i}"
            $ krogneath.hasDone("seraphine_message")
            call quest_updater() from _call_quest_updater_33 
            $ GAME.hasOccurredToday("morning_event") 
    

        # investments unlocked 
        elif GAME.money > 100000 and "invest_info" not in GAME.mc.done and "morning_event" not in GAME.occurredToday:
            queue sound "audio/notify.wav"
            "Your trading and mining skills have attracted some attention..."
            "You receive a message regarding investment opportunities..."
            queue sound "audio/notify.wav"
            call simple_notify("COMPUTER FEATURE UNLOCKED", "Iltari Investment Portal", ["Continue"], "05_gui/ico_gui_quest.png") from _call_simple_notify_8 
            mc "{i}\"Investments, hmmm...\"{/i}"
            mc "{i}\"Interesting.\"{/i}"
            mc "{i}\"I should have a look at the computer later...\"{/i}"
            $ GAME.mc.hasDone("invest_info")
            $ GAME.hasOccurredToday("morning_event")        

        # disciplining kickoff after crew complete and settled in
        elif GAME.questSys.isActive('QID_VEE_TRAIN') and "infraction_expo" not in vee.done:
            call cutscene("disciplining_expo") from _call_cutscene_10 

        # seraphine's demands (3 day cooloff timer after find)
        elif GAME.questSys.isDone('QID_SERAPHINE_ARELLARTI_FIND') and GAME.timerGet("T_DEMANDS") == 0 and not GAME.questSys.isActive('QID_SERAPHINE_DEMANDS_BATHTUB'):
            call cutscene_seraphine("seraphine_demands") from _call_cutscene_seraphine_5 
            $ GAME.timerPurge("T_DEMANDS")
        
        # bathtub renovation
        elif GAME.questSys.inProgress('QID_SERAPHINE_DEMANDS_BATHWAIT') and GAME.timerGet("T_RENOVATE") == 0 and not seraphine.getLocOverride():
            queue sound "audio/notify.wav"
            "Khelara pays you a visit..."

            # CR-1098 START
            if False: # Call hierarchy preservation / Cleanup 1.50
                call cutscenes_seraphine("present_bathtub") from _call_cutscenes_seraphine 
            call cutscene_seraphine("present_bathtub") from _call_cutscene_seraphine_6 
            # CR-1098 END

            $ GAME.timerPurge("T_RENOVATE")

        # nimhe material request
        elif nimhe.getAttr("SLU") >= 9 and "materials_talk" not in nimhe.done:
            queue sound "audio/notify.wav"
            "Nimhe pays you a visit..."
            nim "\"Listen, I am working on an important project...\""
            nim "\"I need AI-Cores for that...\""
            mc "\"We occasionally have some spares...\""
            mc "\"I see what I can do...\""
            nim "\"Thanks.\""
            $ nimhe.hasDone("materials_talk")
            call quest_updater() from _call_quest_updater_34 

        # rando news 
        elif random.randint(0,100) >= 50 and "news" not in GAME.mc.doneToday:
            call sectornet_news() from _call_sectornet_news 
        elif "INV_NEWS" in GAME.investments and "news" not in GAME.mc.doneToday:
            call trading_news() from _call_trading_news 

    call sandbox_interior_prepare_scene() from _call_sandbox_interior_prepare_scene_11 
   
    return()  

#####################################################################
#					HOUR PASSES										
#####################################################################
label hour_passes(amount = 1, mode = "standard"):

    #####################################################################
    #					SCRUBBERS		
    #####################################################################
    $ GAME.scrubber()

    #####################################################################
    #					TIME PASSING		
    #####################################################################
    python:
        for i in range(amount):
            GAME.hour += 1
            if GAME.hour == 24:
                GAME.hour = 0
            for actor in GAME.crew:
                actor.updateAI(mode) 
    #####################################################################
    #					INTERCEPTS		
    #####################################################################
    call away_mission_checks() from _call_away_mission_checks_1 
    # nimhe bot skills
    if GAME.mc.hasAchievement("arcade tycoon") and "JOB_Upgrade" not in nimhe.jobs:
        queue sound "audio/notify.wav"
        "Nimhe pays you a surprise visit..."
        nim "\"I've found out a few interesting capabilities of your Bot Lab today.\"" # CR-0539
        mc "\"What is it?\""
        nim "\"I think I can use it to upgrade parts.\""
        nim "\"Just let me know in the morning when I should make that a priority.\""
        mc "\"Great news!\""
        mc "\"I will do that.\""
        queue sound "audio/notify.wav"
        call large_notify("NEW ORDER AVAILABLE!", "You can now task Nimhe in the morning to upgrade parts. She will assemble one higher grade part from three lower grade parts.\n\nNimhe will create up to three upgrades per day, depending on part stock.", ["Continue"], "08_items/ico ITMCrateBots.png") from _call_large_notify_4 
        $ nimhe.jobs += ["JOB_Upgrade"]

    #####################################################################
    #					CREW REPORTS		
    #####################################################################
    # Crew reports
    if GAME.hour >= 10:
        while GAME.reports:
            $ report = GAME.reports.pop(0)
            queue sound "audio/notify.wav"
            call large_notify(report[0], report[1], report[2], report[3], report[4]) from _call_large_notify_5 
     
    return()

