#####################################################################
#                MG MAINTENANCE
#####################################################################
default subunittype = ""
default matrixPos2 = []
default plateQuad = ""
default plateSlot = ""

screen mg_maintenance_scr(*args):
    $ subSysKey = args[0]
    $ cRows = [0, 120, 240]
    $ cCols = [0, 110, 220, 330]
    $ subunits = ["ITMAICore", "ITMPositron", "ITMFlux", "ITMOutput"]
    $ maintMode = args[1]
    
    image "03_minigames/bg_systems_ohweemod.png"
    #image "03_minigames/bg_{}.png".format(maintMode)
    #text "03_minigames/bg_{}.png".format(maintMode)

    $ titleText = {"hull": "HULL CONFIGURATION", "systems": "SYSTEMS MANAGEMENT"}[maintMode]
    text C_HI_B + titleText + C_HI_E size FSIZE_LARGE xalign 0.95 ypos 120
    $ subSys = GAME.ship.subSys[subSysKey]
    
    if maintMode == "systems" or maintMode == "hull":

        #####################################################################
        #                COMPONENT SELECTION
        #####################################################################
        if subSys[0]:
            # CR-0251 START
            $ item = GAME.items[subSys[0]]
            frame xsize 372 ysize 372 pos 158, 271 background Solid ("#00000000"):
                image "08_items/ico bg1.png" xalign 0.5 yalign 0.5 zoom 0.7
                image "08_items/ico {}.png".format(item.ID)  xalign 0.5 yalign 0.5 zoom 0.7
                button action NullAction() tooltip item.ID 
            #image "03_minigames/item_{}_512x372.png".format(subSysKey) pos 172, 356
            vbox xsize 412 pos 208, 659 spacing 25:
                text "{}".format(GAME.items[subSys[0]].getName(["noArt", "cap", "col"])) #size FSIZE
                #text "{}".format(GAME.items[subSys[0]].description) size FSIZE
                # CR-0251 END

            #####################################################################
            #					GENERAL LOADOUT		
            #####################################################################
            if GAME.ship.supportsAddOns(subSysKey):
                $ maxLoadout = GAME.ship.getLoadoutMax(subSysKey)
                $ addOns = GAME.ship.getAddOns(subSysKey)
                vbox pos 536, 286 spacing 10:
                    for i in range(6):
                        if maxLoadout >= i+1:
                            frame xsize 48 ysize 48 background Solid("#00000000"):
                                image "03_minigames/ico_slot_subunit.png" xalign 0.5 yalign 0.5 zoom 0.5
                                if addOns[i]:
                                    image "08_items/ico {}.png".format(addOns[i].ID) xalign 0.5 yalign 0.5 zoom 0.175
                                button action Return(["addon", subSysKey, i, addOns[i]])
                        else:
                            frame xsize 48 ysize 48 background Solid("#00000000"):
                                text "-" xalign 0.5 yalign 0.5

        else:
            text "NOT INSTALLED" pos 338, 442 xalign 0.5

        hbox pos 90, 215 spacing 20:
            #imagebutton hover "05_gui/gui arrow left.png" idle "05_gui/gui arrow left.png" action Return(["left"])
            frame xsize 100 ysize 40 yalign 0.5 background Solid("#0099ccff"):
                text "PREV" size FSIZE xalign 0.5 ypos 5
                button action Return(["left"])
            hbox xsize 270 yalign 0.5:
                text C_HI_B+subSysKey.upper()+C_HI_E xalign 0.5 yalign 0.5
            frame xsize 100 ysize 40 yalign 0.5 background Solid("#0099ccff"):
                text "NEXT" size FSIZE xalign 0.5 ypos 5
                button action Return(["right"])
        key "K_LEFT" action Return(["left"])
        key "K_RIGHT" action Return(["right"])
        
        #OhWee_Mod_Code
        
        frame xsize 640 ysize 70 pos 385, 150 xalign 0.5 yalign 0.5 background Solid ("#0000FF50"):
            hbox pos 345,10 spacing 50:
                $ x = len(subSystems)
                $ yx = -1
                $ yx0 = 0
                $ yz = -1
                for i2 in range(0, x):
                    $ y = (subSystems[i2])
                    if GAME.ship.hasSubSys(y):
                        $yz += 1
                for i3 in range(0, x):
                    $ y1 = (subSystems[i3])
                    if GAME.ship.hasSubSys(y1):
                        $yx += 1
                        $ y2 = GAME.ship.getSubSys(y1)
                        $ item1 = GAME.items[(y2)]
                        fixed xsize 30 ysize 30:# background Solid ("#00000000"):
                            if yz / 2 < yx:
                                $ xoff_spacing = (yx * -150) + (yz * 70) + (yx0 * -80) + 25
                            else:
                                $ xoff_spacing = (yx * -150) + (yx0 * -150) - 115 #+ (yz * -25) 

                            if i3 == 0:
                                image "08_items/ico bg1.png" xalign 0.5 yalign 0.5 zoom 0.25 xoffset -78
                                imagebutton idle "08_items/ico {}.png".format(item1.ID)  xalign 0.5 yalign 0.5 xoffset -78:
                                    action NullAction() tooltip item1.ID
                                    at customzoom2
                            else:
                                imagebutton idle "08_items/ico {}.png".format(item1.ID):
                                    xalign 0.5 
                                    yalign 0.5 
                                    xoffset xoff_spacing
                                    action Return(["systype", y1]) tooltip item1.ID 
                                    at customzoom
                                if GAME.ship.supportsAddOns(subSystems[i3]):
                                    $ addOns2 = GAME.ship.getAddOns(subSystems[i3])
                                    $ maxLoadout2 = GAME.ship.getLoadoutMax(subSystems[i3])
                                    $addoncount = 0
                                    for i in range(6):
                                        if addOns2[i] :
                                            $addoncount += 1
                                    #$ addoncounttext = str(addoncount) + "of" + str(maxLoadout2)
                                    fixed:
                                         text str(addoncount) + "{size=18}of{/size}" + str(maxLoadout2) xalign 1.0 ypos -35 xoffset xoff_spacing size 24 color "#0FF"
                                $ sys_eff = str(int(GAME.ship.getSubSysStatus(subSystems[i3])))
                                text sys_eff + "%" xalign 0.5 ypos 50 xoffset xoff_spacing size FSIZE color "#0FF"
                    elif i3 == 0:
                        fixed xsize 30 ysize 30:# background Solid ("#00000000"):
                            image "08_items/ico bg1.png" xalign 0.5 yalign 0.5 zoom 0.25 xoffset -78
                        $ yx0 = 1
                        

            text "___" xpos 640 ypos -43 size 32 color "0AC" bold True kerning -10
            text "Subunits" xpos 685 ypos -25 size 24 color "#999"
            text "___" xpos 640 ypos 44 size 32 color "0AC" bold True kerning -10
            text "Efficiency" xpos 685 ypos 62 size 24 color "#999"
            
            #End_OhWee_Mod_Code
        #####################################################################
        #                SUBUNITS
        #####################################################################
        
        #OhWee mod code
        
        text "In Cargo:" pos 1000, 115 size 18 color "#0cf"

        hbox xpos 682 ypos 240 spacing 68:
            $ subunits2 = ["ITMAICore", "ITMPositron", "ITMFlux", "ITMOutput"]
            for i in subunits2:
                frame xysize 40, 40 background "#000a":
                    image "08_items/ico {}.png".format(i) zoom 0.125 xalign 0.5 yalign 0.5
                    text "{}".format(GAME.ship.cargo.count(GAME.items[i])) xoffset 30 yoffset 20 size 20 color "#fff" #"#0CF"
            
            frame xysize 40, 40 xoffset -32 background "#000a":
                image "08_items/ico ITMTunneling.png" zoom 0.125 xalign 0.5 yalign 0.5
                text "{}".format(GAME.ship.cargo.count(GAME.items["ITMTunneling"])) xoffset 48 yoffset 20 size 20 text_align 1.0 xanchor 1.0 color "#fff"#"#0CF"
        text "Tunneling\n Modules" pos 1142, 267 size 21 text_align 1.0 color "#999"
                
        #OhWee mod code
    
        
        for j in range(3):
            for i in range(4):
                # draw connection line:
                if i == 0:
                    if GAME.ship.pathClosed(subSysKey, j):
                        image "connection_active" xpos 620+cCols[i]+64 ypos 262+cRows[j]+62
                    else:
                        image "05_gui/mgm_inactive_line.png" xpos 620+cCols[i]+64 ypos 262+cRows[j]+62
                        
                # draw subunits
                
                frame xsize 80 ysize 80 pos 630+cCols[i]+32, 262+cRows[j]+34 background Solid("#ffffff00"):
                    image "03_minigames/ico_slot_subunit.png" xalign 0.5 yalign 0.5
                    
                    if subSys[j+1][i] == 1:
                        image "08_items/ico {}.png".format(subunits[i]) zoom 0.25 xalign 0.5 yalign 0.5
                        $ tooltext = subunits[i]
                    elif subSys[j+1][i] == 9:
                        image "08_items/ico {}.png".format("ITMTunneling") zoom 0.25 xalign 0.5 yalign 0.5
                        $ tooltext = "ITMTunneling"
                    else:
                        $ tooltext = ""
                        
                    $ matrixPos2 = [j,i]
                    $ subunit_type = subunits[i]
                    
                    button action (Play("sound", "audio/click.wav"), Show("subunit_popup_screen", matrixPos2=matrixPos2)) tooltip tooltext

                    #button action (SetVariable("matrixPos", [j, i]), Call("subunit_popup0")) tooltip tooltext
                    
                        #SetVariable("subunittype", subunits[i]), 
                    
                        #button action Return([ "subunit", subunits[i], [j,i] ]) tooltip subunits[i]
                        #button action Return([ "subunit", "ITMTunneling", [j,i] ]) tooltip "ITMTunneling"
                    
        #####################################################################
        #                SYSTEM TALLY
        #####################################################################
        vbox xsize 300 spacing 26 pos 1250, 262:
            text C_HI_B+"Subsystem Status"+C_HI_E
            text "{}".format(GAME.ship.getSubSysRating(subSysKey))
            text C_HI_B+"Efficiency"+C_HI_E
            text "{:.1f} %".format(GAME.ship.getSubSysStatus(subSysKey))
            text C_HI_B+"Output Power"+C_HI_E
            text "{:.2f} GW".format(GAME.ship.getSubSysOutput(subSysKey))

        #####################################################################
        #                MODE TOGGLE
        #####################################################################
        #frame xsize 350 ysize 64 pos 0,850 background Solid("#00000000") padding 0,0:
            #image "05_gui/gui_menu_option.png" yalign 0.5
            #button action Return ("hull") xpos 20
            #textbutton "Hull (H)" yalign 0.5 action Return("hull") xpos 20 # CR-0587
            #key "h" action Return ("hull")
            #key "h" action Return ("hull")


        #hull plating:
        #####################################################################
        #                SLOTS
        #####################################################################
        
        # armor plating currently in cargo bay
        $ plating_types = ["ITMUnderversePlating", "ITMPhasicPlating", "ITMInferniumPlating", "ITMXenoCeramPlating", "ITMBoronPlating", "ITMDuraniumPlating"]
        
        vbox pos 1780, 600 yanchor 0.5:
          text "   In Cargo" size 20 color "#0ac"
          vpgrid:
            cols 2
                
            for p in plating_types:
                $ platingID = "SS{}".format(plateQuad.title())
                $ itemsP = [x for x in GAME.ship.cargo if p in x.ID]
                $ itemsPCount = len(itemsP)
                    
                if itemsPCount > 0:
                    fixed xysize 52,52:
                        image "08_items/ico {}.png".format(p) zoom 0.125 xoffset -7
                        #if itemsPCount > 1:
                        text str(itemsPCount) size 20 xalign 1.0 yalign 1.0  yoffset 5
                        button action NullAction() tooltip p
        
        
        
        
        $ platePos = {"bow":[1375, 630], "stern":[1375, 930], "starboard": [1760, 715], "port": [1250, 715]}
        
        
        text C_HI_B+"HULL PLATING"+C_HI_E:
            pos 1485, 585

        for i in ["bow", "stern"]:
            $ posX = platePos[i][0]
            $ posY = platePos[i][1]
            hbox pos posX, posY spacing 18:
                for j in range(6):
                
                    $ plateQuad = i
                    $ plateSlot = j  
                     
                    frame xsize 48 ysize 48:
                        $ slot = GAME.ship.subSys_NEW["SS"+i.title()].slotsPlating[j]
                        if slot != None:
                            image "08_items/ico {}.png".format(slot.ID) zoom 0.125 xalign 0.5 yalign 0.5
                            button action (Play("sound", "audio/click.wav"), Show("plating_popup_screen", plateQuad=plateQuad, plateSlot=plateSlot)) tooltip slot.ID
                            
                        else:
                            text " "
                            button action (Play("sound", "audio/click.wav"), Show("plating_popup_screen", plateQuad=plateQuad, plateSlot=plateSlot))
                            

        for i in ["port", "starboard"]:
            $ posX = platePos[i][0]
            $ posY = platePos[i][1]
            vbox pos posX, posY spacing -17:
                for j in range(6):
                
                    $ plateQuad = i
                    $ plateSlot = j
                    
                    frame xsize 48 ysize 48:
                        if j % 2 == 1:
                            yoffset -29
                            xoffset 66
                        $ slot = GAME.ship.subSys_NEW["SS"+i.title()].slotsPlating[j]
                        if slot != None:
                            image "08_items/ico {}.png".format(slot.ID) zoom 0.125 xalign 0.5 yalign 0.5
                            button action (Play("sound", "audio/click.wav"), Show("plating_popup_screen", plateQuad=plateQuad, plateSlot=plateSlot)) tooltip slot.ID
                            
                        else:
                            text " "
                            button action (Play("sound", "audio/click.wav"), Show("plating_popup_screen", plateQuad=plateQuad, plateSlot=plateSlot))
                            
             
        #####################################################################
        #                OTHER STATUS DATA
        #####################################################################
        text "{}HULL ABLATION POTENTIAL:{} {:,} GW".format(C_HI_B, C_HI_E, round(GAME.ship.getTotalAblation_NEW(),1)) xpos 1360 ypos 1000 

        #####################################################################
        #                MODE TOGGLE
        #####################################################################
        #frame xsize 350 ysize 64 pos 0,850 background Solid("#00000000") padding 0,0:
            #image "05_gui/gui_menu_option.png" yalign 0.5
            #button action Return ("systems") xpos 20
            #textbutton "Systems (T)" yalign 0.5 action Return("systems") xpos 20 # CR-0587
            #key "t" action Return ("systems")
            #key "t" action Return ("systems")



    $ tooltip = GetTooltip()
    if tooltip and tooltip in GAME.items.keys():
        $ item = GAME.items[tooltip]
        frame pos 555, 850 xsize 550 background Solid ("00a8"): # CR-0251
            text "{} - {}".format(item.getName(["noArt", "cap", "col"]), item.description)  size FSIZE

    #####################################################################
    #                EXIT BUTTON, OPTION KEYS, ...
    #####################################################################
    


    frame xsize 350 ysize 64 pos 0,940 background Solid("#00000000") padding 0,0:
        image "05_gui/gui_menu_option.png" yalign 0.5
        button action Return ("exit") xpos 20
        textbutton "Exit (X)" yalign 0.5 action Return("exit") xpos 20 # CR-0587
        key "x" action Return ("exit")
        key "X" action Return ("exit")
        
    vbox  xalign 0.5 yalign 0.95:
        if maintMode == "systems":
            text "CURSOR R/L = Next/Previous Subsystem" size FSIZE_MED
        else:
            text "Click on Plating Slot to Equip / Unequip" size FSIZE_MED


label mg_maintenance():

    # Initialize
    $ GAME.mc.hasDone("engine")
    $ maintMode = "systems"
    scene room_engine_smart
    show screen header
    $ subSystems = ["engines", "shields", "weapons", "launcher", "mining", "cargo", "hyperdrive", "uplink"]
    while subSystems[0] != GAME.ship.subSysLast:
        $ subSystems = subSystems[1:]+ subSystems[:1]

    # Maintenance Loop
    while True:

        call screen mg_maintenance_scr(subSystems[0], maintMode) # systems, hull
        if _return == "exit":
            $ exit_confirmed = True
            queue sound "audio/click.wav"
            if GAME.ship.cargoLoaded() > GAME.ship.cargoLimit():
                call large_notify("WARNING!", "Your reconfiguration has reduced cargo bay capacity. Cargo items will randomly be eliminated to adjust to safe compression limits.\n\nReconfiguration of your Cargo Compressor System is recommended.", ["Ignore", "Reconfigure"], "08_items/ico ITMCargoMkI.png", "red") from _call_large_notify_77 
                if _return == "Ignore":
                    $ amount = 0
                    while GAME.ship.cargoLoaded() > GAME.ship.cargoLimit():
                        $ item = random.choice(GAME.ship.cargo)
                        $ GAME.ship.cargo.remove(item)
                        $ amount += 1
                    play sound "audio/load.wav"
                    call simple_notify("CARGO ADJUSTMENT", "{} t of cargo eliminated".format(amount), ["Continue"]) from _call_simple_notify_109 
                else:
                    $ exit_confirmed = False
            if exit_confirmed:
                #hide image "03_minigames/bg_maintenance.png"
                if GAME.ship.getSubSysStatus("engines") > 99 and "explorer" not in GAME.mc.achievements:
                    queue sound "audio/success.wav"
                    call large_notify("ACHIEVEMENT GAINED - EXPLORER", "Congratulations, you have brought your engines up to 100 percent performance!\n\nYou can now access the farthest reaches of this system.", ["Continue"], "08_items/ico ITMCup.png", "pink") from _call_large_notify_78 
                    $ GAME.mc.achievements.append("explorer")    
                #call quest_updater()  # CR-0321          
                return()

        elif _return == "hull":
            if not GAME.questSys.isDone("QID_INTRO_ENGINE"):
                queue sound "audio/beep.wav"
                bb2 "\"We should not concern ourselves with the Hull Plating at the moment...\""
                bb2 "\"Activating the engine should be top priority, Captain [GAME.mc.name]...\""
                mc "\"Ah, right...\""
            else:
                $ maintMode = "hull"
                queue sound "audio/click.wav"

        elif _return == "systems":
            $ maintMode = "systems"
            queue sound "audio/click.wav"
            
        elif "plating" in _return:
        
            queue sound "audio/click.wav"
            
            $ plateType = _return[1]
            $ platingID = "SS{}".format(_return[2].title())
            $ platePos = _return[3]
            
            #"[plateType]"
            
            if plateType == "Empty":
                if GAME.ship.subSys_NEW[platingID].slotsPlating[platePos] == None:
                    pass
                else:
            
                    $ itemP = GAME.ship.subSys_NEW[platingID].slotsPlating[platePos].ID
                    $ GAME.ship.cargo.append(GAME.items[itemP])
                    $ GAME.ship.subSys_NEW[platingID].slotsPlating[platePos] = None
                    #play sound "audio/install.wav"
                
                           
            # if chosen plateType already installed:
            
            else:
                if GAME.ship.subSys_NEW[platingID].slotsPlating[platePos] != None:
                    if GAME.ship.subSys_NEW[platingID].slotsPlating[platePos].ID == plateType:
                        play sound "audio/tech_success.wav"
                
            
                    else: #if GAME.ship.subSys_NEW[platingID].slotsPlating[platePos] != plateType:
                        $ itemP = GAME.ship.subSys_NEW[platingID].slotsPlating[platePos].ID
                        $ GAME.ship.cargo.append(GAME.items[itemP])
                        $ GAME.ship.subSys_NEW[platingID].slotsPlating[platePos] = None
                
                        $ GAME.ship.cargo.remove(GAME.items[plateType])
                        $ item = GAME.items[plateType]
                        $ GAME.ship.subSys_NEW[platingID].slotsPlating[platePos] = item
                        play sound "audio/install.wav"
                
                else: #if GAME.ship.subSys_NEW[platingID].slotsPlating[platePos] == None:
                
                    $ GAME.ship.cargo.remove(GAME.items[plateType])
                    $ item = GAME.items[plateType]
                    $ GAME.ship.subSys_NEW[platingID].slotsPlating[platePos] = item
                    play sound "audio/install.wav"
                
            
            
            #if plateType in GAME.ship.cargo:
                # get available plates from cargo 
                #$ plates = [x for x in GAME.ship.cargo if plateType in x.ID]
                #call screen item_show_scr(plates, "SELECT PLATE TO MOUNT")
                #$ item = _return
                # if plate selected
                #if item:
                    # equip new plate (autouneqip existing to cargo, paranoid)
                    #$ GAME.ship.equipPlating_NEW(platingID, item.ID, platePos)
                    #$ GAME.ship.equipPlating_NEW(platingID, plateType, platePos)
                    #play sound "audio/install.wav"
                    
            hide screen plating_popup_screen

        elif "left" in _return:
            play sound "audio/click.wav"
            $ subSystems = subSystems[1:]+ subSystems[:1]
            $ GAME.ship.subSysLast = subSystems[0]
        elif "right" in _return:
            play sound "audio/click.wav"
            $ subSystems = subSystems[-1:]+ subSystems[:-1]
            $ GAME.ship.subSysLast = subSystems[0]
        
        #OhWee_Mod_Code
        
        elif "systype" in _return:
            $spos = _return[1]
            play sound "audio/click.wav"
            $ s_ind = subSystems.index(spos)
            $ subSystems.pop(s_ind)
            $ subSystems.insert(0, spos)
            
        elif "subunit2" in _return and GAME.ship.hasSubSys(subSystems[0]):
        
            $ sub_slot = _return[1]
            $ matrixPos2 = _return[2]
            $ itemID = _return[3]
            #$ itemID = {0: "ITMAICore", 1: "ITMPositron", 2:"ITMFlux", 3:"ITMOutput"}[matrixPos2[1]]
          

            if sub_slot == 0:
            
                if subSys[subSystems[0]][matrixPos2[0]+1][matrixPos2[1]] == 1:
                    play sound "audio/tech_fail.wav"
                    $ GAME.ship.cargo.append(GAME.items[itemID])
                    $ subSys[subSystems[0]][matrixPos2[0]+1][matrixPos2[1]] = 0
        
                elif subSys[subSystems[0]][matrixPos2[0]+1][matrixPos2[1]] == 9:
                    play sound "audio/tech_fail.wav"
                    $ GAME.ship.cargo.append(GAME.items["ITMTunneling"])
                    $ subSys[subSystems[0]][matrixPos2[0]+1][matrixPos2[1]] = 0
        
                else:
                    play sound "audio/tech_fail.wav"
                    $ subSys[subSystems[0]][matrixPos2[0]+1][matrixPos2[1]] = 0
            
            
            elif sub_slot == 1:

                if subSys[subSystems[0]][matrixPos2[0]+1][matrixPos2[1]] == 1:
                    pass
        
                elif subSys[subSystems[0]][matrixPos2[0]+1][matrixPos2[1]] == 9:
                    $ GAME.ship.cargo.append(GAME.items["ITMTunneling"])
        
                    $ subSys[subSystems[0]][matrixPos2[0]+1][matrixPos2[1]] = 1
                    $ GAME.ship.cargo.remove(GAME.items[itemID])
        
                else: #if empty
    
                    $ GAME.ship.cargo.remove(GAME.items[itemID])
                    $ subSys[subSystems[0]][matrixPos2[0]+1][matrixPos2[1]] = 1

    
            elif sub_slot == 9:
    
                if subSys[subSystems[0]][matrixPos2[0]+1][matrixPos2[1]] == 9:
                    pass
        
                elif subSys[subSystems[0]][matrixPos2[0]+1][matrixPos2[1]] == 1:
                    $ GAME.ship.cargo.append(GAME.items[itemID])
        
                    $ subSys[subSystems[0]][matrixPos2[0]+1][matrixPos2[1]] = 9
                    $ GAME.ship.cargo.remove(GAME.items["ITMTunneling"])
        
                else: #if empty
    
                    $ GAME.ship.cargo.remove(GAME.items["ITMTunneling"])
                    $ subSys[subSystems[0]][matrixPos2[0]+1][matrixPos2[1]] = 9
                    
            else:
                pass

            #$ subSys[subSysKey][matrixPos2[0]+1][matrixPos2[1]] = sub_slot
    

            if GAME.ship.pathClosed(subSystems[0], matrixPos2[0]):
                play sound "audio/tech_success.wav"
            else:
                play sound "audio/tech_fail.wav"
                
            hide screen subunit_popup_screen
            
            #$subSysText = str(subSys[subSystems[0]][matrixPos2[0]+1][matrixPos2[1]])
            #"Sub_slot [sub_slot] - [subSysText]"
            
            $ result = _return
            #return()           
            
        #End OhWee_Mod_Code
        

        elif "subunit" in _return and GAME.ship.hasSubSys(subSystems[0]):
            play sound "audio/click.wav"
            # if occupied uninstall
            $ matrixPos = _return[2]
            $ itemID = {0: "ITMAICore", 1: "ITMPositron", 2:"ITMFlux", 3:"ITMOutput"}[matrixPos[1]]
            
            if _return[1]:

                play sound "audio/install.wav"
                $ GAME.ship.uninstallSubunit(subSystems[0], matrixPos)

            # if empty select install
            else:
                hide screen header
                # CR-2105 START
                $ itemIDsEmphasize = [itemID, "ITMTunneling"]
                call item_show(GAME.ship.cargo, [], "CARGO - SUBUNITS", [], ["ITMAICore", "ITMPositron","ITMFlux",  "ITMOutput", "ITMTunneling"], itemIDsEmphasize) from _call_item_show_3 
                # call item_show(GAME.ship.cargo, [], "CARGO - SUBUNITS", [], [itemID, "ITMTunneling"]) 
                # CR-2105 END

                if _return:
                    $ item = _return
                    # install
                    $ output = GAME.ship.getSubSysStatus(subSystems[0])
                    $ result = GAME.ship.installSubunit(subSystems[0], item.ID, matrixPos)
                    if result:
                        if GAME.ship.getSubSysStatus(subSystems[0]) > output:
                            play sound "audio/tech_success.wav"
                        else:
                            play sound "audio/install.wav"

                    else:
                        play sound "audio/tech_fail.wav"
                        mc "\"I think this subunit belongs elsewhere...\""
                #show image "03_minigames/bg_maintenance.png"
                show screen header
        # ======== DEPRECATED
        elif "loadout" in _return: # 
            $ slot = _return[1]
            if GAME.ship.loadout[slot]:  # uninstall
                queue sound "audio/install.wav"
                $ GAME.ship.loadWare(GAME.ship.loadout[slot].ID)
                $ GAME.ship.loadout[slot] = False
            else: # install
                show image "room_engine_smart"
                call item_show(GAME.ship.cargo, ["torpedo"], "CARGO - TORPEDOES") from _call_item_show_4 
                hide image "room_engine_smart"            
                $ torp = _return
                if torp:
                    queue sound "audio/install.wav"
                    $ GAME.ship.loadout[slot] = torp 
                    $ GAME.ship.unloadWare(torp.ID)
        # ========
        elif "addon" 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_5 
                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"

        else:
            play sound "audio/tech_fail.wav"
            #"[_return]"

    return()
